kallsyms.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  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: kallsyms [--all-symbols] in.map > out.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 <errno.h>
  21. #include <getopt.h>
  22. #include <stdbool.h>
  23. #include <stdio.h>
  24. #include <stdlib.h>
  25. #include <string.h>
  26. #include <ctype.h>
  27. #include <limits.h>
  28. #include <xalloc.h>
  29. #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
  30. #define KSYM_NAME_LEN 512
  31. struct sym_entry {
  32. unsigned long long addr;
  33. unsigned int len;
  34. unsigned int seq;
  35. unsigned char sym[];
  36. };
  37. struct addr_range {
  38. const char *start_sym, *end_sym;
  39. unsigned long long start, end;
  40. };
  41. static unsigned long long _text;
  42. static struct addr_range text_ranges[] = {
  43. { "_stext", "_etext" },
  44. { "_sinittext", "_einittext" },
  45. };
  46. #define text_range_text (&text_ranges[0])
  47. #define text_range_inittext (&text_ranges[1])
  48. static struct sym_entry **table;
  49. static unsigned int table_size, table_cnt;
  50. static int all_symbols;
  51. static int pc_relative;
  52. static int token_profit[0x10000];
  53. /* the table that holds the result of the compression */
  54. static unsigned char best_table[256][2];
  55. static unsigned char best_table_len[256];
  56. static void usage(void)
  57. {
  58. fprintf(stderr, "Usage: kallsyms [--all-symbols] in.map > out.S\n");
  59. exit(1);
  60. }
  61. static char *sym_name(const struct sym_entry *s)
  62. {
  63. return (char *)s->sym + 1;
  64. }
  65. static bool is_ignored_symbol(const char *name, char type)
  66. {
  67. if (type == 'u' || type == 'n')
  68. return true;
  69. if (toupper(type) == 'A') {
  70. /* Keep these useful absolute symbols */
  71. if (strcmp(name, "__kernel_syscall_via_break") &&
  72. strcmp(name, "__kernel_syscall_via_epc") &&
  73. strcmp(name, "__kernel_sigtramp") &&
  74. strcmp(name, "__gp"))
  75. return true;
  76. }
  77. return false;
  78. }
  79. static void check_symbol_range(const char *sym, unsigned long long addr,
  80. struct addr_range *ranges, int entries)
  81. {
  82. size_t i;
  83. struct addr_range *ar;
  84. for (i = 0; i < entries; ++i) {
  85. ar = &ranges[i];
  86. if (strcmp(sym, ar->start_sym) == 0) {
  87. ar->start = addr;
  88. return;
  89. } else if (strcmp(sym, ar->end_sym) == 0) {
  90. ar->end = addr;
  91. return;
  92. }
  93. }
  94. }
  95. static struct sym_entry *read_symbol(FILE *in, char **buf, size_t *buf_len)
  96. {
  97. char *name, type, *p;
  98. unsigned long long addr;
  99. size_t len;
  100. ssize_t readlen;
  101. struct sym_entry *sym;
  102. errno = 0;
  103. readlen = getline(buf, buf_len, in);
  104. if (readlen < 0) {
  105. if (errno) {
  106. perror("read_symbol");
  107. exit(EXIT_FAILURE);
  108. }
  109. return NULL;
  110. }
  111. if ((*buf)[readlen - 1] == '\n')
  112. (*buf)[readlen - 1] = 0;
  113. addr = strtoull(*buf, &p, 16);
  114. if (*buf == p || *p++ != ' ' || !isascii((type = *p++)) || *p++ != ' ') {
  115. fprintf(stderr, "line format error\n");
  116. exit(EXIT_FAILURE);
  117. }
  118. name = p;
  119. len = strlen(name);
  120. if (len >= KSYM_NAME_LEN) {
  121. fprintf(stderr, "Symbol %s too long for kallsyms (%zu >= %d).\n"
  122. "Please increase KSYM_NAME_LEN both in kernel and kallsyms.c\n",
  123. name, len, KSYM_NAME_LEN);
  124. return NULL;
  125. }
  126. if (strcmp(name, "_text") == 0)
  127. _text = addr;
  128. /* Ignore most absolute/undefined (?) symbols. */
  129. if (is_ignored_symbol(name, type))
  130. return NULL;
  131. check_symbol_range(name, addr, text_ranges, ARRAY_SIZE(text_ranges));
  132. /* include the type field in the symbol name, so that it gets
  133. * compressed together */
  134. len++;
  135. sym = xmalloc(sizeof(*sym) + len + 1);
  136. sym->addr = addr;
  137. sym->len = len;
  138. sym->sym[0] = type;
  139. strcpy(sym_name(sym), name);
  140. return sym;
  141. }
  142. static int symbol_in_range(const struct sym_entry *s,
  143. const struct addr_range *ranges, int entries)
  144. {
  145. size_t i;
  146. const struct addr_range *ar;
  147. for (i = 0; i < entries; ++i) {
  148. ar = &ranges[i];
  149. if (s->addr >= ar->start && s->addr <= ar->end)
  150. return 1;
  151. }
  152. return 0;
  153. }
  154. static bool string_starts_with(const char *s, const char *prefix)
  155. {
  156. return strncmp(s, prefix, strlen(prefix)) == 0;
  157. }
  158. static int symbol_valid(const struct sym_entry *s)
  159. {
  160. const char *name = sym_name(s);
  161. /* if --all-symbols is not specified, then symbols outside the text
  162. * and inittext sections are discarded */
  163. if (!all_symbols) {
  164. /*
  165. * Symbols starting with __start and __stop are used to denote
  166. * section boundaries, and should always be included:
  167. */
  168. if (string_starts_with(name, "__start_") ||
  169. string_starts_with(name, "__stop_"))
  170. return 1;
  171. if (symbol_in_range(s, text_ranges,
  172. ARRAY_SIZE(text_ranges)) == 0)
  173. return 0;
  174. /* Corner case. Discard any symbols with the same value as
  175. * _etext _einittext; they can move between pass 1 and 2 when
  176. * the kallsyms data are added. If these symbols move then
  177. * they may get dropped in pass 2, which breaks the kallsyms
  178. * rules.
  179. */
  180. if ((s->addr == text_range_text->end &&
  181. strcmp(name, text_range_text->end_sym)) ||
  182. (s->addr == text_range_inittext->end &&
  183. strcmp(name, text_range_inittext->end_sym)))
  184. return 0;
  185. }
  186. return 1;
  187. }
  188. /* remove all the invalid symbols from the table */
  189. static void shrink_table(void)
  190. {
  191. unsigned int i, pos;
  192. pos = 0;
  193. for (i = 0; i < table_cnt; i++) {
  194. if (symbol_valid(table[i])) {
  195. if (pos != i)
  196. table[pos] = table[i];
  197. pos++;
  198. } else {
  199. free(table[i]);
  200. }
  201. }
  202. table_cnt = pos;
  203. }
  204. static void read_map(const char *in)
  205. {
  206. FILE *fp;
  207. struct sym_entry *sym;
  208. char *buf = NULL;
  209. size_t buflen = 0;
  210. fp = fopen(in, "r");
  211. if (!fp) {
  212. perror(in);
  213. exit(1);
  214. }
  215. while (!feof(fp)) {
  216. sym = read_symbol(fp, &buf, &buflen);
  217. if (!sym)
  218. continue;
  219. sym->seq = table_cnt;
  220. if (table_cnt >= table_size) {
  221. table_size += 10000;
  222. table = xrealloc(table, sizeof(*table) * table_size);
  223. }
  224. table[table_cnt++] = sym;
  225. }
  226. free(buf);
  227. fclose(fp);
  228. }
  229. static void output_label(const char *label)
  230. {
  231. printf(".globl %s\n", label);
  232. printf("\t.balign 4\n");
  233. printf("%s:\n", label);
  234. }
  235. /* uncompress a compressed symbol. When this function is called, the best table
  236. * might still be compressed itself, so the function needs to be recursive */
  237. static int expand_symbol(const unsigned char *data, int len, char *result)
  238. {
  239. int c, rlen, total=0;
  240. while (len) {
  241. c = *data;
  242. /* if the table holds a single char that is the same as the one
  243. * we are looking for, then end the search */
  244. if (best_table[c][0]==c && best_table_len[c]==1) {
  245. *result++ = c;
  246. total++;
  247. } else {
  248. /* if not, recurse and expand */
  249. rlen = expand_symbol(best_table[c], best_table_len[c], result);
  250. total += rlen;
  251. result += rlen;
  252. }
  253. data++;
  254. len--;
  255. }
  256. *result=0;
  257. return total;
  258. }
  259. static int compare_names(const void *a, const void *b)
  260. {
  261. int ret;
  262. const struct sym_entry *sa = *(const struct sym_entry **)a;
  263. const struct sym_entry *sb = *(const struct sym_entry **)b;
  264. ret = strcmp(sym_name(sa), sym_name(sb));
  265. if (!ret) {
  266. if (sa->addr > sb->addr)
  267. return 1;
  268. else if (sa->addr < sb->addr)
  269. return -1;
  270. /* keep old order */
  271. return (int)(sa->seq - sb->seq);
  272. }
  273. return ret;
  274. }
  275. static void sort_symbols_by_name(void)
  276. {
  277. qsort(table, table_cnt, sizeof(table[0]), compare_names);
  278. }
  279. static void write_src(void)
  280. {
  281. unsigned int i, k, off;
  282. unsigned int best_idx[256];
  283. unsigned int *markers, markers_cnt;
  284. char buf[KSYM_NAME_LEN];
  285. printf("\t.section .rodata, \"a\"\n");
  286. output_label("kallsyms_num_syms");
  287. printf("\t.long\t%u\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_cnt = (table_cnt + 255) / 256;
  292. markers = xmalloc(sizeof(*markers) * markers_cnt);
  293. output_label("kallsyms_names");
  294. off = 0;
  295. for (i = 0; i < table_cnt; i++) {
  296. if ((i & 0xFF) == 0)
  297. markers[i >> 8] = off;
  298. table[i]->seq = i;
  299. /* There cannot be any symbol of length zero. */
  300. if (table[i]->len == 0) {
  301. fprintf(stderr, "kallsyms failure: "
  302. "unexpected zero symbol length\n");
  303. exit(EXIT_FAILURE);
  304. }
  305. /* Only lengths that fit in up-to-two-byte ULEB128 are supported. */
  306. if (table[i]->len > 0x3FFF) {
  307. fprintf(stderr, "kallsyms failure: "
  308. "unexpected huge symbol length\n");
  309. exit(EXIT_FAILURE);
  310. }
  311. /* Encode length with ULEB128. */
  312. if (table[i]->len <= 0x7F) {
  313. /* Most symbols use a single byte for the length. */
  314. printf("\t.byte 0x%02x", table[i]->len);
  315. off += table[i]->len + 1;
  316. } else {
  317. /* "Big" symbols use two bytes. */
  318. printf("\t.byte 0x%02x, 0x%02x",
  319. (table[i]->len & 0x7F) | 0x80,
  320. (table[i]->len >> 7) & 0x7F);
  321. off += table[i]->len + 2;
  322. }
  323. for (k = 0; k < table[i]->len; k++)
  324. printf(", 0x%02x", table[i]->sym[k]);
  325. /*
  326. * Now that we wrote out the compressed symbol name, restore the
  327. * original name and print it in the comment.
  328. */
  329. expand_symbol(table[i]->sym, table[i]->len, buf);
  330. strcpy((char *)table[i]->sym, buf);
  331. printf("\t/* %s */\n", table[i]->sym);
  332. }
  333. printf("\n");
  334. output_label("kallsyms_markers");
  335. for (i = 0; i < markers_cnt; i++)
  336. printf("\t.long\t%u\n", markers[i]);
  337. printf("\n");
  338. free(markers);
  339. output_label("kallsyms_token_table");
  340. off = 0;
  341. for (i = 0; i < 256; i++) {
  342. best_idx[i] = off;
  343. expand_symbol(best_table[i], best_table_len[i], buf);
  344. printf("\t.asciz\t\"%s\"\n", buf);
  345. off += strlen(buf) + 1;
  346. }
  347. printf("\n");
  348. output_label("kallsyms_token_index");
  349. for (i = 0; i < 256; i++)
  350. printf("\t.short\t%d\n", best_idx[i]);
  351. printf("\n");
  352. output_label("kallsyms_offsets");
  353. for (i = 0; i < table_cnt; i++) {
  354. if (pc_relative) {
  355. long long offset = table[i]->addr - _text;
  356. if (offset < INT_MIN || offset > INT_MAX) {
  357. fprintf(stderr, "kallsyms failure: "
  358. "relative symbol value %#llx out of range\n",
  359. table[i]->addr);
  360. exit(EXIT_FAILURE);
  361. }
  362. printf("\t.long\t_text - . + (%d)\t/* %s */\n",
  363. (int)offset, table[i]->sym);
  364. } else {
  365. printf("\t.long\t%#x\t/* %s */\n",
  366. (unsigned int)table[i]->addr, table[i]->sym);
  367. }
  368. }
  369. printf("\n");
  370. sort_symbols_by_name();
  371. output_label("kallsyms_seqs_of_names");
  372. for (i = 0; i < table_cnt; i++)
  373. printf("\t.byte 0x%02x, 0x%02x, 0x%02x\t/* %s */\n",
  374. (unsigned char)(table[i]->seq >> 16),
  375. (unsigned char)(table[i]->seq >> 8),
  376. (unsigned char)(table[i]->seq >> 0),
  377. table[i]->sym);
  378. printf("\n");
  379. }
  380. /* table lookup compression functions */
  381. /* count all the possible tokens in a symbol */
  382. static void learn_symbol(const unsigned char *symbol, int len)
  383. {
  384. int i;
  385. for (i = 0; i < len - 1; i++)
  386. token_profit[ symbol[i] + (symbol[i + 1] << 8) ]++;
  387. }
  388. /* decrease the count for all the possible tokens in a symbol */
  389. static void forget_symbol(const unsigned char *symbol, int len)
  390. {
  391. int i;
  392. for (i = 0; i < len - 1; i++)
  393. token_profit[ symbol[i] + (symbol[i + 1] << 8) ]--;
  394. }
  395. /* do the initial token count */
  396. static void build_initial_token_table(void)
  397. {
  398. unsigned int i;
  399. for (i = 0; i < table_cnt; i++)
  400. learn_symbol(table[i]->sym, table[i]->len);
  401. }
  402. static unsigned char *find_token(unsigned char *str, int len,
  403. const unsigned char *token)
  404. {
  405. int i;
  406. for (i = 0; i < len - 1; i++) {
  407. if (str[i] == token[0] && str[i+1] == token[1])
  408. return &str[i];
  409. }
  410. return NULL;
  411. }
  412. /* replace a given token in all the valid symbols. Use the sampled symbols
  413. * to update the counts */
  414. static void compress_symbols(const unsigned char *str, int idx)
  415. {
  416. unsigned int i, len, size;
  417. unsigned char *p1, *p2;
  418. for (i = 0; i < table_cnt; i++) {
  419. len = table[i]->len;
  420. p1 = table[i]->sym;
  421. /* find the token on the symbol */
  422. p2 = find_token(p1, len, str);
  423. if (!p2) continue;
  424. /* decrease the counts for this symbol's tokens */
  425. forget_symbol(table[i]->sym, len);
  426. size = len;
  427. do {
  428. *p2 = idx;
  429. p2++;
  430. size -= (p2 - p1);
  431. memmove(p2, p2 + 1, size);
  432. p1 = p2;
  433. len--;
  434. if (size < 2) break;
  435. /* find the token on the symbol */
  436. p2 = find_token(p1, size, str);
  437. } while (p2);
  438. table[i]->len = len;
  439. /* increase the counts for this symbol's new tokens */
  440. learn_symbol(table[i]->sym, len);
  441. }
  442. }
  443. /* search the token with the maximum profit */
  444. static int find_best_token(void)
  445. {
  446. int i, best, bestprofit;
  447. bestprofit=-10000;
  448. best = 0;
  449. for (i = 0; i < 0x10000; i++) {
  450. if (token_profit[i] > bestprofit) {
  451. best = i;
  452. bestprofit = token_profit[i];
  453. }
  454. }
  455. return best;
  456. }
  457. /* this is the core of the algorithm: calculate the "best" table */
  458. static void optimize_result(void)
  459. {
  460. int i, best;
  461. /* using the '\0' symbol last allows compress_symbols to use standard
  462. * fast string functions */
  463. for (i = 255; i >= 0; i--) {
  464. /* if this table slot is empty (it is not used by an actual
  465. * original char code */
  466. if (!best_table_len[i]) {
  467. /* find the token with the best profit value */
  468. best = find_best_token();
  469. if (token_profit[best] == 0)
  470. break;
  471. /* place it in the "best" table */
  472. best_table_len[i] = 2;
  473. best_table[i][0] = best & 0xFF;
  474. best_table[i][1] = (best >> 8) & 0xFF;
  475. /* replace this token in all the valid symbols */
  476. compress_symbols(best_table[i], i);
  477. }
  478. }
  479. }
  480. /* start by placing the symbols that are actually used on the table */
  481. static void insert_real_symbols_in_table(void)
  482. {
  483. unsigned int i, j, c;
  484. for (i = 0; i < table_cnt; i++) {
  485. for (j = 0; j < table[i]->len; j++) {
  486. c = table[i]->sym[j];
  487. best_table[c][0]=c;
  488. best_table_len[c]=1;
  489. }
  490. }
  491. }
  492. static void optimize_token_table(void)
  493. {
  494. build_initial_token_table();
  495. insert_real_symbols_in_table();
  496. optimize_result();
  497. }
  498. /* guess for "linker script provide" symbol */
  499. static int may_be_linker_script_provide_symbol(const struct sym_entry *se)
  500. {
  501. const char *symbol = sym_name(se);
  502. int len = se->len - 1;
  503. if (len < 8)
  504. return 0;
  505. if (symbol[0] != '_' || symbol[1] != '_')
  506. return 0;
  507. /* __start_XXXXX */
  508. if (!memcmp(symbol + 2, "start_", 6))
  509. return 1;
  510. /* __stop_XXXXX */
  511. if (!memcmp(symbol + 2, "stop_", 5))
  512. return 1;
  513. /* __end_XXXXX */
  514. if (!memcmp(symbol + 2, "end_", 4))
  515. return 1;
  516. /* __XXXXX_start */
  517. if (!memcmp(symbol + len - 6, "_start", 6))
  518. return 1;
  519. /* __XXXXX_end */
  520. if (!memcmp(symbol + len - 4, "_end", 4))
  521. return 1;
  522. return 0;
  523. }
  524. static int compare_symbols(const void *a, const void *b)
  525. {
  526. const struct sym_entry *sa = *(const struct sym_entry **)a;
  527. const struct sym_entry *sb = *(const struct sym_entry **)b;
  528. int wa, wb;
  529. /* sort by address first */
  530. if (sa->addr > sb->addr)
  531. return 1;
  532. if (sa->addr < sb->addr)
  533. return -1;
  534. /* sort by "weakness" type */
  535. wa = (sa->sym[0] == 'w') || (sa->sym[0] == 'W');
  536. wb = (sb->sym[0] == 'w') || (sb->sym[0] == 'W');
  537. if (wa != wb)
  538. return wa - wb;
  539. /* sort by "linker script provide" type */
  540. wa = may_be_linker_script_provide_symbol(sa);
  541. wb = may_be_linker_script_provide_symbol(sb);
  542. if (wa != wb)
  543. return wa - wb;
  544. /* sort by the number of prefix underscores */
  545. wa = strspn(sym_name(sa), "_");
  546. wb = strspn(sym_name(sb), "_");
  547. if (wa != wb)
  548. return wa - wb;
  549. /* sort by initial order, so that other symbols are left undisturbed */
  550. return sa->seq - sb->seq;
  551. }
  552. static void sort_symbols(void)
  553. {
  554. qsort(table, table_cnt, sizeof(table[0]), compare_symbols);
  555. }
  556. int main(int argc, char **argv)
  557. {
  558. while (1) {
  559. static const struct option long_options[] = {
  560. {"all-symbols", no_argument, &all_symbols, 1},
  561. {"pc-relative", no_argument, &pc_relative, 1},
  562. {},
  563. };
  564. int c = getopt_long(argc, argv, "", long_options, NULL);
  565. if (c == -1)
  566. break;
  567. if (c != 0)
  568. usage();
  569. }
  570. if (optind >= argc)
  571. usage();
  572. read_map(argv[optind]);
  573. shrink_table();
  574. sort_symbols();
  575. optimize_token_table();
  576. write_src();
  577. return 0;
  578. }