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