]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.bin/nm/nm.c
This commit was generated by cvs2svn to compensate for changes in r112158,
[FreeBSD/FreeBSD.git] / usr.bin / nm / nm.c
1 /*
2  * Copyright (c) 1989, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Hans Huebner.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by the University of
19  *      California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36
37 #ifndef lint
38 static const char copyright[] =
39 "@(#) Copyright (c) 1989, 1993\n\
40         The Regents of the University of California.  All rights reserved.\n";
41 #endif /* not lint */
42
43 #ifndef lint
44 #if 0
45 static char sccsid[] = "@(#)nm.c        8.1 (Berkeley) 6/6/93";
46 #endif
47 #endif /* not lint */
48
49 #include <sys/cdefs.h>
50 __FBSDID("$FreeBSD$");
51
52 #include <sys/types.h>
53
54 #include <arpa/inet.h>
55
56 #include <a.out.h>
57 #include <ar.h>
58 #include <ctype.h>
59 #include <dirent.h>
60 #include <err.h>
61 #include <ranlib.h>
62 #include <stab.h>
63 #include <stdio.h>
64 #include <stdlib.h>
65 #include <string.h>
66 #include <unistd.h>
67
68 int ignore_bad_archive_entries = 1;
69 int print_only_external_symbols;
70 int print_only_undefined_symbols;
71 int print_all_symbols;
72 int print_file_each_line;
73 int print_weak_symbols;
74 int fcount;
75
76 int rev, table;
77 const char *typestring(u_char);
78
79 /* some macros for symbol type (nlist.n_type) handling */
80 #define IS_DEBUGGER_SYMBOL(x)   ((x) & N_STAB)
81 #define IS_EXTERNAL(x)          ((x) & N_EXT)
82 #define SYMBOL_TYPE(x)          ((x) & (N_TYPE | N_STAB))
83 #define SYMBOL_BIND(x)          (((x) >> 4) & 0xf)
84
85 static void usage(void);
86 int process_file(const char *);
87 int show_archive(const char *, FILE *);
88 int show_objfile(const char *, FILE *);
89 void print_symbol(const char *, struct nlist *);
90 char typeletter(u_char);
91 int fname(const void *, const void *);
92 int rname(const void *, const void *);
93 int value(const void *, const void *);
94
95 int (*sfunc)(const void *, const void *) = fname;
96
97 /*
98  * main()
99  *      parse command line, execute process_file() for each file
100  *      specified on the command line.
101  */
102 int
103 main(int argc, char *argv[])
104 {
105         int ch, errors;
106
107         while ((ch = getopt(argc, argv, "agnoprtuwW")) != -1) {
108                 switch (ch) {
109                 case 'a':
110                         print_all_symbols = 1;
111                         break;
112                 case 'g':
113                         print_only_external_symbols = 1;
114                         break;
115                 case 'n':
116                         sfunc = value;
117                         break;
118                 case 'o':
119                         print_file_each_line = 1;
120                         break;
121                 case 'p':
122                         sfunc = NULL;
123                         break;
124                 case 'r':
125                         rev = 1;
126                         break;
127                 case 't':
128                         table = 1;
129                         break;
130                 case 'u':
131                         print_only_undefined_symbols = 1;
132                         break;
133                 case 'w':
134                         ignore_bad_archive_entries = 0;
135                         break;
136                 case 'W':
137                         print_weak_symbols = 1;
138                         break;
139                 case '?':
140                 default:
141                         usage();
142                 }
143         }
144         fcount = argc - optind;
145         argv += optind;
146
147         if (rev && sfunc == fname)
148                 sfunc = rname;
149
150         if (!fcount)
151                 errors = process_file("a.out");
152         else {
153                 errors = 0;
154                 do {
155                         errors |= process_file(*argv);
156                 } while (*++argv);
157         }
158         exit(errors);
159 }
160
161 /*
162  * process_file()
163  *      show symbols in the file given as an argument.  Accepts archive and
164  *      object files as input.
165  */
166 int
167 process_file(const char *fn)
168 {
169         struct exec exec_head;
170         FILE *fp;
171         int retval;
172         char magic[SARMAG];
173
174         if (!(fp = fopen(fn, "r"))) {
175                 warnx("cannot read %s", fn);
176                 return(1);
177         }
178
179         if (fcount > 1 && !table)
180                 (void)printf("\n%s:\n", fn);
181
182         /*
183          * First check whether this is an object file - read an object
184          * header, and skip back to the beginning.
185          */
186         if (fread((char *)&exec_head, sizeof(exec_head), (size_t)1, fp) != 1) {
187                 warnx("%s: bad format", fn);
188                 (void)fclose(fp);
189                 return(1);
190         }
191         rewind(fp);
192
193         /* this could be an archive */
194         if (N_BADMAG(exec_head)) {
195                 if (fread(magic, sizeof(magic), (size_t)1, fp) != 1 ||
196                     strncmp(magic, ARMAG, SARMAG)) {
197                         warnx("%s: not object file or archive", fn);
198                         (void)fclose(fp);
199                         return(1);
200                 }
201                 retval = show_archive(fn, fp);
202         } else
203                 retval = show_objfile(fn, fp);
204         (void)fclose(fp);
205         return(retval);
206 }
207
208 /* scat: concatenate strings, returning new concatenation point
209  * and permitting overlap.
210  */
211 static char
212 *scat(char *dest, const char *src)
213 {
214         char *end;
215         int l1 = strlen(dest), l2 = strlen(src);
216
217         memmove(dest + l1, src, l2);
218         end = dest + l1 + l2;
219         *end = 0;
220
221         return end;
222 }
223
224 /*
225  * show_archive()
226  *      show symbols in the given archive file
227  */
228 int
229 show_archive(const char *fn, FILE *fp)
230 {
231         struct ar_hdr ar_head;
232         struct exec exec_head;
233         int i, rval;
234         long last_ar_off;
235         char *p, *name, *ar_name;
236         int extra = strlen(fn) + 3;
237
238         if ((name = malloc(MAXNAMLEN + extra)) == NULL)
239                 err(1, NULL);
240         ar_name = name + extra;
241
242         rval = 0;
243
244         /* while there are more entries in the archive */
245         while (fread((char *)&ar_head, sizeof(ar_head), (size_t)1, fp) == 1) {
246                 /* bad archive entry - stop processing this archive */
247                 if (strncmp(ar_head.ar_fmag, ARFMAG, sizeof(ar_head.ar_fmag))) {
248                         warnx("%s: bad format archive header", fn);
249                         (void)free(name);
250                         return(1);
251                 }
252
253                 /* remember start position of current archive object */
254                 last_ar_off = ftell(fp);
255
256                 /* skip ranlib entries */
257                 if (!bcmp(ar_head.ar_name, RANLIBMAG, sizeof(RANLIBMAG) - 1))
258                         goto skip;
259
260                 /* handle long names.  If one is present, read it in at the
261                  * end of the "name" buffer.
262                  */
263                 if (!bcmp(ar_head.ar_name, AR_EFMT1, sizeof(AR_EFMT1) - 1))
264                 {
265                         size_t len = atoi(ar_head.ar_name + sizeof(AR_EFMT1) - 1);
266
267                         if (len <= 0 || len > MAXNAMLEN)
268                         {
269                                 warnx("illegal length for format 1 long name");
270                                 goto skip;
271                         }
272                         if (fread(ar_name, 1, len, fp) != len)
273                         {
274                                 warnx("EOF reading format 1 long name");
275                                 (void)free(name);
276                                 return(1);
277                         }
278                         ar_name[len] = 0;
279                 }
280                 else
281                 {
282                         p = ar_head.ar_name;
283                         for (i = 0; i < (int)sizeof(ar_head.ar_name) && p[i] && p[i] != ' '; i++)
284                                         ar_name[i] = p[i];
285                         ar_name[i] = 0;
286                 }
287
288                 /*
289                  * construct a name of the form "archive.a:obj.o:" for the
290                  * current archive entry if the object name is to be printed
291                  * on each output line
292                  */
293                 p = name;
294                 *p = 0;
295                 if (print_file_each_line && !table)
296                 {
297                         p = scat(p, fn);
298                         p = scat(p, ":");
299                 }
300                 p = scat(p, ar_name);
301
302                 /* get and check current object's header */
303                 if (fread((char *)&exec_head, sizeof(exec_head), (size_t)1, fp) != 1) {
304                         warnx("%s: premature EOF", name);
305                         (void)free(name);
306                         return(1);
307                 }
308
309                 if (N_BADMAG(exec_head)) {
310                         if (!ignore_bad_archive_entries) {
311                                 warnx("%s: bad format", name);
312                                 rval = 1;
313                         }
314                 } else {
315                         (void)fseek(fp, -(long)sizeof(exec_head),
316                             SEEK_CUR);
317                         if (!print_file_each_line && !table)
318                                 (void)printf("\n%s:\n", name);
319                         rval |= show_objfile(name, fp);
320                 }
321
322                 /*
323                  * skip to next archive object - it starts at the next
324                  * even byte boundary
325                  */
326 #define even(x) (((x) + 1) & ~1)
327 skip:           if (fseek(fp, last_ar_off + even(atol(ar_head.ar_size)),
328                     SEEK_SET)) {
329                         warn("%s", fn);
330                         (void)free(name);
331                         return(1);
332                 }
333         }
334         (void)free(name);
335         return(rval);
336 }
337
338 /*
339  * show_objfile()
340  *      show symbols from the object file pointed to by fp.  The current
341  *      file pointer for fp is expected to be at the beginning of an a.out
342  *      header.
343  */
344 int
345 show_objfile(const char *objname, FILE *fp)
346 {
347         struct nlist *names, *np;
348         int i, nnames, nrawnames;
349         struct exec head;
350         int32_t stabsize;
351         char *stab;
352
353         /* read a.out header */
354         if (fread((char *)&head, sizeof(head), (size_t)1, fp) != 1) {
355                 warnx("%s: cannot read header", objname);
356                 return(1);
357         }
358
359         /*
360          * skip back to the header - the N_-macros return values relative
361          * to the beginning of the a.out header
362          */
363         if (fseek(fp, -(long)sizeof(head), SEEK_CUR)) {
364                 warn("%s", objname);
365                 return(1);
366         }
367
368         /* stop if this is no valid object file */
369         if (N_BADMAG(head)) {
370                 warnx("%s: bad format", objname);
371                 return(1);
372         }
373
374         /* stop if the object file contains no symbol table */
375         if (!head.a_syms) {
376                 warnx("%s: no name list", objname);
377                 return(1);
378         }
379
380         if (fseek(fp, (long)N_SYMOFF(head), SEEK_CUR)) {
381                 warn("%s", objname);
382                 return(1);
383         }
384
385         /* get memory for the symbol table */
386         if ((names = malloc((size_t)head.a_syms)) == NULL)
387                 err(1, NULL);
388         nrawnames = head.a_syms / sizeof(*names);
389         if (fread((char *)names, (size_t)head.a_syms, (size_t)1, fp) != 1) {
390                 warnx("%s: cannot read symbol table", objname);
391                 (void)free((char *)names);
392                 return(1);
393         }
394
395         /*
396          * Following the symbol table comes the string table.  The first
397          * 4-byte-integer gives the total size of the string table
398          * _including_ the size specification itself.
399          */
400         if (fread((char *)&stabsize, sizeof(stabsize), (size_t)1, fp) != 1) {
401                 warnx("%s: cannot read stab size", objname);
402                 (void)free((char *)names);
403                 return(1);
404         }
405         if ((stab = malloc((size_t)stabsize)) == NULL)
406                 err(1, NULL);
407
408         /*
409          * read the string table offset by 4 - all indices into the string
410          * table include the size specification.
411          */
412         stabsize -= 4;          /* we already have the size */
413         if (fread(stab + 4, (size_t)stabsize, (size_t)1, fp) != 1) {
414                 warnx("%s: stab truncated..", objname);
415                 (void)free((char *)names);
416                 (void)free(stab);
417                 return(1);
418         }
419
420         /*
421          * fix up the symbol table and filter out unwanted entries
422          *
423          * common symbols are characterized by a n_type of N_UNDF and a
424          * non-zero n_value -- change n_type to N_COMM for all such
425          * symbols to make life easier later.
426          *
427          * filter out all entries which we don't want to print anyway
428          */
429         for (np = names, i = nnames = 0; i < nrawnames; np++, i++) {
430                 if (SYMBOL_TYPE(np->n_type) == N_UNDF && np->n_value)
431                         np->n_type = N_COMM | (np->n_type & N_EXT);
432                 if (!print_all_symbols && IS_DEBUGGER_SYMBOL(np->n_type))
433                         continue;
434                 if (print_only_external_symbols && !IS_EXTERNAL(np->n_type))
435                         continue;
436                 if (print_only_undefined_symbols &&
437                     SYMBOL_TYPE(np->n_type) != N_UNDF)
438                         continue;
439
440                 /*
441                  * make n_un.n_name a character pointer by adding the string
442                  * table's base to n_un.n_strx
443                  *
444                  * don't mess with zero offsets
445                  */
446                 if (np->n_un.n_strx)
447                         np->n_un.n_name = stab + np->n_un.n_strx;
448                 else
449                         np->n_un.n_name = strdup("");
450                 names[nnames++] = *np;
451         }
452
453         /* sort the symbol table if applicable */
454         if (sfunc)
455                 qsort((char *)names, (size_t)nnames, sizeof(*names), sfunc);
456
457         /* print out symbols */
458         for (np = names, i = 0; i < nnames; np++, i++)
459                 print_symbol(objname, np);
460
461         (void)free((char *)names);
462         (void)free(stab);
463         return(0);
464 }
465
466 /*
467  * print_symbol()
468  *      show one symbol
469  */
470 void
471 print_symbol(const char *objname, struct nlist *sym)
472 {
473         if (table) {
474                 printf("%s|", objname);
475                 if (SYMBOL_TYPE(sym->n_type) != N_UNDF)
476                         (void)printf("%08lx", (u_long)sym->n_value);
477                 (void)printf("|");
478                 if (IS_DEBUGGER_SYMBOL(sym->n_type))
479                         (void)printf("-|%02x %04x %5s|", sym->n_other,
480                             sym->n_desc&0xffff, typestring(sym->n_type));
481                 else {
482                         putchar(typeletter(sym->n_type));
483                         if (print_weak_symbols && SYMBOL_BIND(sym->n_other)== 2)
484                                 putchar('W');
485                         putchar('|');
486                 }
487
488                 /* print the symbol's name */
489                 (void)printf("%s\n",sym->n_un.n_name);
490                 return;
491         }
492         if (print_file_each_line)
493                 (void)printf("%s:", objname);
494
495         /*
496          * handle undefined-only format separately (no space is
497          * left for symbol values, no type field is printed)
498          */
499         if (print_only_undefined_symbols) {
500                 (void)puts(sym->n_un.n_name);
501                 return;
502         }
503
504         /* print symbol's value */
505         if (SYMBOL_TYPE(sym->n_type) == N_UNDF)
506                 (void)printf("        ");
507         else
508                 (void)printf("%08lx", (u_long)sym->n_value);
509
510         /* print type information */
511         if (IS_DEBUGGER_SYMBOL(sym->n_type))
512                 (void)printf(" - %02x %04x %5s ", sym->n_other,
513                     sym->n_desc&0xffff, typestring(sym->n_type));
514         else {
515                 putchar(' ');
516                 putchar(typeletter(sym->n_type));
517                 if (print_weak_symbols) {
518                         if (SYMBOL_BIND(sym->n_other) == 2)
519                                 putchar('W');
520                         else
521                                 putchar(' ');
522                 }
523                 putchar(' ');
524         }
525
526         /* print the symbol's name */
527         (void)puts(sym->n_un.n_name);
528 }
529
530 /*
531  * typestring()
532  *      return the a description string for an STAB entry
533  */
534 const char *
535 typestring(u_char type)
536 {
537         switch(type) {
538         case N_BCOMM:
539                 return("BCOMM");
540         case N_ECOML:
541                 return("ECOML");
542         case N_ECOMM:
543                 return("ECOMM");
544         case N_ENTRY:
545                 return("ENTRY");
546         case N_FNAME:
547                 return("FNAME");
548         case N_FUN:
549                 return("FUN");
550         case N_GSYM:
551                 return("GSYM");
552         case N_LBRAC:
553                 return("LBRAC");
554         case N_LCSYM:
555                 return("LCSYM");
556         case N_LENG:
557                 return("LENG");
558         case N_LSYM:
559                 return("LSYM");
560         case N_PC:
561                 return("PC");
562         case N_PSYM:
563                 return("PSYM");
564         case N_RBRAC:
565                 return("RBRAC");
566         case N_RSYM:
567                 return("RSYM");
568         case N_SLINE:
569                 return("SLINE");
570         case N_SO:
571                 return("SO");
572         case N_SOL:
573                 return("SOL");
574         case N_SSYM:
575                 return("SSYM");
576         case N_STSYM:
577                 return("STSYM");
578         }
579         return("???");
580 }
581
582 /*
583  * typeletter()
584  *      return a description letter for the given basic type code of an
585  *      symbol table entry.  The return value will be upper case for
586  *      external, lower case for internal symbols.
587  */
588 char
589 typeletter(u_char type)
590 {
591         switch(SYMBOL_TYPE(type)) {
592         case N_ABS:
593                 return(IS_EXTERNAL(type) ? 'A' : 'a');
594         case N_BSS:
595                 return(IS_EXTERNAL(type) ? 'B' : 'b');
596         case N_COMM:
597                 return(IS_EXTERNAL(type) ? 'C' : 'c');
598         case N_DATA:
599                 return(IS_EXTERNAL(type) ? 'D' : 'd');
600         case N_FN:
601                 /* This one is overloaded. EXT = Filename, INT = warn refs */
602                 return(IS_EXTERNAL(type) ? 'F' : 'w');
603         case N_INDR:
604                 return(IS_EXTERNAL(type) ? 'I' : 'i');
605         case N_TEXT:
606                 return(IS_EXTERNAL(type) ? 'T' : 't');
607         case N_UNDF:
608                 return(IS_EXTERNAL(type) ? 'U' : 'u');
609         }
610         return('?');
611 }
612
613 int
614 fname(const void *a0, const void *b0)
615 {
616         const struct nlist *a = a0, *b = b0;
617
618         return(strcmp(a->n_un.n_name, b->n_un.n_name));
619 }
620
621 int
622 rname(const void *a0, const void *b0)
623 {
624         const struct nlist *a = a0, *b = b0;
625
626         return(strcmp(b->n_un.n_name, a->n_un.n_name));
627 }
628
629 int
630 value(const void *a0, const void *b0)
631 {
632         const struct nlist *a = a0, *b = b0;
633
634         if (SYMBOL_TYPE(a->n_type) == N_UNDF)
635                 if (SYMBOL_TYPE(b->n_type) == N_UNDF)
636                         return(0);
637                 else
638                         return(-1);
639         else if (SYMBOL_TYPE(b->n_type) == N_UNDF)
640                 return(1);
641         if (rev) {
642                 if (a->n_value == b->n_value)
643                         return(rname(a0, b0));
644                 return(b->n_value > a->n_value ? 1 : -1);
645         } else {
646                 if (a->n_value == b->n_value)
647                         return(fname(a0, b0));
648                 return(a->n_value > b->n_value ? 1 : -1);
649         }
650 }
651
652 static void
653 usage(void)
654 {
655         (void)fprintf(stderr, "usage: nm [-agnoprtuwW] [file ...]\n");
656         exit(1);
657 }