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