Add the <stdalign.h> header for C11 conformance.
[dragonfly.git] / usr.bin / ldd / sods.c
1 /*
2  * Copyright (C) 1996-1997 John D. Polstra.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY JOHN D. POLSTRA AND CONTRIBUTORS ``AS IS'' AND
14  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16  * ARE DISCLAIMED.  IN NO EVENT SHALL JOHN D. POLSTRA OR CONTRIBUTORS BE LIABLE
17  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23  * SUCH DAMAGE.
24  *
25  * $FreeBSD: src/usr.bin/ldd/sods.c,v 1.9.2.2 2001/07/11 23:59:11 obrien Exp $
26  */
27
28 #include <sys/param.h>
29 #include <assert.h>
30 #include <ctype.h>
31 #include <err.h>
32 #include <fcntl.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <unistd.h>
37
38 #include <sys/mman.h>
39 #include <sys/stat.h>
40 #include <machine/elf.h>
41
42 #define FREEBSD_AOUT
43
44 #include <a.out.h>
45 #include <sys/link_aout.h>
46 #include <stab.h>
47
48 #ifndef N_SETA
49 #define N_SETA  0x14            /* Absolute set element symbol */
50 #endif                          /* This is input to LD, in a .o file.  */
51
52 #ifndef N_SETT
53 #define N_SETT  0x16            /* Text set element symbol */
54 #endif                          /* This is input to LD, in a .o file.  */
55
56 #ifndef N_SETD
57 #define N_SETD  0x18            /* Data set element symbol */
58 #endif                          /* This is input to LD, in a .o file. */
59
60 #ifndef N_SETB
61 #define N_SETB  0x1A            /* Bss set element symbol */
62 #endif                          /* This is input to LD, in a .o file. */
63
64 #ifndef N_SETV
65 #define N_SETV  0x1C            /* Pointer to set vector in data area. */
66 #endif                          /* This is output from LD. */
67
68 #ifdef STANDALONE
69 static
70 #endif
71 void dump_file(const char *);
72
73 static void dump_rels(const char *, const struct relocation_info *,
74     unsigned long, const char *(*)(unsigned long), unsigned char *);
75 static void dump_segs();
76 static void dump_sods();
77 static void dump_sym(const struct nlist *);
78 static void dump_syms();
79
80 static void dump_rtsyms();
81
82 static const char *rtsym_name(unsigned long);
83 static const char *sym_name(unsigned long);
84
85 #ifdef STANDALONE
86 static
87 #endif
88 int error_count;
89
90 /*
91  * Variables ending in _base are pointers to things in our address space,
92  * i.e., in the file itself.
93  *
94  * Variables ending in _addr are adjusted according to where things would
95  * actually appear in memory if the file were loaded.
96  */
97 static const char *file_base;
98 static const char *text_base;
99 static const char *data_base;
100 static const struct relocation_info *rel_base;
101 static const struct nlist *sym_base;
102 static const char *str_base;
103
104 static const struct relocation_info *rtrel_base;
105 static const struct nzlist *rtsym_base;
106 static const char *rtstr_base;
107
108 static const struct exec *ex;
109 static const struct _dynamic *dyn;
110 static const struct section_dispatch_table *sdt;
111
112 static const char *text_addr;
113 static const char *data_addr;
114
115 static unsigned long rel_count;
116 static unsigned long sym_count;
117
118 static unsigned long rtrel_count;
119 static unsigned long rtsym_count;
120
121 /* Dynamically allocated flags, 1 byte per symbol, to record whether each
122    symbol was referenced by a relocation entry. */
123 static unsigned char *sym_used;
124 static unsigned char *rtsym_used;
125
126 static unsigned long origin;    /* What values are relocated relative to */
127
128 #ifdef STANDALONE
129 int
130 main(int argc, char *argv[])
131 {
132     int i;
133
134     for (i = 1;  i < argc;  ++i)
135         dump_file(argv[i]);
136
137     return error_count == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
138 }
139 #endif
140
141 #ifdef STANDALONE
142 static
143 #endif
144 void
145 dump_file(const char *fname)
146 {
147     int fd;
148     struct stat sb;
149     caddr_t objbase;
150
151     if (stat(fname, &sb) == -1) {
152         warnx("cannot stat \"%s\"", fname);
153         ++error_count;
154         return;
155     }
156
157     if ((sb.st_mode & S_IFMT) != S_IFREG) {
158         warnx("\"%s\" is not a regular file", fname);
159         ++error_count;
160         return;
161     }
162
163     if ((fd = open(fname, O_RDONLY, 0)) == -1) {
164         warnx("cannot open \"%s\"", fname);
165         ++error_count;
166         return;
167     }
168
169     objbase = mmap(0, sb.st_size, PROT_READ, MAP_SHARED, fd, 0);
170     if (objbase == (caddr_t) -1) {
171         warnx("cannot mmap \"%s\"", fname);
172         ++error_count;
173         close(fd);
174         return;
175     }
176
177     close(fd);
178
179     file_base = (const char *) objbase; /* Makes address arithmetic easier */
180
181     if (IS_ELF(*(Elf32_Ehdr*) file_base)) {
182         warnx("%s: this is an ELF program; use objdump to examine", fname);
183         ++error_count;
184         munmap(objbase, sb.st_size);
185         close(fd);
186         return;
187     }
188
189     ex = (const struct exec *) file_base;
190
191     printf("%s: a_midmag = 0x%lx\n", fname, ex->a_midmag);
192     printf("  magic = 0x%lx = 0%lo, netmagic = 0x%x = 0%o\n",
193         N_GETMAGIC(*ex), N_GETMAGIC(*ex),
194         N_GETMAGIC_NET(*ex), N_GETMAGIC_NET(*ex));
195
196     if (N_BADMAG(*ex)) {
197         warnx("%s: bad magic number", fname);
198         ++error_count;
199         munmap(objbase, sb.st_size);
200         return;
201     }
202
203     printf("  a_text   = 0x%lx\n", ex->a_text);
204     printf("  a_data   = 0x%lx\n", ex->a_data);
205     printf("  a_bss    = 0x%lx\n", ex->a_bss);
206     printf("  a_syms   = 0x%lx\n", ex->a_syms);
207     printf("  a_entry  = 0x%lx\n", ex->a_entry);
208     printf("  a_trsize = 0x%lx\n", ex->a_trsize);
209     printf("  a_drsize = 0x%lx\n", ex->a_drsize);
210
211     text_base = file_base + N_TXTOFF(*ex);
212     data_base = file_base + N_DATOFF(*ex);
213     rel_base = (const struct relocation_info *) (file_base + N_RELOFF(*ex));
214     sym_base = (const struct nlist *) (file_base + N_SYMOFF(*ex));
215     str_base = file_base + N_STROFF(*ex);
216
217     rel_count = (ex->a_trsize + ex->a_drsize) / sizeof rel_base[0];
218     assert(rel_count * sizeof rel_base[0] == ex->a_trsize + ex->a_drsize);
219     sym_count = ex->a_syms / sizeof sym_base[0];
220     assert(sym_count * sizeof sym_base[0] == ex->a_syms);
221
222     if (sym_count != 0) {
223         sym_used = (unsigned char *) calloc(sym_count, sizeof(unsigned char));
224         assert(sym_used != NULL);
225     }
226
227     printf("  Entry = 0x%lx\n", ex->a_entry);
228     printf("  Text offset = %x, address = %lx\n", N_TXTOFF(*ex),
229         N_TXTADDR(*ex));
230     printf("  Data offset = %lx, address = %lx\n", N_DATOFF(*ex),
231         N_DATADDR(*ex));
232
233     /*
234      * In an executable program file, everything is relocated relative to
235      * the assumed run-time load address, i.e., N_TXTADDR(*ex), i.e., 0x1000.
236      *
237      * In a shared library file, everything is relocated relative to the
238      * start of the file, i.e., N_TXTOFF(*ex), i.e., 0.
239      *
240      * The way to tell the difference is by looking at ex->a_entry.   If it
241      * is >= 0x1000, then we have an executable program.  Otherwise, we
242      * have a shared library.
243      *
244      * When a program is executed, the entire file is mapped into memory,
245      * including the a.out header and so forth.  But it is not mapped at
246      * address 0; rather it is mapped at address 0x1000.  The first page
247      * of the user's address space is left unmapped in order to catch null
248      * pointer dereferences.
249      *
250      * In this program, when we map in an executable program, we have to
251      * simulate the empty page by decrementing our assumed base address by
252      * a pagesize.
253      */
254
255     text_addr = text_base;
256     data_addr = data_base;
257     origin = 0;
258
259     if (ex->a_entry >= PAGE_SIZE) {     /* Executable, not a shared library */
260         /*
261          * The fields in the object have already been relocated on the
262          * assumption that the object will be loaded at N_TXTADDR(*ex).
263          * We have to compensate for that.
264          */
265         text_addr -= PAGE_SIZE;
266         data_addr -= PAGE_SIZE;
267         origin = PAGE_SIZE;
268         printf("  Program, origin = %lx\n", origin);
269     } else if (N_GETFLAG(*ex) & EX_DYNAMIC)
270         printf("  Shared library, origin = %lx\n", origin);
271     else
272         printf("  Object file, origin = %lx\n", origin);
273
274     if (N_GETFLAG(*ex) & EX_DYNAMIC) {
275         dyn = (const struct _dynamic *) data_base;
276         printf("  Dynamic version = %d\n", dyn->d_version);
277
278         sdt = (const struct section_dispatch_table *)
279             (text_addr + (unsigned long) dyn->d_un.d_sdt);
280
281         rtrel_base =
282             (const struct relocation_info *) (text_addr + sdt->sdt_rel);
283         rtrel_count = (sdt->sdt_hash - sdt->sdt_rel) / sizeof rtrel_base[0];
284         assert(rtrel_count * sizeof rtrel_base[0] ==
285             sdt->sdt_hash - sdt->sdt_rel);
286
287         rtsym_base = (const struct nzlist *) (text_addr + sdt->sdt_nzlist);
288         rtsym_count = (sdt->sdt_strings - sdt->sdt_nzlist) /
289             sizeof rtsym_base[0];
290         assert(rtsym_count * sizeof rtsym_base[0] ==
291             sdt->sdt_strings - sdt->sdt_nzlist);
292
293         if (rtsym_count != 0) {
294             rtsym_used = (unsigned char *) calloc(rtsym_count,
295                 sizeof(unsigned char));
296             assert(rtsym_used != NULL);
297         }
298
299         rtstr_base = text_addr + sdt->sdt_strings;
300     }
301
302     dump_segs();
303     dump_sods();
304     dump_rels("Relocations", rel_base, rel_count, sym_name, sym_used);
305     dump_syms();
306
307     dump_rels("Run-time relocations", rtrel_base, rtrel_count, rtsym_name,
308         rtsym_used);
309     dump_rtsyms();
310
311     if (rtsym_used != NULL) {
312         free(rtsym_used);
313         rtsym_used = NULL;
314     }
315     if (sym_used != NULL) {
316         free(sym_used);
317         sym_used = NULL;
318     }
319     munmap(objbase, sb.st_size);
320 }
321
322 static void
323 dump_rels(const char *label, const struct relocation_info *base,
324     unsigned long count, const char *(*name)(unsigned long),
325     unsigned char *sym_used_flags)
326 {
327     unsigned long i;
328
329     printf("  %s:\n", label);
330     for (i = 0;  i < count;  ++i) {
331         const struct relocation_info *r = &base[i];
332         unsigned int size;
333         char contents[16];
334
335         size = 1u << r->r_length;
336
337         if (origin <= r->r_address
338           && r->r_address < origin + ex->a_text + ex->a_data
339           && 1 <= size && size <= 4) {
340             /*
341              * XXX - This can cause unaligned accesses.  OK for the
342              * i386, not so for other architectures.
343              */
344             switch (size) {
345             case 1:
346                 snprintf(contents, sizeof contents, "      [%02x]",
347                   *(unsigned char *)(text_addr + r->r_address));
348                 break;
349             case 2:
350                 snprintf(contents, sizeof contents, "    [%04x]",
351                   *(unsigned short *)(text_addr + r->r_address));
352                 break;
353             case 4:
354                 snprintf(contents, sizeof contents, "[%08lx]",
355                   *(unsigned long *)(text_addr + r->r_address));
356                 break;
357             }
358         } else
359             snprintf(contents, sizeof contents, "          ");
360
361         printf("    %6lu %8x/%u %s %c%c%c%c%c%c", i,
362             r->r_address, size,
363             contents,
364             r->r_extern   ? 'e' : '-',
365             r->r_jmptable ? 'j' : '-',
366             r->r_relative ? 'r' : '-',
367             r->r_baserel  ? 'b' : '-',
368             r->r_pcrel    ? 'p' : '-',
369             r->r_copy     ? 'c' : '-');
370
371         if (r->r_extern || r->r_baserel || r->r_jmptable || r->r_copy) {
372             printf(" %4u %s", r->r_symbolnum, name(r->r_symbolnum));
373             sym_used_flags[r->r_symbolnum] = 1;
374         }
375
376         printf("\n");
377     }
378 }
379
380 static void
381 dump_rtsyms(void)
382 {
383     unsigned long i;
384
385     printf("  Run-time symbols:\n");
386     for (i = 0;  i < rtsym_count;  ++i) {
387         printf("    %6lu%c ", i, rtsym_used[i] ? '*' : ' ');
388         dump_sym(&rtsym_base[i].nlist);
389         printf("/%-5ld %s\n", rtsym_base[i].nz_size, rtsym_name(i));
390     }
391 }
392
393 static void
394 dump_segs(void)
395 {
396     printf("  Text segment starts at address %lx\n", origin + N_TXTOFF(*ex));
397     if (N_GETFLAG(*ex) & EX_DYNAMIC) {
398         printf("    rel starts at %lx\n", sdt->sdt_rel);
399         printf("    hash starts at %lx\n", sdt->sdt_hash);
400         printf("    nzlist starts at %lx\n", sdt->sdt_nzlist);
401         printf("    strings starts at %lx\n", sdt->sdt_strings);
402     }
403
404     printf("  Data segment starts at address %lx\n", origin + N_DATOFF(*ex));
405     if (N_GETFLAG(*ex) & EX_DYNAMIC) {
406         printf("    _dynamic starts at %lx\n", origin + N_DATOFF(*ex));
407         printf("    so_debug starts at %lx\n", (unsigned long) dyn->d_debug);
408         printf("    sdt starts at %lx\n", (unsigned long) dyn->d_un.d_sdt);
409         printf("    got starts at %lx\n", sdt->sdt_got);
410         printf("    plt starts at %lx\n", sdt->sdt_plt);
411         printf("    rest of stuff starts at %lx\n",
412             sdt->sdt_plt + sdt->sdt_plt_sz);
413     }
414 }
415
416 static void
417 dump_sods(void)
418 {
419     long sod_offset;
420     long paths_offset;
421
422     if (dyn == NULL)            /* Not a shared object */
423         return;
424
425     sod_offset = sdt->sdt_sods;
426     printf("  Shared object dependencies:\n");
427     while (sod_offset != 0) {
428         const struct sod *sodp = (const struct sod *) (text_addr + sod_offset);
429         const char *name = (const char *) (text_addr + sodp->sod_name);
430
431         if (sodp->sod_library)
432             printf("    -l%-16s version %d.%d\n", name, sodp->sod_major,
433                 sodp->sod_minor);
434         else
435             printf("    %s\n", name);
436         sod_offset = sodp->sod_next;
437     }
438     paths_offset = sdt->sdt_paths;
439     printf("  Shared object additional paths:\n");
440     if (paths_offset != 0) {
441         char *path = (char *)(text_addr + paths_offset);
442         printf("    %s\n", path);
443     } else {
444         printf("    (none)\n");
445     }
446 }
447
448 static void
449 dump_sym(const struct nlist *np)
450 {
451     char type[8];
452     char aux[8];
453     char weak;
454     char *p;
455
456     switch (np->n_type & ~N_EXT) {
457     case N_UNDF:        strcpy(type, "undf");  break;
458     case N_ABS:         strcpy(type, "abs");  break;
459     case N_TEXT:        strcpy(type, "text");  break;
460     case N_DATA:        strcpy(type, "data");  break;
461     case N_BSS:         strcpy(type, "bss");  break;
462     case N_INDR:        strcpy(type, "indr");  break;
463     case N_SIZE:        strcpy(type, "size");  break;
464     case N_COMM:        strcpy(type, "comm");  break;
465     case N_SETA:        strcpy(type, "seta");  break;
466     case N_SETT:        strcpy(type, "sett");  break;
467     case N_SETD:        strcpy(type, "setd");  break;
468     case N_SETB:        strcpy(type, "setb");  break;
469     case N_SETV:        strcpy(type, "setv");  break;
470     case N_FN:          strcpy(type, np->n_type&N_EXT ? "fn" : "warn");  break;
471     case N_GSYM:        strcpy(type, "gsym");  break;
472     case N_FNAME:       strcpy(type, "fname");  break;
473     case N_FUN:         strcpy(type, "fun");  break;
474     case N_STSYM:       strcpy(type, "stsym");  break;
475     case N_LCSYM:       strcpy(type, "lcsym");  break;
476     case N_MAIN:        strcpy(type, "main");  break;
477     case N_PC:          strcpy(type, "pc");  break;
478     case N_RSYM:        strcpy(type, "rsym");  break;
479     case N_SLINE:       strcpy(type, "sline");  break;
480     case N_DSLINE:      strcpy(type, "dsline");  break;
481     case N_BSLINE:      strcpy(type, "bsline");  break;
482     case N_SSYM:        strcpy(type, "ssym");  break;
483     case N_SO:          strcpy(type, "so");  break;
484     case N_LSYM:        strcpy(type, "lsym");  break;
485     case N_BINCL:       strcpy(type, "bincl");  break;
486     case N_SOL:         strcpy(type, "sol");  break;
487     case N_PSYM:        strcpy(type, "psym");  break;
488     case N_EINCL:       strcpy(type, "eincl");  break;
489     case N_ENTRY:       strcpy(type, "entry");  break;
490     case N_LBRAC:       strcpy(type, "lbrac");  break;
491     case N_EXCL:        strcpy(type, "excl");  break;
492     case N_RBRAC:       strcpy(type, "rbrac");  break;
493     case N_BCOMM:       strcpy(type, "bcomm");  break;
494     case N_ECOMM:       strcpy(type, "ecomm");  break;
495     case N_ECOML:       strcpy(type, "ecoml");  break;
496     case N_LENG:        strcpy(type, "leng");  break;
497     default:
498         snprintf(type, sizeof type, "%#02x", np->n_type);
499         break;
500     }
501
502     if (np->n_type & N_EXT && type[0] != '0')
503         for (p = type;  *p != '\0';  ++p)
504             *p = toupper(*p);
505
506     switch (N_AUX(np)) {
507     case 0:             strcpy(aux, "");  break;
508     case AUX_OBJECT:    strcpy(aux, "objt");  break;
509     case AUX_FUNC:      strcpy(aux, "func");  break;
510     default:            snprintf(aux, sizeof aux, "%#01x", N_AUX(np));  break;
511     }
512
513     weak = N_BIND(np) == BIND_WEAK ? 'w' : ' ';
514
515     printf("%c%-6s %-4s %8lx", weak, type, aux, np->n_value);
516 }
517
518 static void
519 dump_syms(void)
520 {
521     unsigned long i;
522
523     printf("  Symbols:\n");
524     for (i = 0;  i < sym_count;  ++i) {
525         printf("    %6lu%c ", i, sym_used[i] ? '*' : ' ');
526         dump_sym(&sym_base[i]);
527         printf(" %s\n", sym_name(i));
528     }
529 }
530
531 static const char *
532 rtsym_name(unsigned long n)
533 {
534     assert(n < rtsym_count);
535     if (rtsym_base[n].nz_strx == 0)
536         return "";
537     return rtstr_base + rtsym_base[n].nz_strx;
538 }
539
540 static const char *
541 sym_name(unsigned long n)
542 {
543     assert(n < sym_count);
544     if (sym_base[n].n_un.n_strx == 0)
545         return "";
546     return str_base + sym_base[n].n_un.n_strx;
547 }