kallsyms.c 13 KB

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