kallsyms.c 13 KB

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