kallsyms.c 16 KB

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