OSDN Git Service

Cleanup whitespace and formatting
[uclinux-h8/uClibc.git] / utils / ldd.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * A small little ldd implementation for uClibc
4  *
5  * Copyright (C) 2000-2004 Erik Andersen <andersee@debian.org>
6  *
7  * Several functions in this file (specifically, elf_find_section_type(),
8  * elf_find_phdr_type(), and elf_find_dynamic(), were stolen from elflib.c from
9  * elfvector (http://www.BitWagon.com/elfvector.html) by John F. Reiser
10  * <jreiser@BitWagon.com>, which is copyright 2000 BitWagon Software LLC
11  * (GPL2).
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21  * General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software
25  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26  *
27  */
28
29
30 #define _GNU_SOURCE
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <fcntl.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <sys/mman.h>
37 #include <sys/stat.h>
38 #include <sys/types.h>
39 #include <sys/types.h>
40 #include <sys/wait.h>
41
42 #include "bswap.h"
43 #if defined (sun)
44 #include "link.h"
45 #else
46 #include "elf.h"
47 #endif
48
49 #ifdef DMALLOC
50 #include <dmalloc.h>
51 #endif
52
53 #if defined(__arm__)
54 #define MATCH_MACHINE(x) (x == EM_ARM)
55 #define ELFCLASSM       ELFCLASS32
56 #endif
57
58 #if defined(__s390__)
59 #define MATCH_MACHINE(x) (x == EM_S390)
60 #define ELFCLASSM       ELFCLASS32
61 #endif
62
63 #if defined(__i386__)
64 #ifndef EM_486
65 #define MATCH_MACHINE(x) (x == EM_386)
66 #else
67 #define MATCH_MACHINE(x) (x == EM_386 || x == EM_486)
68 #endif
69 #define ELFCLASSM       ELFCLASS32
70 #endif
71
72 #if defined(__mc68000__)
73 #define MATCH_MACHINE(x) (x == EM_68K)
74 #define ELFCLASSM       ELFCLASS32
75 #endif
76
77 #if defined(__mips__)
78 #define MATCH_MACHINE(x) (x == EM_MIPS || x == EM_MIPS_RS3_LE)
79 #define ELFCLASSM       ELFCLASS32
80 #endif
81
82 #if defined(__powerpc__)
83 #define MATCH_MACHINE(x) (x == EM_PPC)
84 #define ELFCLASSM       ELFCLASS32
85 #endif
86
87 #if defined(__sh__)
88 #define MATCH_MACHINE(x) (x == EM_SH)
89 #define ELFCLASSM       ELFCLASS32
90 #endif
91
92 #if defined (__v850e__)
93 #define MATCH_MACHINE(x) ((x) == EM_V850 || (x) == EM_CYGNUS_V850)
94 #define ELFCLASSM       ELFCLASS32
95 #endif
96
97 #if defined (__sparc__)
98 #define MATCH_MACHINE(x) ((x) == EM_SPARC || (x) == EM_SPARC32PLUS)
99 #define ELFCLASSM    ELFCLASS32
100 #endif
101
102 #if defined(__cris__)
103 #define MATCH_MACHINE(x) (x == EM_CRIS)
104 #define ELFCLASSM       ELFCLASS32
105 #endif
106
107 #ifndef MATCH_MACHINE
108 #warning "You really should add a MATCH_MACHINE() macro for your architecture"
109 #endif
110
111 #if __BYTE_ORDER == __LITTLE_ENDIAN
112 #define ELFDATAM        ELFDATA2LSB
113 #elif __BYTE_ORDER == __BIG_ENDIAN
114 #define ELFDATAM        ELFDATA2MSB
115 #endif
116
117 struct library {
118         char *name;
119         int resolved;
120         char *path;
121         struct library *next;
122 };
123 struct library *lib_list = NULL;
124 char not_found[] = "not found";
125 char *interp = NULL;
126 char *interp_dir = NULL;
127 int byteswap;
128 static int interpreter_already_found=0;
129
130 inline uint32_t byteswap32_to_host(uint32_t value)
131 {
132         if (byteswap==1) {
133                 return(bswap_32(value));
134         } else {
135                 return(value);
136         }
137 }
138
139 Elf32_Shdr * elf_find_section_type( int key, Elf32_Ehdr *ehdr)
140 {
141         int j;
142         Elf32_Shdr *shdr;
143         shdr = (Elf32_Shdr *)(ehdr->e_shoff + (char *)ehdr);
144         for (j = ehdr->e_shnum; --j>=0; ++shdr) {
145                 if (key==(int)byteswap32_to_host(shdr->sh_type)) {
146                         return shdr;
147                 }
148         }
149         return NULL;
150 }
151
152 Elf32_Phdr * elf_find_phdr_type( int type, Elf32_Ehdr *ehdr)
153 {
154         int j;
155         Elf32_Phdr *phdr = (Elf32_Phdr *)(ehdr->e_phoff + (char *)ehdr);
156         for (j = ehdr->e_phnum; --j>=0; ++phdr) {
157                 if (type==(int)byteswap32_to_host(phdr->p_type)) {
158                         return phdr;
159                 }
160         }
161         return NULL;
162 }
163
164 /* Returns value if return_val==1, ptr otherwise */
165 void * elf_find_dynamic(int const key, Elf32_Dyn *dynp,
166         Elf32_Ehdr *ehdr, int return_val)
167 {
168         Elf32_Phdr *pt_text = elf_find_phdr_type(PT_LOAD, ehdr);
169         unsigned tx_reloc = byteswap32_to_host(pt_text->p_vaddr) - byteswap32_to_host(pt_text->p_offset);
170         for (; DT_NULL!=byteswap32_to_host(dynp->d_tag); ++dynp) {
171                 if (key == (int)byteswap32_to_host(dynp->d_tag)) {
172                         if (return_val == 1)
173                                 return (void *)(intptr_t)byteswap32_to_host(dynp->d_un.d_val);
174                         else
175                                 return (void *)(byteswap32_to_host(dynp->d_un.d_val) - tx_reloc + (char *)ehdr );
176                 }
177         }
178         return NULL;
179 }
180
181 static char * elf_find_rpath(Elf32_Ehdr* ehdr, Elf32_Dyn* dynamic)
182 {
183         Elf32_Dyn  *dyns;
184
185         for (dyns=dynamic; byteswap32_to_host(dyns->d_tag)!=DT_NULL; ++dyns) {
186                 if (DT_RPATH == byteswap32_to_host(dyns->d_tag)) {
187                         char *strtab;
188                         strtab = (char *)elf_find_dynamic(DT_STRTAB, dynamic, ehdr, 0);
189                         return ((char*)strtab + byteswap32_to_host(dyns->d_un.d_val));
190                 }
191         }
192         return NULL;
193 }
194
195 int check_elf_header(Elf32_Ehdr *const ehdr)
196 {
197         if (! ehdr || strncmp((void *)ehdr, ELFMAG, SELFMAG) != 0 ||
198                         ehdr->e_ident[EI_CLASS] != ELFCLASS32 ||
199                         ehdr->e_ident[EI_VERSION] != EV_CURRENT)
200         {
201                 return 1;
202         }
203
204         /* Check if the target endianness matches the host's endianness */
205         byteswap = 0;
206 #if __BYTE_ORDER == __LITTLE_ENDIAN
207         if (ehdr->e_ident[5] == ELFDATA2MSB) {
208                 /* Ick -- we will have to byte-swap everything */
209                 byteswap = 1;
210         }
211 #elif __BYTE_ORDER == __BIG_ENDIAN
212         if (ehdr->e_ident[5] == ELFDATA2LSB) {
213                 /* Ick -- we will have to byte-swap everything */
214                 byteswap = 1;
215         }
216 #else
217 #error Unknown host byte order!
218 #endif
219
220         /* Be vary lazy, and only byteswap the stuff we use */
221         if (byteswap==1) {
222                 ehdr->e_type=bswap_16(ehdr->e_type);
223                 ehdr->e_phoff=bswap_32(ehdr->e_phoff);
224                 ehdr->e_shoff=bswap_32(ehdr->e_shoff);
225                 ehdr->e_phnum=bswap_16(ehdr->e_phnum);
226                 ehdr->e_shnum=bswap_16(ehdr->e_shnum);
227         }
228
229         return 0;
230 }
231
232 /* This function's behavior must exactly match that
233  * in uClibc/ldso/ldso/readelflib1.c */
234 static void search_for_named_library(char *name, char *result, const char *path_list)
235 {
236         int i, count = 1;
237         char *path, *path_n;
238         struct stat filestat;
239
240         /* We need a writable copy of this string */
241         path = strdup(path_list);
242         if (!path) {
243                 fprintf(stderr, "Out of memory!\n");
244                 exit(EXIT_FAILURE);
245         }
246         /* Eliminate all double //s */
247         path_n=path;
248         while((path_n=strstr(path_n, "//"))) {
249                 i = strlen(path_n);
250                 memmove(path_n, path_n+1, i-1);
251                 *(path_n + i - 1)='\0';
252         }
253
254         /* Replace colons with zeros in path_list and count them */
255         for(i=strlen(path); i > 0; i--) {
256                 if (path[i]==':') {
257                         path[i]=0;
258                         count++;
259                 }
260         }
261         path_n = path;
262         for (i = 0; i < count; i++) {
263                 strcpy(result, path_n);
264                 strcat(result, "/");
265                 strcat(result, name);
266                 if (stat (result, &filestat) == 0 && filestat.st_mode & S_IRUSR) {
267                         free(path);
268                         return;
269                 }
270                 path_n += (strlen(path_n) + 1);
271         }
272         free(path);
273         *result = '\0';
274 }
275
276 void locate_library_file(Elf32_Ehdr* ehdr, Elf32_Dyn* dynamic, int is_suid, struct library *lib)
277 {
278         char *buf;
279         char *path;
280         struct stat filestat;
281
282         /* If this is a fully resolved name, our job is easy */
283         if (stat (lib->name, &filestat) == 0) {
284                 lib->path = lib->name;
285                 return;
286         }
287
288         /* We need some elbow room here.  Make some room...*/
289         buf = malloc(1024);
290         if (!buf) {
291                 fprintf(stderr, "Out of memory!\n");
292                 exit(EXIT_FAILURE);
293         }
294
295         /* This function must match the behavior of _dl_load_shared_library
296          * in readelflib1.c or things won't work out as expected... */
297
298         /* The ABI specifies that RPATH is searched first, so do that now.  */
299         path = elf_find_rpath(ehdr, dynamic);
300         if (path) {
301                 search_for_named_library(lib->name, buf, path);
302                 if (*buf != '\0') {
303                         lib->path = buf;
304                         return;
305                 }
306         }
307
308         /* Next check LD_{ELF_}LIBRARY_PATH if specified and allowed.
309          * Since this app doesn't actually run an executable I will skip
310          * the suid check, and just use LD_{ELF_}LIBRARY_PATH if set */
311         if (is_suid==1)
312                 path = NULL;
313         else
314                 path = getenv("LD_LIBRARY_PATH");
315         if (path) {
316                 search_for_named_library(lib->name, buf, path);
317                 if (*buf != '\0') {
318                         lib->path = buf;
319                         return;
320                 }
321         }
322
323 #ifdef USE_CACHE
324         /* FIXME -- add code to check the Cache here */
325 #endif
326
327
328         /* Next look for libraries wherever the shared library
329          * loader was installed -- this is usually where we
330          * should find things... */
331         if (interp_dir) {
332                 search_for_named_library(lib->name, buf, interp_dir);
333                 if (*buf != '\0') {
334                         lib->path = buf;
335                         return;
336                 }
337         }
338
339         /* Lastly, search the standard list of paths for the library.
340            This list must exactly match the list in uClibc/ldso/ldso/readelflib1.c */
341         path =  UCLIBC_RUNTIME_PREFIX "usr/X11R6/lib:"
342                 UCLIBC_RUNTIME_PREFIX "usr/lib:"
343                 UCLIBC_RUNTIME_PREFIX "lib:"
344                 "/usr/lib:"
345                 "/lib";
346         search_for_named_library(lib->name, buf, path);
347         if (*buf != '\0') {
348                 lib->path = buf;
349         } else {
350                 free(buf);
351                 lib->path = not_found;
352         }
353 }
354
355 static int add_library(Elf32_Ehdr* ehdr, Elf32_Dyn* dynamic, int is_setuid, char *s)
356 {
357         char *tmp, *tmp1, *tmp2;
358         struct library *cur, *newlib=lib_list;
359
360         if (!s || !strlen(s))
361                 return 1;
362
363         tmp = s;
364         while (*tmp) {
365                 if (*tmp == '/')
366                         s = tmp + 1;
367                 tmp++;
368         }
369
370         /* We add libc.so.0 elsewhere */
371         if (interpreter_already_found && (tmp=strrchr(interp, '/')) != NULL)
372         {
373                 int len = strlen(interp_dir);
374                 if (strcmp(s, interp+1+len)==0)
375                         return 1;
376         }
377
378         for (cur = lib_list; cur; cur=cur->next) {
379                 /* Check if this library is already in the list */
380                 tmp1 = tmp2 = cur->name;
381                 while (*tmp1) {
382                         if (*tmp1 == '/')
383                                 tmp2 = tmp1 + 1;
384                         tmp1++;
385                 }
386                 if(strcmp(tmp2, s)==0) {
387                         //printf("find_elf_interpreter is skipping '%s' (already in list)\n", cur->name);
388                         return 0;
389                 }
390         }
391
392         /* Ok, this lib needs to be added to the list */
393         newlib = malloc(sizeof(struct library));
394         if (!newlib)
395                 return 1;
396         newlib->name = malloc(strlen(s)+1);
397         strcpy(newlib->name, s);
398         newlib->resolved = 0;
399         newlib->path = NULL;
400         newlib->next = NULL;
401
402         /* Now try and locate where this library might be living... */
403         locate_library_file(ehdr, dynamic, is_setuid, newlib);
404
405         //printf("add_library is adding '%s' to '%s'\n", newlib->name, newlib->path);
406         if (!lib_list) {
407                 lib_list = newlib;
408         } else {
409                 for (cur = lib_list;  cur->next; cur=cur->next); /* nothing */
410                 cur->next = newlib;
411         }
412         return 0;
413 }
414
415 static void find_needed_libraries(Elf32_Ehdr* ehdr,
416                 Elf32_Dyn* dynamic, int is_setuid)
417 {
418         Elf32_Dyn  *dyns;
419
420         for (dyns=dynamic; byteswap32_to_host(dyns->d_tag)!=DT_NULL; ++dyns) {
421                 if (DT_NEEDED == byteswap32_to_host(dyns->d_tag)) {
422                         char *strtab;
423                         strtab = (char *)elf_find_dynamic(DT_STRTAB, dynamic, ehdr, 0);
424                         add_library(ehdr, dynamic, is_setuid,
425                                         (char*)strtab + byteswap32_to_host(dyns->d_un.d_val));
426                 }
427         }
428 }
429
430 static struct library * find_elf_interpreter(Elf32_Ehdr* ehdr)
431 {
432         Elf32_Phdr *phdr;
433
434         if (interpreter_already_found==1)
435                 return NULL;
436         phdr = elf_find_phdr_type(PT_INTERP, ehdr);
437         if (phdr) {
438                 struct library *cur, *newlib=NULL;
439                 char *s = (char*)ehdr + byteswap32_to_host(phdr->p_offset);
440
441                 char *tmp, *tmp1;
442                 interp = strdup(s);
443                 interp_dir = strdup(s);
444                 tmp = strrchr(interp_dir, '/');
445                 if (*tmp)
446                         *tmp = '\0';
447                 else {
448                         free(interp_dir);
449                         interp_dir = interp;
450                 }
451                 tmp1 = tmp = s;
452                 while (*tmp) {
453                         if (*tmp == '/')
454                                 tmp1 = tmp + 1;
455                         tmp++;
456                 }
457                 for (cur = lib_list; cur; cur=cur->next) {
458                         /* Check if this library is already in the list */
459                         if(strcmp(cur->name, tmp1)==0) {
460                                 //printf("find_elf_interpreter is replacing '%s' (already in list)\n", cur->name);
461                                 newlib = cur;
462                                 free(newlib->name);
463                                 free(newlib->path);
464                                 return NULL;
465                         }
466                 }
467                 if (newlib == NULL)
468                         newlib = malloc(sizeof(struct library));
469                 if (!newlib)
470                         return NULL;
471                 newlib->name = malloc(strlen(s)+1);
472                 strcpy(newlib->name, s);
473                 newlib->path = newlib->name;
474                 newlib->resolved = 1;
475                 newlib->next = NULL;
476
477 #if 0
478                 //printf("find_elf_interpreter is adding '%s' to '%s'\n", newlib->name, newlib->path);
479                 if (!lib_list) {
480                         lib_list = newlib;
481                 } else {
482                         for (cur = lib_list;  cur->next; cur=cur->next); /* nothing */
483                         cur->next = newlib;
484                 }
485 #endif
486                 interpreter_already_found=1;
487                 return newlib;
488         }
489         return NULL;
490 }
491
492 /* map the .so, and locate interesting pieces */
493 int find_dependancies(char* filename)
494 {
495         int is_suid = 0;
496         FILE *thefile;
497         struct stat statbuf;
498         Elf32_Ehdr *ehdr = NULL;
499         Elf32_Shdr *dynsec = NULL;
500         Elf32_Dyn *dynamic = NULL;
501         struct library *interp;
502
503         if (filename == not_found)
504                 return 0;
505
506         if (!filename) {
507                 fprintf(stderr, "No filename specified.\n");
508                 return -1;
509         }
510         if (!(thefile = fopen(filename, "r"))) {
511                 perror(filename);
512                 return -1;
513         }
514         if (fstat(fileno(thefile), &statbuf) < 0) {
515                 perror(filename);
516                 return -1;
517         }
518
519         if ((size_t)statbuf.st_size < sizeof(Elf32_Ehdr))
520                 goto foo;
521
522         if (!S_ISREG(statbuf.st_mode))
523                 goto foo;
524
525         /* mmap the file to make reading stuff from it effortless */
526         ehdr = (Elf32_Ehdr *)mmap(0, statbuf.st_size, 
527                         PROT_READ|PROT_WRITE, MAP_PRIVATE, fileno(thefile), 0);
528
529 foo:
530         /* Check if this looks like a legit ELF file */
531         if (check_elf_header(ehdr)) {
532                 fprintf(stderr, "%s: not an ELF file.\n", filename);
533                 return -1;
534         }
535         /* Check if this is the right kind of ELF file */
536         if (ehdr->e_type != ET_EXEC && ehdr->e_type != ET_DYN) {
537                 fprintf(stderr, "%s: not a dynamic executable\n", filename);
538                 return -1;
539         }
540         if (ehdr->e_type == ET_EXEC) {
541                 if (statbuf.st_mode & S_ISUID)
542                         is_suid = 1;
543                 if ((statbuf.st_mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP))
544                         is_suid = 1;
545                 /* FIXME */
546                 if (is_suid)
547                         fprintf(stderr, "%s: is setuid\n", filename);
548         }
549
550         interpreter_already_found=0;
551         interp = find_elf_interpreter(ehdr);
552
553 #ifdef __LDSO_LDD_SUPPORT
554         if (interp && ehdr->e_type == ET_EXEC && ehdr->e_ident[EI_CLASS] == ELFCLASSM &&
555                         ehdr->e_ident[EI_DATA] == ELFDATAM
556                         && ehdr->e_ident[EI_VERSION] == EV_CURRENT && MATCH_MACHINE(ehdr->e_machine))
557         {
558                 struct stat statbuf;
559                 if (stat(interp->path, &statbuf) == 0 && S_ISREG(statbuf.st_mode)) {
560                         pid_t pid;
561                         int status;
562                         static const char * const environment[] = {
563                                 "PATH=/usr/bin:/bin:/usr/sbin:/sbin",
564                                 "SHELL=/bin/sh",
565                                 "LD_TRACE_LOADED_OBJECTS=1",
566                                 NULL
567                         };
568
569                         if ((pid = fork()) == 0) {
570                                 /* Cool, it looks like we should be able to actually
571                                  * run this puppy.  Do so now... */
572                                 execle(filename, filename, NULL, environment);
573                                 _exit(0xdead);
574                         }
575
576                         /* Wait till it returns */
577                         waitpid(pid, &status, 0);
578                         if (WIFEXITED(status) && WEXITSTATUS(status)==0) {
579                                 return 1;
580                         }
581
582                         /* If the exec failed, we fall through to trying to find
583                          * all the needed libraries ourselves by rummaging about
584                          * in the ELF headers... */
585                 }
586         }
587 #endif
588
589         dynsec = elf_find_section_type(SHT_DYNAMIC, ehdr);
590         if (dynsec) {
591                 dynamic = (Elf32_Dyn*)(byteswap32_to_host(dynsec->sh_offset) + (intptr_t)ehdr);
592                 find_needed_libraries(ehdr, dynamic, is_suid);
593         }
594
595         return 0;
596 }
597
598 int main( int argc, char** argv)
599 {
600         int multi=0;
601         int got_em_all=1;
602         char *filename = NULL;
603         struct library *cur;
604
605         if (argc < 2) {
606                 fprintf(stderr, "ldd: missing file arguments\n");
607                 fprintf(stderr, "Try `ldd --help' for more information.\n");
608                 exit(EXIT_FAILURE);
609         }
610         if (argc > 2) {
611                 multi++;
612         }
613
614         while (--argc > 0) {
615                 ++argv;
616
617                 if(strcmp(*argv, "--")==0) {
618                         /* Ignore "--" */
619                         continue;
620                 }
621
622                 if(strcmp(*argv, "--help")==0) {
623                         fprintf(stderr, "Usage: ldd [OPTION]... FILE...\n");
624                         fprintf(stderr, "\t--help\t\tprint this help and exit\n");
625                         exit(EXIT_FAILURE);
626                 }
627
628                 filename=*argv;
629                 if (!filename) {
630                         fprintf(stderr, "No filename specified.\n");
631                         exit(EXIT_FAILURE);
632                 }
633
634                 if (multi) {
635                         printf("%s:\n", *argv);
636                 }
637
638                 if (find_dependancies(filename)!=0)
639                         continue;
640
641                 while(got_em_all) {
642                         got_em_all=0;
643                         /* Keep walking the list till everybody is resolved */
644                         for (cur = lib_list; cur; cur=cur->next) {
645                                 if (cur->resolved == 0 && cur->path) {
646                                         got_em_all=1;
647                                         //printf("checking sub-depends for '%s\n", cur->path);
648                                         find_dependancies(cur->path);
649                                         cur->resolved = 1;
650                                 }
651                         }
652                 }
653
654
655                 /* Print the list */
656                 got_em_all=0;
657                 for (cur = lib_list; cur; cur=cur->next) {
658                         got_em_all=1;
659                         printf("\t%s => %s (0x00000000)\n", cur->name, cur->path);
660                 }
661                 if (interp_dir && got_em_all==1)
662                         printf("\t%s => %s (0x00000000)\n", interp, interp);
663                 if (got_em_all==0)
664                         printf("\tnot a dynamic executable\n");
665
666                 for (cur = lib_list; cur; cur=cur->next) {
667                         if (cur->path && cur->path != not_found) {
668                                 free(cur->path);
669                                 cur->path=NULL;
670                         }
671                         if (cur->name) {
672                                 free(cur->name);
673                                 cur->name=NULL;
674                         }
675                 }
676                 lib_list=NULL;
677         }
678
679         return 0;
680 }
681