kallsyms.c 15 KB

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