1 /* Copyright (c) 2009, 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 * Redistributions of source code must retain the above copyright
9 notice, this list of conditions and the following disclaimer.
10 * Neither the name of the owner nor the names of its
11 contributors may be used to endorse or promote products derived from
12 this software without specific prior written permission.
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>
39 #define _WIN32_WINNT 0x0501
44 #ifndef STATUS_DLL_NOT_FOUND
45 #define STATUS_DLL_NOT_FOUND (0xC0000135L)
50 struct option longopts
[] =
52 {"help", no_argument
, NULL
, 0},
53 {"version", no_argument
, NULL
, 0},
54 {"data-relocs", no_argument
, NULL
, 'd'},
55 {"function-relocs", no_argument
, NULL
, 'r'},
56 {"unused", no_argument
, NULL
, 'u'},
57 {0, no_argument
, NULL
, 0}
60 static int process_file (const wchar_t *);
63 usage (const char *fmt
, ...)
67 fprintf (stderr
, "ldd: ");
68 vfprintf (stderr
, fmt
, ap
);
69 fprintf (stderr
, "\nTry `ldd --help' for more information.\n");
73 #define print_errno_error_and_return(__fn) \
75 fprintf (stderr, "ldd: %s: %s\n", (__fn), strerror (errno));\
79 #define set_errno_and_return(x) \
81 cygwin_internal (CW_SETERRNO, __FILE__, __LINE__ - 2);\
86 static HANDLE hProcess
;
88 static struct filelist
90 struct filelist
*next
;
99 for (p
= head
; p
; p
= p
->next
)
100 if (strcasecmp (name
, p
->name
) == 0)
103 p
= (filelist
*) malloc(sizeof (struct filelist
));
105 p
->name
= strdup (name
);
111 get_module_filename (HANDLE hp
, HMODULE hm
)
116 for (len
= 1024; (res
= GetModuleFileNameExW (hp
, hm
, (buf
= (wchar_t *) realloc (buf
, len
* sizeof (wchar_t))), len
)) == len
; len
+= 1024)
127 load_dll (const wchar_t *fn
)
129 wchar_t *buf
= get_module_filename (GetCurrentProcess (), NULL
);
132 printf ("ldd: GetModuleFileName returned an error %lu\n", GetLastError ());
133 exit (1); /* FIXME */
136 wchar_t *newbuf
= (wchar_t *) malloc ((sizeof (L
"\"\" -- ") + wcslen (buf
) + wcslen (fn
)) * sizeof (wchar_t));
138 wcscpy (newbuf
+ 1, buf
);
139 wchar_t *p
= wcsstr (newbuf
, L
"\\ldd");
142 printf ("ldd: can't parse my own filename \"%ls\"\n", buf
);
146 wcscat (newbuf
, L
"\" -- ");
153 start_process (const wchar_t *fn
, bool& isdll
)
155 STARTUPINFOW si
= {};
156 PROCESS_INFORMATION pi
;
159 if (wcslen (fn
) < 4 || wcscasecmp (wcschr (fn
, L
'\0') - 4, L
".dll") != 0)
169 if (CreateProcessW (NULL
, cmd
, NULL
, NULL
, FALSE
, DEBUG_ONLY_THIS_PROCESS
, NULL
, NULL
, &si
, &pi
))
172 hProcess
= pi
.hProcess
;
173 DebugSetProcessKillOnExit (true);
178 set_errno_and_return (1);
182 set_entry_point_break ()
186 if (!EnumProcessModules (hProcess
, &hm
, sizeof (hm
), &cb
) || !cb
)
187 set_errno_and_return (1);
190 if (!GetModuleInformation (hProcess
, hm
, &mi
, sizeof (mi
)) || !mi
.EntryPoint
)
191 set_errno_and_return (1);
193 static const unsigned char int3
= 0xcc;
194 if (!WriteProcessMemory (hProcess
, mi
.EntryPoint
, &int3
, 1, &cb
) || cb
!= 1)
195 set_errno_and_return (1);
205 #define SLOP strlen (" (?)")
207 tocyg (wchar_t *win_fn
)
209 ssize_t cwlen
= cygwin_conv_path (CCP_WIN_W_TO_POSIX
, win_fn
, NULL
, 0);
213 int len
= wcstombs (NULL
, win_fn
, 0) + 1;
214 if ((fn
= (char *) malloc (len
)))
215 wcstombs (fn
, win_fn
, len
);
219 char *fn_cyg
= (char *) malloc (cwlen
+ SLOP
+ 1);
220 if (cygwin_conv_path (CCP_WIN_W_TO_POSIX
, win_fn
, fn_cyg
, cwlen
) == 0)
225 int len
= wcstombs (NULL
, win_fn
, 0);
226 fn
= (char *) malloc (len
+ SLOP
+ 1);
227 wcstombs (fn
, win_fn
, len
+ SLOP
+ 1);
233 #define CYGWIN_DLL_LEN (wcslen (L"\\cygwin1.dll"))
235 print_dlls (dlls
*dll
, const wchar_t *dllfn
, const wchar_t *process_fn
)
237 head
= NULL
; /* FIXME: memory leak */
238 while ((dll
= dll
->next
))
241 wchar_t *fullpath
= get_module_filename (hProcess
, (HMODULE
) dll
->lpBaseOfDll
);
244 else if (dllfn
&& wcscmp (fullpath
, dllfn
) == 0)
251 fn
= tocyg (fullpath
);
252 saw_file (basename (fn
));
255 printf ("\t%s => %s (%p)\n", basename (fn
), fn
, dll
->lpBaseOfDll
);
259 return process_file (process_fn
);
264 report (const char *in_fn
, bool multiple
)
267 printf ("%s:\n", in_fn
);
268 char *fn
= realpath (in_fn
, NULL
);
270 print_errno_error_and_return (in_fn
);
272 ssize_t len
= cygwin_conv_path (CCP_POSIX_TO_WIN_W
, fn
, NULL
, 0);
274 print_errno_error_and_return (fn
);
277 wchar_t fn_win
[len
+ 1];
278 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W
, fn
, fn_win
, len
))
279 print_errno_error_and_return (fn
);
281 if (!fn
|| start_process (fn_win
, isdll
))
282 print_errno_error_and_return (in_fn
);
286 unsigned dll_count
= 0;
289 dlls
*dll_last
= &dll_list
;
290 const wchar_t *process_fn
= NULL
;
293 bool exitnow
= false;
294 DWORD cont
= DBG_CONTINUE
;
295 if (!WaitForDebugEvent (&ev
, INFINITE
))
297 switch (ev
.dwDebugEventCode
)
299 case LOAD_DLL_DEBUG_EVENT
:
300 if (!isdll
&& ++dll_count
== 2)
301 set_entry_point_break ();
302 dll_last
->next
= (dlls
*) malloc (sizeof (dlls
));
303 dll_last
->next
->lpBaseOfDll
= ev
.u
.LoadDll
.lpBaseOfDll
;
304 dll_last
->next
->next
= NULL
;
305 dll_last
= dll_last
->next
;
307 case EXCEPTION_DEBUG_EVENT
:
308 switch (ev
.u
.Exception
.ExceptionRecord
.ExceptionCode
)
310 case STATUS_DLL_NOT_FOUND
:
313 case STATUS_BREAKPOINT
:
315 cont
= DBG_EXCEPTION_NOT_HANDLED
;
319 case CREATE_THREAD_DEBUG_EVENT
:
320 TerminateProcess (hProcess
, 0);
322 case EXIT_PROCESS_DEBUG_EVENT
:
323 print_dlls (&dll_list
, isdll
? fn_win
: NULL
, process_fn
);
329 if (!ContinueDebugEvent (ev
.dwProcessId
, ev
.dwThreadId
, cont
))
331 cygwin_internal (CW_SETERRNO
, __FILE__
, __LINE__
- 2);
332 print_errno_error_and_return (in_fn
);
343 main (int argc
, char **argv
)
348 /* Use locale from environment. If not set or set to "C", use UTF-8. */
349 setlocale (LC_CTYPE
, "");
350 if (!strcmp (setlocale (LC_CTYPE
, NULL
), "C"))
351 setlocale (LC_CTYPE
, "en_US.UTF-8");
352 while ((optch
= getopt_long (argc
, argv
, "dru", longopts
, &index
)) != -1)
358 usage ("option not implemented `-%c'", optch
);
363 printf ("ldd (Cygwin) %s\nCopyright (C) 2009 Chris Faylor\n"
364 "This is free software; see the source for copying conditions. There is NO\n"
365 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n",
371 puts ("Usage: ldd [OPTION]... FILE...\n\
372 --help print this help and exit\n\
373 --version print version information and exit\n\
374 -r, --function-relocs process data and function relocations\n\
375 (currently unimplemented)\n\
376 -u, --unused print unused direct dependencies\n\
377 (currently unimplemented)\n\
378 -v, --verbose print all information\n\
379 (currently unimplemented)");
385 usage("missing file arguments");
388 bool multiple
= !!argv
[1];
390 while ((fn
= *argv
++))
391 if (report (fn
, multiple
))
396 static bool printing
= false;
399 /* dump of import directory
400 section begins at pointer 'section base'
401 section RVA is 'section_rva'
402 import directory begins at pointer 'imp' */
404 dump_import_directory (const void *const section_base
,
405 const DWORD section_rva
,
406 const IMAGE_IMPORT_DESCRIPTOR
*imp
)
408 /* get memory address given the RVA */
409 #define adr(rva) ((const void*) ((char*) section_base+((DWORD) (rva))-section_rva))
411 /* continue until address inaccessible or there's no DLL name */
412 for (; !IsBadReadPtr (imp
, sizeof (*imp
)) && imp
->Name
; imp
++)
414 wchar_t full_path
[PATH_MAX
];
416 char *fn
= (char *) adr (imp
->Name
);
421 int len
= mbstowcs (NULL
, fn
, 0);
424 wchar_t fnw
[len
+ 1];
425 mbstowcs (fnw
, fn
, len
+ 1);
426 /* output DLL's name */
428 if (!SearchPathW (NULL
, fnw
, NULL
, PATH_MAX
, full_path
, &dummy
))
430 print_fn
= strdup ("not found");
437 print_fn
= tocyg (full_path
);
438 strcat (print_fn
, " (?)");
441 printf ("\t%s => %s\n", (char *) fn
, print_fn
);
449 /* load a file in RAM (memory-mapped)
450 return pointer to loaded file
453 map_file (const wchar_t *filename
)
455 HANDLE hFile
, hMapping
;
457 if ((hFile
= CreateFileW (filename
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
,
458 0, OPEN_EXISTING
, FILE_FLAG_SEQUENTIAL_SCAN
, 0)) == INVALID_HANDLE_VALUE
)
460 fprintf (stderr
, "couldn't open %ls\n", filename
);
463 if (!(hMapping
= CreateFileMapping (hFile
, 0, PAGE_READONLY
| SEC_COMMIT
, 0, 0, 0)))
465 fprintf (stderr
, "CreateFileMapping failed with windows error %lu\n", GetLastError ());
469 if (!(basepointer
= MapViewOfFile (hMapping
, FILE_MAP_READ
, 0, 0, 0)))
471 fprintf (stderr
, "MapViewOfFile failed with windows error %lu\n", GetLastError ());
472 CloseHandle (hMapping
);
477 CloseHandle (hMapping
);
484 /* this will return a pointer immediatly behind the DOS-header
487 skip_dos_stub (const IMAGE_DOS_HEADER
*dos_ptr
)
489 /* look there's enough space for a DOS-header */
490 if (IsBadReadPtr (dos_ptr
, sizeof (*dos_ptr
)))
492 fprintf (stderr
, "not enough space for DOS-header\n");
497 if (dos_ptr
->e_magic
!= IMAGE_DOS_SIGNATURE
)
499 fprintf (stderr
, "not a DOS-stub\n");
503 /* ok, then, go get it */
504 return (char*) dos_ptr
+ dos_ptr
->e_lfanew
;
508 /* find the directory's section index given the RVA
509 Returns -1 if impossible */
511 get_directory_index (const unsigned dir_rva
,
512 const unsigned dir_length
,
513 const int number_of_sections
,
514 const IMAGE_SECTION_HEADER
*sections
)
517 for (sect
= 0; sect
< number_of_sections
; sect
++)
519 /* compare directory RVA to section RVA */
520 if (sections
[sect
].VirtualAddress
<= dir_rva
521 && dir_rva
< sections
[sect
].VirtualAddress
+sections
[sect
].SizeOfRawData
)
528 /* dump imports of a single file
529 Returns 0 if successful, !=0 else */
531 process_file (const wchar_t *filename
)
533 void *basepointer
; /* Points to loaded PE file
534 * This is memory mapped stuff
536 int number_of_sections
;
537 DWORD import_rva
; /* RVA of import directory */
538 DWORD import_length
; /* length of import directory */
539 int import_index
; /* index of section with import directory */
541 /* ensure byte-alignment for struct tag_header */
542 #include <pshpack1.h>
544 const struct tag_header
547 IMAGE_FILE_HEADER file_head
;
548 IMAGE_OPTIONAL_HEADER opt_head
;
549 IMAGE_SECTION_HEADER section_header
[1]; /* an array of unknown length */
552 /* revert to regular alignment */
557 /* first, load file */
558 basepointer
= map_file (filename
);
561 puts ("cannot load file");
565 /* get header pointer; validate a little bit */
566 header
= (tag_header
*) skip_dos_stub ((IMAGE_DOS_HEADER
*) basepointer
);
569 puts ("cannot skip DOS stub");
570 UnmapViewOfFile (basepointer
);
574 /* look there's enough space for PE headers */
575 if (IsBadReadPtr (header
, sizeof (*header
)))
577 puts ("not enough space for PE headers");
578 UnmapViewOfFile (basepointer
);
582 /* validate PE signature */
583 if (header
->signature
!= IMAGE_NT_SIGNATURE
)
585 puts ("not a PE file");
586 UnmapViewOfFile (basepointer
);
590 /* get number of sections */
591 number_of_sections
= header
->file_head
.NumberOfSections
;
593 /* check there are sections... */
594 if (number_of_sections
< 1)
596 UnmapViewOfFile (basepointer
);
600 /* validate there's enough space for section headers */
601 if (IsBadReadPtr (header
->section_header
, number_of_sections
*sizeof (IMAGE_SECTION_HEADER
)))
603 puts ("not enough space for section headers");
604 UnmapViewOfFile (basepointer
);
608 /* get RVA and length of import directory */
609 import_rva
= header
->opt_head
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_IMPORT
].VirtualAddress
;
610 import_length
= header
->opt_head
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_IMPORT
].Size
;
612 /* check there's stuff to care about */
613 if (!import_rva
|| !import_length
)
615 UnmapViewOfFile (basepointer
);
616 return 0; /* success! */
619 /* get import directory pointer */
620 import_index
= get_directory_index (import_rva
,import_length
,number_of_sections
,header
->section_header
);
622 /* check directory was found */
623 if (import_index
< 0)
625 puts ("couldn't find import directory in sections");
626 UnmapViewOfFile (basepointer
);
630 /* The pointer to the start of the import directory's section */
631 const void *section_address
= (char*) basepointer
+ header
->section_header
[import_index
].PointerToRawData
;
632 if (dump_import_directory (section_address
,
633 header
->section_header
[import_index
].VirtualAddress
,
634 /* the last parameter is the pointer to the import directory:
635 section address + (import RVA - section RVA)
636 The difference is the offset of the import directory in the section */
637 (const IMAGE_IMPORT_DESCRIPTOR
*) ((char *) section_address
+import_rva
-header
->section_header
[import_index
].VirtualAddress
)))
639 UnmapViewOfFile (basepointer
);
643 UnmapViewOfFile (basepointer
);