kallsyms.c 15 KB

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