kallsyms.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. /* Generate assembler source containing symbol information
  2. *
  3. * Copyright 2002 by Kai Germaschewski
  4. *
  5. * This software may be used and distributed according to the terms
  6. * of the GNU General Public License, incorporated herein by reference.
  7. *
  8. * Usage: nm -n vmlinux | scripts/kallsyms [--all-symbols] > symbols.S
  9. *
  10. * Table compression uses all the unused char codes on the symbols and
  11. * maps these to the most used substrings (tokens). For instance, it might
  12. * map char code 0xF7 to represent "write_" and then in every symbol where
  13. * "write_" appears it can be replaced by 0xF7, saving 5 bytes.
  14. * The used codes themselves are also placed in the table so that the
  15. * decompresion can work without "special cases".
  16. * Applied to kernel symbols, this usually produces a compression ratio
  17. * of about 50%.
  18. *
  19. */
  20. #include <stdio.h>
  21. #include <stdlib.h>
  22. #include <string.h>
  23. #include <ctype.h>
  24. #define KSYM_NAME_LEN 128
  25. struct sym_entry {
  26. unsigned long long addr;
  27. unsigned int len;
  28. unsigned int start_pos;
  29. unsigned char *sym;
  30. };
  31. static struct sym_entry *table;
  32. static unsigned int table_size, table_cnt;
  33. static unsigned long long _text, _stext, _etext, _sinittext, _einittext;
  34. static int all_symbols = 0;
  35. static char symbol_prefix_char = '\0';
  36. int token_profit[0x10000];
  37. /* the table that holds the result of the compression */
  38. unsigned char best_table[256][2];
  39. unsigned char best_table_len[256];
  40. static void usage(void)
  41. {
  42. fprintf(stderr, "Usage: kallsyms [--all-symbols] [--symbol-prefix=<prefix char>] < in.map > out.S\n");
  43. exit(1);
  44. }
  45. /*
  46. * This ignores the intensely annoying "mapping symbols" found
  47. * in ARM ELF files: $a, $t and $d.
  48. */
  49. static inline int is_arm_mapping_symbol(const char *str)
  50. {
  51. return str[0] == '$' && strchr("atd", str[1])
  52. && (str[2] == '\0' || str[2] == '.');
  53. }
  54. static int read_symbol(FILE *in, struct sym_entry *s)
  55. {
  56. char str[500];
  57. char *sym, stype;
  58. int rc;
  59. rc = fscanf(in, "%llx %c %499s\n", &s->addr, &stype, str);
  60. if (rc != 3) {
  61. if (rc != EOF) {
  62. /* skip line */
  63. fgets(str, 500, in);
  64. }
  65. return -1;
  66. }
  67. sym = str;
  68. /* skip prefix char */
  69. if (symbol_prefix_char && str[0] == symbol_prefix_char)
  70. sym++;
  71. /* Ignore most absolute/undefined (?) symbols. */
  72. if (strcmp(sym, "_text") == 0)
  73. _text = s->addr;
  74. else if (strcmp(sym, "_stext") == 0)
  75. _stext = s->addr;
  76. else if (strcmp(sym, "_etext") == 0)
  77. _etext = s->addr;
  78. else if (strcmp(sym, "_sinittext") == 0)
  79. _sinittext = s->addr;
  80. else if (strcmp(sym, "_einittext") == 0)
  81. _einittext = s->addr;
  82. else if (toupper(stype) == 'A')
  83. {
  84. /* Keep these useful absolute symbols */
  85. if (strcmp(sym, "__kernel_syscall_via_break") &&
  86. strcmp(sym, "__kernel_syscall_via_epc") &&
  87. strcmp(sym, "__kernel_sigtramp") &&
  88. strcmp(sym, "__gp"))
  89. return -1;
  90. }
  91. else if (toupper(stype) == 'U' ||
  92. is_arm_mapping_symbol(sym))
  93. return -1;
  94. /* exclude also MIPS ELF local symbols ($L123 instead of .L123) */
  95. else if (str[0] == '$')
  96. return -1;
  97. /* exclude debugging symbols */
  98. else if (stype == 'N')
  99. return -1;
  100. /* include the type field in the symbol name, so that it gets
  101. * compressed together */
  102. s->len = strlen(str) + 1;
  103. s->sym = malloc(s->len + 1);
  104. if (!s->sym) {
  105. fprintf(stderr, "kallsyms failure: "
  106. "unable to allocate required amount of memory\n");
  107. exit(EXIT_FAILURE);
  108. }
  109. strcpy((char *)s->sym + 1, str);
  110. s->sym[0] = stype;
  111. return 0;
  112. }
  113. static int symbol_valid(struct sym_entry *s)
  114. {
  115. /* Symbols which vary between passes. Passes 1 and 2 must have
  116. * identical symbol lists.
  117. */
  118. static char *special_symbols[] = {
  119. /* Exclude linker generated symbols which vary between passes */
  120. "_SDA_BASE_", /* ppc */
  121. "_SDA2_BASE_", /* ppc */
  122. NULL };
  123. int i;
  124. int offset = 1;
  125. /* skip prefix char */
  126. if (symbol_prefix_char && *(s->sym + 1) == symbol_prefix_char)
  127. offset++;
  128. /* if --all-symbols is not specified, then symbols outside the text
  129. * and inittext sections are discarded */
  130. if (!all_symbols) {
  131. if ((s->addr < _stext || s->addr > _etext)
  132. && (s->addr < _sinittext || s->addr > _einittext))
  133. return 0;
  134. /* Corner case. Discard any symbols with the same value as
  135. * _etext _einittext; they can move between pass 1 and 2 when
  136. * the kallsyms data are added. If these symbols move then
  137. * they may get dropped in pass 2, which breaks the kallsyms
  138. * rules.
  139. */
  140. if ((s->addr == _etext &&
  141. strcmp((char *)s->sym + offset, "_etext")) ||
  142. (s->addr == _einittext &&
  143. strcmp((char *)s->sym + offset, "_einittext")))
  144. return 0;
  145. }
  146. /* Exclude symbols which vary between passes. */
  147. if (strstr((char *)s->sym + offset, "_compiled.") ||
  148. strncmp((char*)s->sym + offset, "__compound_literal.", 19) == 0 ||
  149. strncmp((char*)s->sym + offset, "__compound_literal$", 19) == 0)
  150. return 0;
  151. for (i = 0; special_symbols[i]; i++)
  152. if( strcmp((char *)s->sym + offset, special_symbols[i]) == 0 )
  153. return 0;
  154. return 1;
  155. }
  156. static void read_map(FILE *in)
  157. {
  158. while (!feof(in)) {
  159. if (table_cnt >= table_size) {
  160. table_size += 10000;
  161. table = realloc(table, sizeof(*table) * table_size);
  162. if (!table) {
  163. fprintf(stderr, "out of memory\n");
  164. exit (1);
  165. }
  166. }
  167. if (read_symbol(in, &table[table_cnt]) == 0) {
  168. table[table_cnt].start_pos = table_cnt;
  169. table_cnt++;
  170. }
  171. }
  172. }
  173. static void output_label(char *label)
  174. {
  175. if (symbol_prefix_char)
  176. printf(".globl %c%s\n", symbol_prefix_char, label);
  177. else
  178. printf(".globl %s\n", label);
  179. printf("\tALGN\n");
  180. if (symbol_prefix_char)
  181. printf("%c%s:\n", symbol_prefix_char, label);
  182. else
  183. printf("%s:\n", label);
  184. }
  185. /* uncompress a compressed symbol. When this function is called, the best table
  186. * might still be compressed itself, so the function needs to be recursive */
  187. static int expand_symbol(unsigned char *data, int len, char *result)
  188. {
  189. int c, rlen, total=0;
  190. while (len) {
  191. c = *data;
  192. /* if the table holds a single char that is the same as the one
  193. * we are looking for, then end the search */
  194. if (best_table[c][0]==c && best_table_len[c]==1) {
  195. *result++ = c;
  196. total++;
  197. } else {
  198. /* if not, recurse and expand */
  199. rlen = expand_symbol(best_table[c], best_table_len[c], result);
  200. total += rlen;
  201. result += rlen;
  202. }
  203. data++;
  204. len--;
  205. }
  206. *result=0;
  207. return total;
  208. }
  209. static void write_src(void)
  210. {
  211. unsigned int i, k, off;
  212. unsigned int best_idx[256];
  213. unsigned int *markers;
  214. char buf[KSYM_NAME_LEN];
  215. printf("#include <asm/types.h>\n");
  216. printf("#if BITS_PER_LONG == 64\n");
  217. printf("#define PTR .quad\n");
  218. printf("#define ALGN .align 8\n");
  219. printf("#else\n");
  220. printf("#define PTR .long\n");
  221. printf("#define ALGN .align 4\n");
  222. printf("#endif\n");
  223. printf("\t.section .rodata, \"a\"\n");
  224. /* Provide proper symbols relocatability by their '_text'
  225. * relativeness. The symbol names cannot be used to construct
  226. * normal symbol references as the list of symbols contains
  227. * symbols that are declared static and are private to their
  228. * .o files. This prevents .tmp_kallsyms.o or any other
  229. * object from referencing them.
  230. */
  231. output_label("kallsyms_addresses");
  232. for (i = 0; i < table_cnt; i++) {
  233. if (toupper(table[i].sym[0]) != 'A') {
  234. if (_text <= table[i].addr)
  235. printf("\tPTR\t_text + %#llx\n",
  236. table[i].addr - _text);
  237. else
  238. printf("\tPTR\t_text - %#llx\n",
  239. _text - table[i].addr);
  240. } else {
  241. printf("\tPTR\t%#llx\n", table[i].addr);
  242. }
  243. }
  244. printf("\n");
  245. output_label("kallsyms_num_syms");
  246. printf("\tPTR\t%d\n", table_cnt);
  247. printf("\n");
  248. /* table of offset markers, that give the offset in the compressed stream
  249. * every 256 symbols */
  250. markers = malloc(sizeof(unsigned int) * ((table_cnt + 255) / 256));
  251. if (!markers) {
  252. fprintf(stderr, "kallsyms failure: "
  253. "unable to allocate required memory\n");
  254. exit(EXIT_FAILURE);
  255. }
  256. output_label("kallsyms_names");
  257. off = 0;
  258. for (i = 0; i < table_cnt; i++) {
  259. if ((i & 0xFF) == 0)
  260. markers[i >> 8] = off;
  261. printf("\t.byte 0x%02x", table[i].len);
  262. for (k = 0; k < table[i].len; k++)
  263. printf(", 0x%02x", table[i].sym[k]);
  264. printf("\n");
  265. off += table[i].len + 1;
  266. }
  267. printf("\n");
  268. output_label("kallsyms_markers");
  269. for (i = 0; i < ((table_cnt + 255) >> 8); i++)
  270. printf("\tPTR\t%d\n", markers[i]);
  271. printf("\n");
  272. free(markers);
  273. output_label("kallsyms_token_table");
  274. off = 0;
  275. for (i = 0; i < 256; i++) {
  276. best_idx[i] = off;
  277. expand_symbol(best_table[i], best_table_len[i], buf);
  278. printf("\t.asciz\t\"%s\"\n", buf);
  279. off += strlen(buf) + 1;
  280. }
  281. printf("\n");
  282. output_label("kallsyms_token_index");
  283. for (i = 0; i < 256; i++)
  284. printf("\t.short\t%d\n", best_idx[i]);
  285. printf("\n");
  286. }
  287. /* table lookup compression functions */
  288. /* count all the possible tokens in a symbol */
  289. static void learn_symbol(unsigned char *symbol, int len)
  290. {
  291. int i;
  292. for (i = 0; i < len - 1; i++)
  293. token_profit[ symbol[i] + (symbol[i + 1] << 8) ]++;
  294. }
  295. /* decrease the count for all the possible tokens in a symbol */
  296. static void forget_symbol(unsigned char *symbol, int len)
  297. {
  298. int i;
  299. for (i = 0; i < len - 1; i++)
  300. token_profit[ symbol[i] + (symbol[i + 1] << 8) ]--;
  301. }
  302. /* remove all the invalid symbols from the table and do the initial token count */
  303. static void build_initial_tok_table(void)
  304. {
  305. unsigned int i, pos;
  306. pos = 0;
  307. for (i = 0; i < table_cnt; i++) {
  308. if ( symbol_valid(&table[i]) ) {
  309. if (pos != i)
  310. table[pos] = table[i];
  311. learn_symbol(table[pos].sym, table[pos].len);
  312. pos++;
  313. }
  314. }
  315. table_cnt = pos;
  316. }
  317. static void *find_token(unsigned char *str, int len, unsigned char *token)
  318. {
  319. int i;
  320. for (i = 0; i < len - 1; i++) {
  321. if (str[i] == token[0] && str[i+1] == token[1])
  322. return &str[i];
  323. }
  324. return NULL;
  325. }
  326. /* replace a given token in all the valid symbols. Use the sampled symbols
  327. * to update the counts */
  328. static void compress_symbols(unsigned char *str, int idx)
  329. {
  330. unsigned int i, len, size;
  331. unsigned char *p1, *p2;
  332. for (i = 0; i < table_cnt; i++) {
  333. len = table[i].len;
  334. p1 = table[i].sym;
  335. /* find the token on the symbol */
  336. p2 = find_token(p1, len, str);
  337. if (!p2) continue;
  338. /* decrease the counts for this symbol's tokens */
  339. forget_symbol(table[i].sym, len);
  340. size = len;
  341. do {
  342. *p2 = idx;
  343. p2++;
  344. size -= (p2 - p1);
  345. memmove(p2, p2 + 1, size);
  346. p1 = p2;
  347. len--;
  348. if (size < 2) break;
  349. /* find the token on the symbol */
  350. p2 = find_token(p1, size, str);
  351. } while (p2);
  352. table[i].len = len;
  353. /* increase the counts for this symbol's new tokens */
  354. learn_symbol(table[i].sym, len);
  355. }
  356. }
  357. /* search the token with the maximum profit */
  358. static int find_best_token(void)
  359. {
  360. int i, best, bestprofit;
  361. bestprofit=-10000;
  362. best = 0;
  363. for (i = 0; i < 0x10000; i++) {
  364. if (token_profit[i] > bestprofit) {
  365. best = i;
  366. bestprofit = token_profit[i];
  367. }
  368. }
  369. return best;
  370. }
  371. /* this is the core of the algorithm: calculate the "best" table */
  372. static void optimize_result(void)
  373. {
  374. int i, best;
  375. /* using the '\0' symbol last allows compress_symbols to use standard
  376. * fast string functions */
  377. for (i = 255; i >= 0; i--) {
  378. /* if this table slot is empty (it is not used by an actual
  379. * original char code */
  380. if (!best_table_len[i]) {
  381. /* find the token with the breates profit value */
  382. best = find_best_token();
  383. /* place it in the "best" table */
  384. best_table_len[i] = 2;
  385. best_table[i][0] = best & 0xFF;
  386. best_table[i][1] = (best >> 8) & 0xFF;
  387. /* replace this token in all the valid symbols */
  388. compress_symbols(best_table[i], i);
  389. }
  390. }
  391. }
  392. /* start by placing the symbols that are actually used on the table */
  393. static void insert_real_symbols_in_table(void)
  394. {
  395. unsigned int i, j, c;
  396. memset(best_table, 0, sizeof(best_table));
  397. memset(best_table_len, 0, sizeof(best_table_len));
  398. for (i = 0; i < table_cnt; i++) {
  399. for (j = 0; j < table[i].len; j++) {
  400. c = table[i].sym[j];
  401. best_table[c][0]=c;
  402. best_table_len[c]=1;
  403. }
  404. }
  405. }
  406. static void optimize_token_table(void)
  407. {
  408. build_initial_tok_table();
  409. insert_real_symbols_in_table();
  410. /* When valid symbol is not registered, exit to error */
  411. if (!table_cnt) {
  412. fprintf(stderr, "No valid symbol.\n");
  413. exit(1);
  414. }
  415. optimize_result();
  416. }
  417. static int compare_symbols(const void *a, const void *b)
  418. {
  419. const struct sym_entry *sa;
  420. const struct sym_entry *sb;
  421. int wa, wb;
  422. sa = a;
  423. sb = b;
  424. /* sort by address first */
  425. if (sa->addr > sb->addr)
  426. return 1;
  427. if (sa->addr < sb->addr)
  428. return -1;
  429. /* sort by "weakness" type */
  430. wa = (sa->sym[0] == 'w') || (sa->sym[0] == 'W');
  431. wb = (sb->sym[0] == 'w') || (sb->sym[0] == 'W');
  432. if (wa != wb)
  433. return wa - wb;
  434. /* sort by initial order, so that other symbols are left undisturbed */
  435. return sa->start_pos - sb->start_pos;
  436. }
  437. static void sort_symbols(void)
  438. {
  439. qsort(table, table_cnt, sizeof(struct sym_entry), compare_symbols);
  440. }
  441. int main(int argc, char **argv)
  442. {
  443. if (argc >= 2) {
  444. int i;
  445. for (i = 1; i < argc; i++) {
  446. if(strcmp(argv[i], "--all-symbols") == 0)
  447. all_symbols = 1;
  448. else if (strncmp(argv[i], "--symbol-prefix=", 16) == 0) {
  449. char *p = &argv[i][16];
  450. /* skip quote */
  451. if ((*p == '"' && *(p+2) == '"') || (*p == '\'' && *(p+2) == '\''))
  452. p++;
  453. symbol_prefix_char = *p;
  454. } else
  455. usage();
  456. }
  457. } else if (argc != 1)
  458. usage();
  459. read_map(stdin);
  460. if (table_cnt) {
  461. sort_symbols();
  462. optimize_token_table();
  463. }
  464. write_src();
  465. return 0;
  466. }