1 /* Copyright (c) 2009, 2010, 2011, 2013 Chris Faylor
5 Redistribution and use in source and binary forms, with or without
6 modification, are permitted provided that the following conditions are met:
8 1. Redistributions of source code must retain the above copyright
9 notice, this list of conditions and the following disclaimer.
10 2. Redistributions in binary form must reproduce the above copyright
11 notice, this list of conditions and the following disclaimer in the
12 documentation and/or other materials provided with the distribution.
14 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS
15 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
16 TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
17 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
18 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
19 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
20 TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
22 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
23 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
24 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35 #include <sys/cygwin.h>
36 #include <cygwin/version.h>
40 #define _WIN32_WINNT 0x0a00
46 struct option longopts
[] =
48 {"help", no_argument
, NULL
, 'h'},
49 {"verbose", no_argument
, NULL
, 'v'},
50 {"version", no_argument
, NULL
, 'V'},
51 {"data-relocs", no_argument
, NULL
, 'd'},
52 {"function-relocs", no_argument
, NULL
, 'r'},
53 {"unused", no_argument
, NULL
, 'u'},
54 {0, no_argument
, NULL
, 0}
56 const char *opts
= "dhruvV";
58 static int process_file (const wchar_t *);
61 error (const char *fmt
, ...)
65 fprintf (stderr
, "ldd: ");
66 vfprintf (stderr
, fmt
, ap
);
67 fprintf (stderr
, "\nTry `ldd --help' for more information.\n");
71 static void __attribute__ ((__noreturn__
))
74 printf ("Usage: %s [OPTION]... FILE...\n\
76 Print shared library dependencies\n\
78 -h, --help print this help and exit\n\
79 -V, --version print version information and exit\n\
80 -r, --function-relocs process data and function relocations\n\
81 (currently unimplemented)\n\
82 -u, --unused print unused direct dependencies\n\
83 (currently unimplemented)\n\
84 -v, --verbose print all information\n\
85 (currently unimplemented)\n",
86 program_invocation_short_name
);
93 printf ("ldd (cygwin) %d.%d.%d\n"
94 "Print shared library dependencies\n"
95 "Copyright (C) 2009 - %s Chris Faylor\n"
96 "This is free software; see the source for copying conditions. There is NO\n"
97 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n",
98 CYGWIN_VERSION_DLL_MAJOR
/ 1000,
99 CYGWIN_VERSION_DLL_MAJOR
% 1000,
100 CYGWIN_VERSION_DLL_MINOR
,
101 strrchr (__DATE__
, ' ') + 1);
104 #define print_errno_error_and_return(__fn) \
106 fprintf (stderr, "ldd: %s: %s\n", (__fn), strerror (errno));\
110 #define set_errno_and_return(x) \
112 cygwin_internal (CW_SETERRNO, __FILE__, __LINE__ - 2);\
117 static HANDLE hProcess
;
119 static struct filelist
121 struct filelist
*next
;
126 saw_file (char *name
)
130 for (p
= head
; p
; p
= p
->next
)
131 if (strcasecmp (name
, p
->name
) == 0)
134 p
= (filelist
*) malloc(sizeof (struct filelist
));
136 p
->name
= strdup (name
);
142 get_module_filename (HANDLE hp
, HMODULE hm
)
147 for (len
= 1024; (res
= GetModuleFileNameExW (hp
, hm
, (buf
= (wchar_t *) realloc (buf
, len
* sizeof (wchar_t))), len
)) == len
; len
+= 1024)
158 load_dll (const wchar_t *fn
)
160 wchar_t *buf
= get_module_filename (GetCurrentProcess (), NULL
);
163 printf ("ldd: GetModuleFileName returned an error %u\n",
164 (unsigned int) GetLastError ());
165 exit (1); /* FIXME */
168 wchar_t *newbuf
= (wchar_t *) malloc ((sizeof (L
"\"\" -- ") + wcslen (buf
) + wcslen (fn
)) * sizeof (wchar_t));
170 wcscpy (newbuf
+ 1, buf
);
171 wchar_t *p
= wcsstr (newbuf
, L
"\\ldd");
174 printf ("ldd: can't parse my own filename \"%ls\"\n", buf
);
178 wcscat (newbuf
, L
"\" -- ");
185 start_process (const wchar_t *fn
, bool& isdll
)
187 STARTUPINFOW si
= {};
188 PROCESS_INFORMATION pi
;
191 /* OCaml natdynlink plugins (.cmxs) cannot be handled by ldd because they
192 can only be loaded by flexdll_dlopen() */
193 if (wcslen (fn
) < 4 || (wcscasecmp (wcschr (fn
, L
'\0') - 4, L
".dll") != 0
194 && wcscasecmp (wcschr (fn
, L
'\0') - 4, L
".oct") != 0
195 && wcscasecmp (wcschr (fn
, L
'\0') - 3, L
".so") != 0))
205 if (CreateProcessW (NULL
, cmd
, NULL
, NULL
, FALSE
, DEBUG_ONLY_THIS_PROCESS
, NULL
, NULL
, &si
, &pi
))
208 hProcess
= pi
.hProcess
;
209 DebugSetProcessKillOnExit (true);
214 set_errno_and_return (1);
224 #define SLOP strlen (" (?)")
226 tocyg (wchar_t *win_fn
)
228 ssize_t cwlen
= cygwin_conv_path (CCP_WIN_W_TO_POSIX
, win_fn
, NULL
, 0);
232 int len
= wcstombs (NULL
, win_fn
, 0) + 1;
233 if ((fn
= (char *) malloc (len
)))
234 wcstombs (fn
, win_fn
, len
);
238 char *fn_cyg
= (char *) malloc (cwlen
+ SLOP
+ 1);
239 if (cygwin_conv_path (CCP_WIN_W_TO_POSIX
, win_fn
, fn_cyg
, cwlen
) == 0)
244 int len
= wcstombs (NULL
, win_fn
, 0);
245 fn
= (char *) malloc (len
+ SLOP
+ 1);
246 wcstombs (fn
, win_fn
, len
+ SLOP
+ 1);
252 #define CYGWIN_DLL_LEN (wcslen (L"\\cygwin1.dll"))
254 print_dlls (dlls
*dll
, const wchar_t *dllfn
, const wchar_t *process_fn
)
256 head
= NULL
; /* FIXME: memory leak */
257 while ((dll
= dll
->next
))
260 wchar_t *fullpath
= get_module_filename (hProcess
, (HMODULE
) dll
->lpBaseOfDll
);
263 // if no path found yet, try getting it from an open handle to the DLL
264 wchar_t dllname
[PATH_MAX
];
265 if (GetFinalPathNameByHandleW (dll
->hFile
, dllname
, PATH_MAX
, 0))
267 fn
= tocyg (dllname
);
268 saw_file (basename (fn
));
273 else if (dllfn
&& wcscmp (fullpath
, dllfn
) == 0)
280 fn
= tocyg (fullpath
);
281 saw_file (basename (fn
));
284 printf ("\t%s => %s (%p)\n", basename (fn
), fn
, dll
->lpBaseOfDll
);
288 return process_file (process_fn
);
293 report (const char *in_fn
, bool multiple
)
296 printf ("%s:\n", in_fn
);
297 char *fn
= realpath (in_fn
, NULL
);
299 print_errno_error_and_return (in_fn
);
301 ssize_t len
= cygwin_conv_path (CCP_POSIX_TO_WIN_W
, fn
, NULL
, 0);
303 print_errno_error_and_return (fn
);
306 wchar_t fn_win
[len
+ 1];
307 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W
, fn
, fn_win
, len
))
308 print_errno_error_and_return (fn
);
310 if (!fn
|| start_process (fn_win
, isdll
))
311 print_errno_error_and_return (in_fn
);
316 dlls
*dll_last
= &dll_list
;
317 const wchar_t *process_fn
= NULL
;
323 bool exitnow
= false;
324 DWORD cont
= DBG_CONTINUE
;
325 if (!WaitForDebugEvent (&ev
, INFINITE
))
327 switch (ev
.dwDebugEventCode
)
329 case CREATE_PROCESS_DEBUG_EVENT
:
332 PIMAGE_DOS_HEADER dos_header
= (PIMAGE_DOS_HEADER
) alloca (4096);
333 PIMAGE_NT_HEADERS nt_header
;
335 static const unsigned char int3
= 0xcc;
338 if (!ReadProcessMemory (hProcess
,
339 ev
.u
.CreateProcessInfo
.lpBaseOfImage
,
340 dos_header
, 4096, &bytes
))
341 print_errno_error_and_return (in_fn
);
343 nt_header
= PIMAGE_NT_HEADERS (PBYTE (dos_header
)
344 + dos_header
->e_lfanew
);
345 entry_point
= (PVOID
)
346 ((caddr_t
) ev
.u
.CreateProcessInfo
.lpBaseOfImage
347 + nt_header
->OptionalHeader
.AddressOfEntryPoint
);
349 if (!WriteProcessMemory (hProcess
, entry_point
, &int3
, 1, &bytes
))
350 print_errno_error_and_return (in_fn
);
353 case LOAD_DLL_DEBUG_EVENT
:
354 dll_last
->next
= (dlls
*) malloc (sizeof (dlls
));
355 dll_last
->next
->lpBaseOfDll
= ev
.u
.LoadDll
.lpBaseOfDll
;
356 dll_last
->next
->hFile
= ev
.u
.LoadDll
.hFile
;
357 dll_last
->next
->next
= NULL
;
358 dll_last
= dll_last
->next
;
360 case EXCEPTION_DEBUG_EVENT
:
361 switch (ev
.u
.Exception
.ExceptionRecord
.ExceptionCode
)
363 case STATUS_ENTRYPOINT_NOT_FOUND
:
364 /* A STATUS_ENTRYPOINT_NOT_FOUND might be encountered right after
365 loading all DLLs. We have to handle it here, otherwise ldd
366 runs into an endless loop. */
368 case STATUS_DLL_NOT_FOUND
:
371 case STATUS_BREAKPOINT
:
373 TerminateProcess (hProcess
, 0);
376 if (ev
.u
.Exception
.ExceptionRecord
.ExceptionFlags
&
377 EXCEPTION_NONCONTINUABLE
) {
382 case EXIT_PROCESS_DEBUG_EVENT
:
383 if (ev
.u
.ExitProcess
.dwExitCode
!= 0)
386 print_dlls (&dll_list
, isdll
? fn_win
: NULL
, process_fn
);
392 if (!ContinueDebugEvent (ev
.dwProcessId
, ev
.dwThreadId
, cont
))
394 cygwin_internal (CW_SETERRNO
, __FILE__
, __LINE__
- 2);
395 print_errno_error_and_return (in_fn
);
405 main (int argc
, char **argv
)
409 /* Use locale from environment. If not set or set to "C", use UTF-8. */
410 setlocale (LC_CTYPE
, "");
411 if (!strcmp (setlocale (LC_CTYPE
, NULL
), "C"))
412 setlocale (LC_CTYPE
, "en_US.UTF-8");
413 while ((optch
= getopt_long (argc
, argv
, opts
, longopts
, NULL
)) != -1)
419 error ("option not implemented `-%c'", optch
);
427 fprintf (stderr
, "Try `%s --help' for more information.\n",
428 program_invocation_short_name
);
433 error ("missing file arguments");
436 bool multiple
= !!argv
[1];
438 while ((fn
= *argv
++))
439 if (report (fn
, multiple
))
444 static bool printing
= false;
447 /* dump of import directory
448 section begins at pointer 'section base'
449 section RVA is 'section_rva'
450 import directory begins at pointer 'imp' */
452 dump_import_directory (const void *const section_base
,
453 const DWORD section_rva
,
454 const IMAGE_IMPORT_DESCRIPTOR
*imp
)
456 /* get memory address given the RVA */
457 #define adr(rva) ((const void*) ((char*) section_base+((DWORD) (rva))-section_rva))
459 /* continue until address inaccessible or there's no DLL name */
460 for (; !IsBadReadPtr (imp
, sizeof (*imp
)) && imp
->Name
; imp
++)
462 wchar_t full_path
[PATH_MAX
];
464 char *fn
= (char *) adr (imp
->Name
);
469 int len
= mbstowcs (NULL
, fn
, 0);
472 wchar_t fnw
[len
+ 1];
473 mbstowcs (fnw
, fn
, len
+ 1);
474 /* output DLL's name */
476 if (!SearchPathW (NULL
, fnw
, NULL
, PATH_MAX
, full_path
, &dummy
))
478 print_fn
= strdup ("not found");
485 print_fn
= tocyg (full_path
);
486 strcat (print_fn
, " (?)");
489 printf ("\t%s => %s\n", (char *) fn
, print_fn
);
497 /* load a file in RAM (memory-mapped)
498 return pointer to loaded file
501 map_file (const wchar_t *filename
)
503 HANDLE hFile
, hMapping
;
505 if ((hFile
= CreateFileW (filename
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
,
506 0, OPEN_EXISTING
, FILE_FLAG_SEQUENTIAL_SCAN
, 0)) == INVALID_HANDLE_VALUE
)
508 fprintf (stderr
, "couldn't open %ls\n", filename
);
511 if (!(hMapping
= CreateFileMapping (hFile
, 0, PAGE_READONLY
| SEC_COMMIT
, 0, 0, 0)))
513 fprintf (stderr
, "CreateFileMapping failed with windows error %u\n",
514 (unsigned int) GetLastError ());
518 if (!(basepointer
= MapViewOfFile (hMapping
, FILE_MAP_READ
, 0, 0, 0)))
520 fprintf (stderr
, "MapViewOfFile failed with windows error %u\n",
521 (unsigned int) GetLastError ());
522 CloseHandle (hMapping
);
527 CloseHandle (hMapping
);
534 /* this will return a pointer immediatly behind the DOS-header
537 skip_dos_stub (const IMAGE_DOS_HEADER
*dos_ptr
)
539 /* look there's enough space for a DOS-header */
540 if (IsBadReadPtr (dos_ptr
, sizeof (*dos_ptr
)))
542 fprintf (stderr
, "not enough space for DOS-header\n");
547 if (dos_ptr
->e_magic
!= IMAGE_DOS_SIGNATURE
)
549 fprintf (stderr
, "not a DOS-stub\n");
553 /* ok, then, go get it */
554 return (char*) dos_ptr
+ dos_ptr
->e_lfanew
;
558 /* find the directory's section index given the RVA
559 Returns -1 if impossible */
561 get_directory_index (const unsigned dir_rva
,
562 const unsigned dir_length
,
563 const int number_of_sections
,
564 const IMAGE_SECTION_HEADER
*sections
)
567 for (sect
= 0; sect
< number_of_sections
; sect
++)
569 /* compare directory RVA to section RVA */
570 if (sections
[sect
].VirtualAddress
<= dir_rva
571 && dir_rva
< sections
[sect
].VirtualAddress
+sections
[sect
].SizeOfRawData
)
578 /* dump imports of a single file
579 Returns 0 if successful, !=0 else */
581 process_file (const wchar_t *filename
)
583 void *basepointer
; /* Points to loaded PE file
584 * This is memory mapped stuff
586 int number_of_sections
;
587 DWORD import_rva
; /* RVA of import directory */
588 DWORD import_length
; /* length of import directory */
589 int import_index
; /* index of section with import directory */
591 /* ensure byte-alignment for struct tag_header */
592 #include <pshpack1.h>
594 const struct tag_header
597 IMAGE_FILE_HEADER file_head
;
598 IMAGE_OPTIONAL_HEADER opt_head
;
599 IMAGE_SECTION_HEADER section_header
[1]; /* an array of unknown length */
602 /* revert to regular alignment */
607 /* first, load file */
608 basepointer
= map_file (filename
);
611 puts ("cannot load file");
615 /* get header pointer; validate a little bit */
616 header
= (tag_header
*) skip_dos_stub ((IMAGE_DOS_HEADER
*) basepointer
);
619 puts ("cannot skip DOS stub");
620 UnmapViewOfFile (basepointer
);
624 /* look there's enough space for PE headers */
625 if (IsBadReadPtr (header
, sizeof (*header
)))
627 puts ("not enough space for PE headers");
628 UnmapViewOfFile (basepointer
);
632 /* validate PE signature */
633 if (header
->signature
!= IMAGE_NT_SIGNATURE
)
635 puts ("not a PE file");
636 UnmapViewOfFile (basepointer
);
640 /* get number of sections */
641 number_of_sections
= header
->file_head
.NumberOfSections
;
643 /* check there are sections... */
644 if (number_of_sections
< 1)
646 UnmapViewOfFile (basepointer
);
650 /* validate there's enough space for section headers */
651 if (IsBadReadPtr (header
->section_header
, number_of_sections
*sizeof (IMAGE_SECTION_HEADER
)))
653 puts ("not enough space for section headers");
654 UnmapViewOfFile (basepointer
);
658 /* get RVA and length of import directory */
659 import_rva
= header
->opt_head
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_IMPORT
].VirtualAddress
;
660 import_length
= header
->opt_head
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_IMPORT
].Size
;
662 /* check there's stuff to care about */
663 if (!import_rva
|| !import_length
)
665 UnmapViewOfFile (basepointer
);
666 return 0; /* success! */
669 /* get import directory pointer */
670 import_index
= get_directory_index (import_rva
,import_length
,number_of_sections
,header
->section_header
);
672 /* check directory was found */
673 if (import_index
< 0)
675 puts ("couldn't find import directory in sections");
676 UnmapViewOfFile (basepointer
);
680 /* The pointer to the start of the import directory's section */
681 const void *section_address
= (char*) basepointer
+ header
->section_header
[import_index
].PointerToRawData
;
682 if (dump_import_directory (section_address
,
683 header
->section_header
[import_index
].VirtualAddress
,
684 /* the last parameter is the pointer to the import directory:
685 section address + (import RVA - section RVA)
686 The difference is the offset of the import directory in the section */
687 (const IMAGE_IMPORT_DESCRIPTOR
*) ((char *) section_address
+import_rva
-header
->section_header
[import_index
].VirtualAddress
)))
689 UnmapViewOfFile (basepointer
);
693 UnmapViewOfFile (basepointer
);