kallsyms.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  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 (%lu 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_text - %#llx\n",
  290. _text - table[i].addr);
  291. } else {
  292. printf("\tPTR\t%#llx\n", table[i].addr);
  293. }
  294. }
  295. printf("\n");
  296. output_label("kallsyms_num_syms");
  297. printf("\tPTR\t%d\n", table_cnt);
  298. printf("\n");
  299. /* table of offset markers, that give the offset in the compressed stream
  300. * every 256 symbols */
  301. markers = malloc(sizeof(unsigned int) * ((table_cnt + 255) / 256));
  302. if (!markers) {
  303. fprintf(stderr, "kallsyms failure: "
  304. "unable to allocate required memory\n");
  305. exit(EXIT_FAILURE);
  306. }
  307. output_label("kallsyms_names");
  308. off = 0;
  309. for (i = 0; i < table_cnt; i++) {
  310. if ((i & 0xFF) == 0)
  311. markers[i >> 8] = off;
  312. printf("\t.byte 0x%02x", table[i].len);
  313. for (k = 0; k < table[i].len; k++)
  314. printf(", 0x%02x", table[i].sym[k]);
  315. printf("\n");
  316. off += table[i].len + 1;
  317. }
  318. printf("\n");
  319. output_label("kallsyms_markers");
  320. for (i = 0; i < ((table_cnt + 255) >> 8); i++)
  321. printf("\tPTR\t%d\n", markers[i]);
  322. printf("\n");
  323. free(markers);
  324. output_label("kallsyms_token_table");
  325. off = 0;
  326. for (i = 0; i < 256; i++) {
  327. best_idx[i] = off;
  328. expand_symbol(best_table[i], best_table_len[i], buf);
  329. printf("\t.asciz\t\"%s\"\n", buf);
  330. off += strlen(buf) + 1;
  331. }
  332. printf("\n");
  333. output_label("kallsyms_token_index");
  334. for (i = 0; i < 256; i++)
  335. printf("\t.short\t%d\n", best_idx[i]);
  336. printf("\n");
  337. }
  338. /* table lookup compression functions */
  339. /* count all the possible tokens in a symbol */
  340. static void learn_symbol(unsigned char *symbol, int len)
  341. {
  342. int i;
  343. for (i = 0; i < len - 1; i++)
  344. token_profit[ symbol[i] + (symbol[i + 1] << 8) ]++;
  345. }
  346. /* decrease the count for all the possible tokens in a symbol */
  347. static void forget_symbol(unsigned char *symbol, int len)
  348. {
  349. int i;
  350. for (i = 0; i < len - 1; i++)
  351. token_profit[ symbol[i] + (symbol[i + 1] << 8) ]--;
  352. }
  353. /* remove all the invalid symbols from the table and do the initial token count */
  354. static void build_initial_tok_table(void)
  355. {
  356. unsigned int i, pos;
  357. pos = 0;
  358. for (i = 0; i < table_cnt; i++) {
  359. if ( symbol_valid(&table[i]) ) {
  360. if (pos != i)
  361. table[pos] = table[i];
  362. learn_symbol(table[pos].sym, table[pos].len);
  363. pos++;
  364. }
  365. }
  366. table_cnt = pos;
  367. }
  368. static void *find_token(unsigned char *str, int len, unsigned char *token)
  369. {
  370. int i;
  371. for (i = 0; i < len - 1; i++) {
  372. if (str[i] == token[0] && str[i+1] == token[1])
  373. return &str[i];
  374. }
  375. return NULL;
  376. }
  377. /* replace a given token in all the valid symbols. Use the sampled symbols
  378. * to update the counts */
  379. static void compress_symbols(unsigned char *str, int idx)
  380. {
  381. unsigned int i, len, size;
  382. unsigned char *p1, *p2;
  383. for (i = 0; i < table_cnt; i++) {
  384. len = table[i].len;
  385. p1 = table[i].sym;
  386. /* find the token on the symbol */
  387. p2 = find_token(p1, len, str);
  388. if (!p2) continue;
  389. /* decrease the counts for this symbol's tokens */
  390. forget_symbol(table[i].sym, len);
  391. size = len;
  392. do {
  393. *p2 = idx;
  394. p2++;
  395. size -= (p2 - p1);
  396. memmove(p2, p2 + 1, size);
  397. p1 = p2;
  398. len--;
  399. if (size < 2) break;
  400. /* find the token on the symbol */
  401. p2 = find_token(p1, size, str);
  402. } while (p2);
  403. table[i].len = len;
  404. /* increase the counts for this symbol's new tokens */
  405. learn_symbol(table[i].sym, len);
  406. }
  407. }
  408. /* search the token with the maximum profit */
  409. static int find_best_token(void)
  410. {
  411. int i, best, bestprofit;
  412. bestprofit=-10000;
  413. best = 0;
  414. for (i = 0; i < 0x10000; i++) {
  415. if (token_profit[i] > bestprofit) {
  416. best = i;
  417. bestprofit = token_profit[i];
  418. }
  419. }
  420. return best;
  421. }
  422. /* this is the core of the algorithm: calculate the "best" table */
  423. static void optimize_result(void)
  424. {
  425. int i, best;
  426. /* using the '\0' symbol last allows compress_symbols to use standard
  427. * fast string functions */
  428. for (i = 255; i >= 0; i--) {
  429. /* if this table slot is empty (it is not used by an actual
  430. * original char code */
  431. if (!best_table_len[i]) {
  432. /* find the token with the breates profit value */
  433. best = find_best_token();
  434. if (token_profit[best] == 0)
  435. break;
  436. /* place it in the "best" table */
  437. best_table_len[i] = 2;
  438. best_table[i][0] = best & 0xFF;
  439. best_table[i][1] = (best >> 8) & 0xFF;
  440. /* replace this token in all the valid symbols */
  441. compress_symbols(best_table[i], i);
  442. }
  443. }
  444. }
  445. /* start by placing the symbols that are actually used on the table */
  446. static void insert_real_symbols_in_table(void)
  447. {
  448. unsigned int i, j, c;
  449. memset(best_table, 0, sizeof(best_table));
  450. memset(best_table_len, 0, sizeof(best_table_len));
  451. for (i = 0; i < table_cnt; i++) {
  452. for (j = 0; j < table[i].len; j++) {
  453. c = table[i].sym[j];
  454. best_table[c][0]=c;
  455. best_table_len[c]=1;
  456. }
  457. }
  458. }
  459. static void optimize_token_table(void)
  460. {
  461. build_initial_tok_table();
  462. insert_real_symbols_in_table();
  463. /* When valid symbol is not registered, exit to error */
  464. if (!table_cnt) {
  465. fprintf(stderr, "No valid symbol.\n");
  466. exit(1);
  467. }
  468. optimize_result();
  469. }
  470. /* guess for "linker script provide" symbol */
  471. static int may_be_linker_script_provide_symbol(const struct sym_entry *se)
  472. {
  473. const char *symbol = (char *)se->sym + 1;
  474. int len = se->len - 1;
  475. if (len < 8)
  476. return 0;
  477. if (symbol[0] != '_' || symbol[1] != '_')
  478. return 0;
  479. /* __start_XXXXX */
  480. if (!memcmp(symbol + 2, "start_", 6))
  481. return 1;
  482. /* __stop_XXXXX */
  483. if (!memcmp(symbol + 2, "stop_", 5))
  484. return 1;
  485. /* __end_XXXXX */
  486. if (!memcmp(symbol + 2, "end_", 4))
  487. return 1;
  488. /* __XXXXX_start */
  489. if (!memcmp(symbol + len - 6, "_start", 6))
  490. return 1;
  491. /* __XXXXX_end */
  492. if (!memcmp(symbol + len - 4, "_end", 4))
  493. return 1;
  494. return 0;
  495. }
  496. static int prefix_underscores_count(const char *str)
  497. {
  498. const char *tail = str;
  499. while (*tail == '_')
  500. tail++;
  501. return tail - str;
  502. }
  503. static int compare_symbols(const void *a, const void *b)
  504. {
  505. const struct sym_entry *sa;
  506. const struct sym_entry *sb;
  507. int wa, wb;
  508. sa = a;
  509. sb = b;
  510. /* sort by address first */
  511. if (sa->addr > sb->addr)
  512. return 1;
  513. if (sa->addr < sb->addr)
  514. return -1;
  515. /* sort by "weakness" type */
  516. wa = (sa->sym[0] == 'w') || (sa->sym[0] == 'W');
  517. wb = (sb->sym[0] == 'w') || (sb->sym[0] == 'W');
  518. if (wa != wb)
  519. return wa - wb;
  520. /* sort by "linker script provide" type */
  521. wa = may_be_linker_script_provide_symbol(sa);
  522. wb = may_be_linker_script_provide_symbol(sb);
  523. if (wa != wb)
  524. return wa - wb;
  525. /* sort by the number of prefix underscores */
  526. wa = prefix_underscores_count((const char *)sa->sym + 1);
  527. wb = prefix_underscores_count((const char *)sb->sym + 1);
  528. if (wa != wb)
  529. return wa - wb;
  530. /* sort by initial order, so that other symbols are left undisturbed */
  531. return sa->start_pos - sb->start_pos;
  532. }
  533. static void sort_symbols(void)
  534. {
  535. qsort(table, table_cnt, sizeof(struct sym_entry), compare_symbols);
  536. }
  537. int main(int argc, char **argv)
  538. {
  539. if (argc >= 2) {
  540. int i;
  541. for (i = 1; i < argc; i++) {
  542. if(strcmp(argv[i], "--all-symbols") == 0)
  543. all_symbols = 1;
  544. else if (strncmp(argv[i], "--symbol-prefix=", 16) == 0) {
  545. char *p = &argv[i][16];
  546. /* skip quote */
  547. if ((*p == '"' && *(p+2) == '"') || (*p == '\'' && *(p+2) == '\''))
  548. p++;
  549. symbol_prefix_char = *p;
  550. } else if (strncmp(argv[i], "--page-offset=", 14) == 0) {
  551. const char *p = &argv[i][14];
  552. kernel_start_addr = strtoull(p, NULL, 16);
  553. } else
  554. usage();
  555. }
  556. } else if (argc != 1)
  557. usage();
  558. read_map(stdin);
  559. sort_symbols();
  560. optimize_token_table();
  561. write_src();
  562. return 0;
  563. }