kallsyms.c 16 KB

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