kallsyms.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  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. * ChangeLog:
  11. *
  12. * (25/Aug/2004) Paulo Marques <pmarques@grupopie.com>
  13. * Changed the compression method from stem compression to "table lookup"
  14. * compression
  15. *
  16. * Table compression uses all the unused char codes on the symbols and
  17. * maps these to the most used substrings (tokens). For instance, it might
  18. * map char code 0xF7 to represent "write_" and then in every symbol where
  19. * "write_" appears it can be replaced by 0xF7, saving 5 bytes.
  20. * The used codes themselves are also placed in the table so that the
  21. * decompresion can work without "special cases".
  22. * Applied to kernel symbols, this usually produces a compression ratio
  23. * of about 50%.
  24. *
  25. */
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. #include <string.h>
  29. #include <ctype.h>
  30. /* maximum token length used. It doesn't pay to increase it a lot, because
  31. * very long substrings probably don't repeat themselves too often. */
  32. #define MAX_TOK_SIZE 11
  33. #define KSYM_NAME_LEN 127
  34. /* we use only a subset of the complete symbol table to gather the token count,
  35. * to speed up compression, at the expense of a little compression ratio */
  36. #define WORKING_SET 1024
  37. /* first find the best token only on the list of tokens that would profit more
  38. * than GOOD_BAD_THRESHOLD. Only if this list is empty go to the "bad" list.
  39. * Increasing this value will put less tokens on the "good" list, so the search
  40. * is faster. However, if the good list runs out of tokens, we must painfully
  41. * search the bad list. */
  42. #define GOOD_BAD_THRESHOLD 10
  43. /* token hash parameters */
  44. #define HASH_BITS 18
  45. #define HASH_TABLE_SIZE (1 << HASH_BITS)
  46. #define HASH_MASK (HASH_TABLE_SIZE - 1)
  47. #define HASH_BASE_OFFSET 2166136261U
  48. #define HASH_FOLD(a) ((a)&(HASH_MASK))
  49. /* flags to mark symbols */
  50. #define SYM_FLAG_VALID 1
  51. #define SYM_FLAG_SAMPLED 2
  52. struct sym_entry {
  53. unsigned long long addr;
  54. char type;
  55. unsigned char flags;
  56. unsigned char len;
  57. unsigned char *sym;
  58. };
  59. static struct sym_entry *table;
  60. static int size, cnt;
  61. static unsigned long long _stext, _etext, _sinittext, _einittext;
  62. static int all_symbols = 0;
  63. struct token {
  64. unsigned char data[MAX_TOK_SIZE];
  65. unsigned char len;
  66. /* profit: the number of bytes that could be saved by inserting this
  67. * token into the table */
  68. int profit;
  69. struct token *next; /* next token on the hash list */
  70. struct token *right; /* next token on the good/bad list */
  71. struct token *left; /* previous token on the good/bad list */
  72. struct token *smaller; /* token that is less one letter than this one */
  73. };
  74. struct token bad_head, good_head;
  75. struct token *hash_table[HASH_TABLE_SIZE];
  76. /* the table that holds the result of the compression */
  77. unsigned char best_table[256][MAX_TOK_SIZE+1];
  78. unsigned char best_table_len[256];
  79. static void
  80. usage(void)
  81. {
  82. fprintf(stderr, "Usage: kallsyms [--all-symbols] < in.map > out.S\n");
  83. exit(1);
  84. }
  85. /*
  86. * This ignores the intensely annoying "mapping symbols" found
  87. * in ARM ELF files: $a, $t and $d.
  88. */
  89. static inline int
  90. is_arm_mapping_symbol(const char *str)
  91. {
  92. return str[0] == '$' && strchr("atd", str[1])
  93. && (str[2] == '\0' || str[2] == '.');
  94. }
  95. static int
  96. read_symbol(FILE *in, struct sym_entry *s)
  97. {
  98. char str[500];
  99. int rc;
  100. rc = fscanf(in, "%llx %c %499s\n", &s->addr, &s->type, str);
  101. if (rc != 3) {
  102. if (rc != EOF) {
  103. /* skip line */
  104. fgets(str, 500, in);
  105. }
  106. return -1;
  107. }
  108. /* Ignore most absolute/undefined (?) symbols. */
  109. if (strcmp(str, "_stext") == 0)
  110. _stext = s->addr;
  111. else if (strcmp(str, "_etext") == 0)
  112. _etext = s->addr;
  113. else if (strcmp(str, "_sinittext") == 0)
  114. _sinittext = s->addr;
  115. else if (strcmp(str, "_einittext") == 0)
  116. _einittext = s->addr;
  117. else if (toupper(s->type) == 'A')
  118. {
  119. /* Keep these useful absolute symbols */
  120. if (strcmp(str, "__kernel_syscall_via_break") &&
  121. strcmp(str, "__kernel_syscall_via_epc") &&
  122. strcmp(str, "__kernel_sigtramp") &&
  123. strcmp(str, "__gp"))
  124. return -1;
  125. }
  126. else if (toupper(s->type) == 'U' ||
  127. is_arm_mapping_symbol(str))
  128. return -1;
  129. /* include the type field in the symbol name, so that it gets
  130. * compressed together */
  131. s->len = strlen(str) + 1;
  132. s->sym = (char *) malloc(s->len + 1);
  133. strcpy(s->sym + 1, str);
  134. s->sym[0] = s->type;
  135. return 0;
  136. }
  137. static int
  138. symbol_valid(struct sym_entry *s)
  139. {
  140. /* Symbols which vary between passes. Passes 1 and 2 must have
  141. * identical symbol lists. The kallsyms_* symbols below are only added
  142. * after pass 1, they would be included in pass 2 when --all-symbols is
  143. * specified so exclude them to get a stable symbol list.
  144. */
  145. static char *special_symbols[] = {
  146. "kallsyms_addresses",
  147. "kallsyms_num_syms",
  148. "kallsyms_names",
  149. "kallsyms_markers",
  150. "kallsyms_token_table",
  151. "kallsyms_token_index",
  152. /* Exclude linker generated symbols which vary between passes */
  153. "_SDA_BASE_", /* ppc */
  154. "_SDA2_BASE_", /* ppc */
  155. NULL };
  156. int i;
  157. /* if --all-symbols is not specified, then symbols outside the text
  158. * and inittext sections are discarded */
  159. if (!all_symbols) {
  160. if ((s->addr < _stext || s->addr > _etext)
  161. && (s->addr < _sinittext || s->addr > _einittext))
  162. return 0;
  163. /* Corner case. Discard any symbols with the same value as
  164. * _etext or _einittext, they can move between pass 1 and 2
  165. * when the kallsyms data is added. If these symbols move then
  166. * they may get dropped in pass 2, which breaks the kallsyms
  167. * rules.
  168. */
  169. if ((s->addr == _etext && strcmp(s->sym + 1, "_etext")) ||
  170. (s->addr == _einittext && strcmp(s->sym + 1, "_einittext")))
  171. return 0;
  172. }
  173. /* Exclude symbols which vary between passes. */
  174. if (strstr(s->sym + 1, "_compiled."))
  175. return 0;
  176. for (i = 0; special_symbols[i]; i++)
  177. if( strcmp(s->sym + 1, special_symbols[i]) == 0 )
  178. return 0;
  179. return 1;
  180. }
  181. static void
  182. read_map(FILE *in)
  183. {
  184. while (!feof(in)) {
  185. if (cnt >= size) {
  186. size += 10000;
  187. table = realloc(table, sizeof(*table) * size);
  188. if (!table) {
  189. fprintf(stderr, "out of memory\n");
  190. exit (1);
  191. }
  192. }
  193. if (read_symbol(in, &table[cnt]) == 0)
  194. cnt++;
  195. }
  196. }
  197. static void output_label(char *label)
  198. {
  199. printf(".globl %s\n",label);
  200. printf("\tALGN\n");
  201. printf("%s:\n",label);
  202. }
  203. /* uncompress a compressed symbol. When this function is called, the best table
  204. * might still be compressed itself, so the function needs to be recursive */
  205. static int expand_symbol(unsigned char *data, int len, char *result)
  206. {
  207. int c, rlen, total=0;
  208. while (len) {
  209. c = *data;
  210. /* if the table holds a single char that is the same as the one
  211. * we are looking for, then end the search */
  212. if (best_table[c][0]==c && best_table_len[c]==1) {
  213. *result++ = c;
  214. total++;
  215. } else {
  216. /* if not, recurse and expand */
  217. rlen = expand_symbol(best_table[c], best_table_len[c], result);
  218. total += rlen;
  219. result += rlen;
  220. }
  221. data++;
  222. len--;
  223. }
  224. *result=0;
  225. return total;
  226. }
  227. static void
  228. write_src(void)
  229. {
  230. int i, k, off, valid;
  231. unsigned int best_idx[256];
  232. unsigned int *markers;
  233. char buf[KSYM_NAME_LEN+1];
  234. printf("#include <asm/types.h>\n");
  235. printf("#if BITS_PER_LONG == 64\n");
  236. printf("#define PTR .quad\n");
  237. printf("#define ALGN .align 8\n");
  238. printf("#else\n");
  239. printf("#define PTR .long\n");
  240. printf("#define ALGN .align 4\n");
  241. printf("#endif\n");
  242. printf(".data\n");
  243. output_label("kallsyms_addresses");
  244. valid = 0;
  245. for (i = 0; i < cnt; i++) {
  246. if (table[i].flags & SYM_FLAG_VALID) {
  247. printf("\tPTR\t%#llx\n", table[i].addr);
  248. valid++;
  249. }
  250. }
  251. printf("\n");
  252. output_label("kallsyms_num_syms");
  253. printf("\tPTR\t%d\n", valid);
  254. printf("\n");
  255. /* table of offset markers, that give the offset in the compressed stream
  256. * every 256 symbols */
  257. markers = (unsigned int *) malloc(sizeof(unsigned int)*((valid + 255) / 256));
  258. output_label("kallsyms_names");
  259. valid = 0;
  260. off = 0;
  261. for (i = 0; i < cnt; i++) {
  262. if (!table[i].flags & SYM_FLAG_VALID)
  263. continue;
  264. if ((valid & 0xFF) == 0)
  265. markers[valid >> 8] = off;
  266. printf("\t.byte 0x%02x", table[i].len);
  267. for (k = 0; k < table[i].len; k++)
  268. printf(", 0x%02x", table[i].sym[k]);
  269. printf("\n");
  270. off += table[i].len + 1;
  271. valid++;
  272. }
  273. printf("\n");
  274. output_label("kallsyms_markers");
  275. for (i = 0; i < ((valid + 255) >> 8); i++)
  276. printf("\tPTR\t%d\n", markers[i]);
  277. printf("\n");
  278. free(markers);
  279. output_label("kallsyms_token_table");
  280. off = 0;
  281. for (i = 0; i < 256; i++) {
  282. best_idx[i] = off;
  283. expand_symbol(best_table[i],best_table_len[i],buf);
  284. printf("\t.asciz\t\"%s\"\n", buf);
  285. off += strlen(buf) + 1;
  286. }
  287. printf("\n");
  288. output_label("kallsyms_token_index");
  289. for (i = 0; i < 256; i++)
  290. printf("\t.short\t%d\n", best_idx[i]);
  291. printf("\n");
  292. }
  293. /* table lookup compression functions */
  294. static inline unsigned int rehash_token(unsigned int hash, unsigned char data)
  295. {
  296. return ((hash * 16777619) ^ data);
  297. }
  298. static unsigned int hash_token(unsigned char *data, int len)
  299. {
  300. unsigned int hash=HASH_BASE_OFFSET;
  301. int i;
  302. for (i = 0; i < len; i++)
  303. hash = rehash_token(hash, data[i]);
  304. return HASH_FOLD(hash);
  305. }
  306. /* find a token given its data and hash value */
  307. static struct token *find_token_hash(unsigned char *data, int len, unsigned int hash)
  308. {
  309. struct token *ptr;
  310. ptr = hash_table[hash];
  311. while (ptr) {
  312. if ((ptr->len == len) && (memcmp(ptr->data, data, len) == 0))
  313. return ptr;
  314. ptr=ptr->next;
  315. }
  316. return NULL;
  317. }
  318. static inline void insert_token_in_group(struct token *head, struct token *ptr)
  319. {
  320. ptr->right = head->right;
  321. ptr->right->left = ptr;
  322. head->right = ptr;
  323. ptr->left = head;
  324. }
  325. static inline void remove_token_from_group(struct token *ptr)
  326. {
  327. ptr->left->right = ptr->right;
  328. ptr->right->left = ptr->left;
  329. }
  330. /* build the counts for all the tokens that start with "data", and have lenghts
  331. * from 2 to "len" */
  332. static void learn_token(unsigned char *data, int len)
  333. {
  334. struct token *ptr,*last_ptr;
  335. int i, newprofit;
  336. unsigned int hash = HASH_BASE_OFFSET;
  337. unsigned int hashes[MAX_TOK_SIZE + 1];
  338. if (len > MAX_TOK_SIZE)
  339. len = MAX_TOK_SIZE;
  340. /* calculate and store the hash values for all the sub-tokens */
  341. hash = rehash_token(hash, data[0]);
  342. for (i = 2; i <= len; i++) {
  343. hash = rehash_token(hash, data[i-1]);
  344. hashes[i] = HASH_FOLD(hash);
  345. }
  346. last_ptr = NULL;
  347. ptr = NULL;
  348. for (i = len; i >= 2; i--) {
  349. hash = hashes[i];
  350. if (!ptr) ptr = find_token_hash(data, i, hash);
  351. if (!ptr) {
  352. /* create a new token entry */
  353. ptr = (struct token *) malloc(sizeof(*ptr));
  354. memcpy(ptr->data, data, i);
  355. ptr->len = i;
  356. /* when we create an entry, it's profit is 0 because
  357. * we also take into account the size of the token on
  358. * the compressed table. We then subtract GOOD_BAD_THRESHOLD
  359. * so that the test to see if this token belongs to
  360. * the good or bad list, is a comparison to zero */
  361. ptr->profit = -GOOD_BAD_THRESHOLD;
  362. ptr->next = hash_table[hash];
  363. hash_table[hash] = ptr;
  364. insert_token_in_group(&bad_head, ptr);
  365. ptr->smaller = NULL;
  366. } else {
  367. newprofit = ptr->profit + (ptr->len - 1);
  368. /* check to see if this token needs to be moved to a
  369. * different list */
  370. if((ptr->profit < 0) && (newprofit >= 0)) {
  371. remove_token_from_group(ptr);
  372. insert_token_in_group(&good_head,ptr);
  373. }
  374. ptr->profit = newprofit;
  375. }
  376. if (last_ptr) last_ptr->smaller = ptr;
  377. last_ptr = ptr;
  378. ptr = ptr->smaller;
  379. }
  380. }
  381. /* decrease the counts for all the tokens that start with "data", and have lenghts
  382. * from 2 to "len". This function is much simpler than learn_token because we have
  383. * more guarantees (tho tokens exist, the ->smaller pointer is set, etc.)
  384. * The two separate functions exist only because of compression performance */
  385. static void forget_token(unsigned char *data, int len)
  386. {
  387. struct token *ptr;
  388. int i, newprofit;
  389. unsigned int hash=0;
  390. if (len > MAX_TOK_SIZE) len = MAX_TOK_SIZE;
  391. hash = hash_token(data, len);
  392. ptr = find_token_hash(data, len, hash);
  393. for (i = len; i >= 2; i--) {
  394. newprofit = ptr->profit - (ptr->len - 1);
  395. if ((ptr->profit >= 0) && (newprofit < 0)) {
  396. remove_token_from_group(ptr);
  397. insert_token_in_group(&bad_head, ptr);
  398. }
  399. ptr->profit=newprofit;
  400. ptr=ptr->smaller;
  401. }
  402. }
  403. /* count all the possible tokens in a symbol */
  404. static void learn_symbol(unsigned char *symbol, int len)
  405. {
  406. int i;
  407. for (i = 0; i < len - 1; i++)
  408. learn_token(symbol + i, len - i);
  409. }
  410. /* decrease the count for all the possible tokens in a symbol */
  411. static void forget_symbol(unsigned char *symbol, int len)
  412. {
  413. int i;
  414. for (i = 0; i < len - 1; i++)
  415. forget_token(symbol + i, len - i);
  416. }
  417. /* set all the symbol flags and do the initial token count */
  418. static void build_initial_tok_table(void)
  419. {
  420. int i, use_it, valid;
  421. valid = 0;
  422. for (i = 0; i < cnt; i++) {
  423. table[i].flags = 0;
  424. if ( symbol_valid(&table[i]) ) {
  425. table[i].flags |= SYM_FLAG_VALID;
  426. valid++;
  427. }
  428. }
  429. use_it = 0;
  430. for (i = 0; i < cnt; i++) {
  431. /* subsample the available symbols. This method is almost like
  432. * a Bresenham's algorithm to get uniformly distributed samples
  433. * across the symbol table */
  434. if (table[i].flags & SYM_FLAG_VALID) {
  435. use_it += WORKING_SET;
  436. if (use_it >= valid) {
  437. table[i].flags |= SYM_FLAG_SAMPLED;
  438. use_it -= valid;
  439. }
  440. }
  441. if (table[i].flags & SYM_FLAG_SAMPLED)
  442. learn_symbol(table[i].sym, table[i].len);
  443. }
  444. }
  445. /* replace a given token in all the valid symbols. Use the sampled symbols
  446. * to update the counts */
  447. static void compress_symbols(unsigned char *str, int tlen, int idx)
  448. {
  449. int i, len, learn, size;
  450. unsigned char *p;
  451. for (i = 0; i < cnt; i++) {
  452. if (!(table[i].flags & SYM_FLAG_VALID)) continue;
  453. len = table[i].len;
  454. learn = 0;
  455. p = table[i].sym;
  456. do {
  457. /* find the token on the symbol */
  458. p = (unsigned char *) strstr((char *) p, (char *) str);
  459. if (!p) break;
  460. if (!learn) {
  461. /* if this symbol was used to count, decrease it */
  462. if (table[i].flags & SYM_FLAG_SAMPLED)
  463. forget_symbol(table[i].sym, len);
  464. learn = 1;
  465. }
  466. *p = idx;
  467. size = (len - (p - table[i].sym)) - tlen + 1;
  468. memmove(p + 1, p + tlen, size);
  469. p++;
  470. len -= tlen - 1;
  471. } while (size >= tlen);
  472. if(learn) {
  473. table[i].len = len;
  474. /* if this symbol was used to count, learn it again */
  475. if(table[i].flags & SYM_FLAG_SAMPLED)
  476. learn_symbol(table[i].sym, len);
  477. }
  478. }
  479. }
  480. /* search the token with the maximum profit */
  481. static struct token *find_best_token(void)
  482. {
  483. struct token *ptr,*best,*head;
  484. int bestprofit;
  485. bestprofit=-10000;
  486. /* failsafe: if the "good" list is empty search from the "bad" list */
  487. if(good_head.right == &good_head) head = &bad_head;
  488. else head = &good_head;
  489. ptr = head->right;
  490. best = NULL;
  491. while (ptr != head) {
  492. if (ptr->profit > bestprofit) {
  493. bestprofit = ptr->profit;
  494. best = ptr;
  495. }
  496. ptr = ptr->right;
  497. }
  498. return best;
  499. }
  500. /* this is the core of the algorithm: calculate the "best" table */
  501. static void optimize_result(void)
  502. {
  503. struct token *best;
  504. int i;
  505. /* using the '\0' symbol last allows compress_symbols to use standard
  506. * fast string functions */
  507. for (i = 255; i >= 0; i--) {
  508. /* if this table slot is empty (it is not used by an actual
  509. * original char code */
  510. if (!best_table_len[i]) {
  511. /* find the token with the breates profit value */
  512. best = find_best_token();
  513. /* place it in the "best" table */
  514. best_table_len[i] = best->len;
  515. memcpy(best_table[i], best->data, best_table_len[i]);
  516. /* zero terminate the token so that we can use strstr
  517. in compress_symbols */
  518. best_table[i][best_table_len[i]]='\0';
  519. /* replace this token in all the valid symbols */
  520. compress_symbols(best_table[i], best_table_len[i], i);
  521. }
  522. }
  523. }
  524. /* start by placing the symbols that are actually used on the table */
  525. static void insert_real_symbols_in_table(void)
  526. {
  527. int i, j, c;
  528. memset(best_table, 0, sizeof(best_table));
  529. memset(best_table_len, 0, sizeof(best_table_len));
  530. for (i = 0; i < cnt; i++) {
  531. if (table[i].flags & SYM_FLAG_VALID) {
  532. for (j = 0; j < table[i].len; j++) {
  533. c = table[i].sym[j];
  534. best_table[c][0]=c;
  535. best_table_len[c]=1;
  536. }
  537. }
  538. }
  539. }
  540. static void optimize_token_table(void)
  541. {
  542. memset(hash_table, 0, sizeof(hash_table));
  543. good_head.left = &good_head;
  544. good_head.right = &good_head;
  545. bad_head.left = &bad_head;
  546. bad_head.right = &bad_head;
  547. build_initial_tok_table();
  548. insert_real_symbols_in_table();
  549. optimize_result();
  550. }
  551. int
  552. main(int argc, char **argv)
  553. {
  554. if (argc == 2 && strcmp(argv[1], "--all-symbols") == 0)
  555. all_symbols = 1;
  556. else if (argc != 1)
  557. usage();
  558. read_map(stdin);
  559. optimize_token_table();
  560. write_src();
  561. return 0;
  562. }