winedbg: When reloading real PE modules from a minidump, also look in the search...
[wine] / programs / winedbg / tgt_minidump.c
1 /*
2  * Wine debugger - minidump handling
3  *
4  * Copyright 2005 Eric Pouech
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #define NONAMELESSUNION
22 #define NONAMELESSSTRUCT
23
24 #include "config.h"
25
26 #include <stdlib.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <stdarg.h>
30
31 #include "debugger.h"
32 #include "wingdi.h"
33 #include "winuser.h"
34 #include "tlhelp32.h"
35 #include "wine/debug.h"
36 #include "wine/exception.h"
37
38 WINE_DEFAULT_DEBUG_CHANNEL(winedbg);
39
40 static struct be_process_io be_process_minidump_io;
41
42 void minidump_write(const char* file, const EXCEPTION_RECORD* rec)
43 {
44     HANDLE                              hFile;
45     MINIDUMP_EXCEPTION_INFORMATION      mei;
46     EXCEPTION_POINTERS                  ep;
47
48     hFile = CreateFile(file, GENERIC_READ|GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
49                        FILE_ATTRIBUTE_NORMAL, NULL);
50
51     if (hFile == INVALID_HANDLE_VALUE) return;
52
53     if (rec)
54     {
55         mei.ThreadId = dbg_curr_thread->tid;
56         mei.ExceptionPointers = &ep;
57         ep.ExceptionRecord = (EXCEPTION_RECORD*)rec;
58         ep.ContextRecord = &dbg_context;
59         mei.ClientPointers = FALSE;
60     }
61     MiniDumpWriteDump(dbg_curr_process->handle, dbg_curr_process->pid,
62                       hFile, MiniDumpNormal/*|MiniDumpWithDataSegs*/,
63                       rec ? &mei : NULL, NULL, NULL);
64     CloseHandle(hFile);
65 }
66
67 #define Wine_ElfModuleListStream        0xFFF0
68
69 struct tgt_process_minidump_data
70 {
71     void*       mapping;
72     HANDLE      hFile;
73     HANDLE      hMap;
74 };
75
76 static inline struct tgt_process_minidump_data* PRIVATE(struct dbg_process* pcs)
77 {
78     return (struct tgt_process_minidump_data*)pcs->pio_data;
79 }
80
81 static BOOL WINAPI tgt_process_minidump_read(HANDLE hProcess, const void* addr, 
82                                              void* buffer, SIZE_T len, SIZE_T* rlen)
83 {
84     ULONG               size;
85     MINIDUMP_DIRECTORY* dir;
86     void*               stream;
87
88     if (!PRIVATE(dbg_curr_process)->mapping) return FALSE;
89     if (MiniDumpReadDumpStream(PRIVATE(dbg_curr_process)->mapping,
90                                MemoryListStream, &dir, &stream, &size))
91     {
92         MINIDUMP_MEMORY_LIST*   mml = (MINIDUMP_MEMORY_LIST*)stream;
93         MINIDUMP_MEMORY_DESCRIPTOR* mmd = &mml->MemoryRanges[0];
94         int                     i;
95
96         for (i = 0; i < mml->NumberOfMemoryRanges; i++, mmd++)
97         {
98             if (mmd->StartOfMemoryRange <= (DWORD_PTR)addr &&
99                 (DWORD_PTR)addr < mmd->StartOfMemoryRange + mmd->Memory.DataSize)
100             {
101                 len = min(len, mmd->StartOfMemoryRange + mmd->Memory.DataSize - (DWORD_PTR)addr);
102                 memcpy(buffer, 
103                        (char*)PRIVATE(dbg_curr_process)->mapping + mmd->Memory.Rva + (DWORD_PTR)addr - mmd->StartOfMemoryRange,
104                        len);
105                 if (rlen) *rlen = len;
106                 return TRUE;
107             }
108         }
109     }
110     /* FIXME: this is a dirty hack to let the last frame in a bt to work
111      * However, we need to check who's to blame, this code or the current 
112      * dbghelp!StackWalk implementation
113      */
114     if ((DWORD_PTR)addr < 32)
115     {
116         memset(buffer, 0, len); 
117         if (rlen) *rlen = len;
118         return TRUE;
119     }
120     return FALSE;
121 }
122
123 static BOOL WINAPI tgt_process_minidump_write(HANDLE hProcess, void* addr,
124                                              const void* buffer, SIZE_T len, SIZE_T* wlen)
125 {
126     return FALSE;
127 }
128
129 BOOL CALLBACK validate_file(PCWSTR name, void* user)
130 {
131     return FALSE; /* get the first file we find !! */
132 }
133
134 static BOOL is_pe_module_embedded(struct tgt_process_minidump_data* data,
135                                   MINIDUMP_MODULE* pe_mm)
136 {
137     ULONG                       size;
138     MINIDUMP_DIRECTORY*         dir;
139     MINIDUMP_MODULE_LIST*       mml;
140
141     if (MiniDumpReadDumpStream(data->mapping, Wine_ElfModuleListStream, &dir,
142                                (void**)&mml, &size))
143     {
144         MINIDUMP_MODULE*        mm;
145         unsigned                i;
146
147         for (i = 0, mm = &mml->Modules[0]; i < mml->NumberOfModules; i++, mm++)
148         {
149             if (mm->BaseOfImage <= pe_mm->BaseOfImage &&
150                 mm->BaseOfImage + mm->SizeOfImage >= pe_mm->BaseOfImage + pe_mm->SizeOfImage)
151                 return TRUE;
152         }
153     }
154     return FALSE;
155 }
156
157 static enum dbg_start minidump_do_reload(struct tgt_process_minidump_data* data)
158 {
159     ULONG                       size;
160     MINIDUMP_DIRECTORY*         dir;
161     void*                       stream;
162     DWORD                       pid = 1; /* by default */
163     HANDLE                      hProc = (HANDLE)0x900DBAAD;
164     int                         i;
165     MINIDUMP_MODULE_LIST*       mml;
166     MINIDUMP_MODULE*            mm;
167     MINIDUMP_STRING*            mds;
168     char                        exec_name[1024];
169     WCHAR                       nameW[1024];
170     unsigned                    len;
171
172     /* fetch PID */
173     if (MiniDumpReadDumpStream(data->mapping, MiscInfoStream, &dir, &stream, &size))
174     {
175         MINIDUMP_MISC_INFO* mmi = (MINIDUMP_MISC_INFO*)stream;
176         if (mmi->Flags1 & MINIDUMP_MISC1_PROCESS_ID)
177             pid = mmi->ProcessId;
178     }
179
180     /* fetch executable name (it's normally the first one in module list) */
181     strcpy(exec_name, "<minidump-exec>"); /* default */
182     if (MiniDumpReadDumpStream(data->mapping, ModuleListStream, &dir, &stream, &size))
183     {
184         mml = (MINIDUMP_MODULE_LIST*)stream;
185         if (mml->NumberOfModules)
186         {
187             char*               ptr;
188
189             mm = &mml->Modules[0];
190             mds = (MINIDUMP_STRING*)((char*)data->mapping + mm->ModuleNameRva);
191             len = WideCharToMultiByte(CP_ACP, 0, mds->Buffer,
192                                       mds->Length / sizeof(WCHAR),
193                                       exec_name, sizeof(exec_name) - 1, NULL, NULL);
194             exec_name[len] = 0;
195             for (ptr = exec_name + len - 1; ptr >= exec_name; ptr--)
196             {
197                 if (*ptr == '/' || *ptr == '\\')
198                 {
199                     memmove(exec_name, ptr + 1, strlen(ptr + 1) + 1);
200                     break;
201                 }
202             }
203         }
204     }
205
206     if (MiniDumpReadDumpStream(data->mapping, SystemInfoStream, &dir, &stream, &size))
207     {
208         MINIDUMP_SYSTEM_INFO*   msi = (MINIDUMP_SYSTEM_INFO*)stream;
209         const char *str;
210         char tmp[128];
211
212         dbg_printf("WineDbg starting on minidump on pid %04x\n", pid);
213         switch (msi->ProcessorArchitecture)
214         {
215         case PROCESSOR_ARCHITECTURE_UNKNOWN: 
216             str = "Unknown";
217             break;
218         case PROCESSOR_ARCHITECTURE_INTEL:
219             strcpy(tmp, "Intel ");
220             switch (msi->ProcessorLevel)
221             {
222             case 3: str = "80386"; break;
223             case 4: str = "80486"; break;
224             case 5: str = "Pentium"; break;
225             case 6: str = "Pentium Pro/II"; break;
226             default: str = "???"; break;
227             }
228             strcat(tmp, str);
229             if (msi->ProcessorLevel == 3 || msi->ProcessorLevel == 4)
230             {
231                 if (HIWORD(msi->ProcessorRevision) == 0xFF)
232                     sprintf(tmp + strlen(tmp), "-%c%d",
233                             'A' + HIBYTE(LOWORD(msi->ProcessorRevision)),
234                             LOBYTE(LOWORD(msi->ProcessorRevision)));
235                 else
236                     sprintf(tmp + strlen(tmp), "-%c%d",
237                             'A' + HIWORD(msi->ProcessorRevision),
238                             LOWORD(msi->ProcessorRevision));
239             }
240             else sprintf(tmp + strlen(tmp), "-%d.%d",
241                          HIWORD(msi->ProcessorRevision),
242                          LOWORD(msi->ProcessorRevision));
243             str = tmp;
244             break;
245         case PROCESSOR_ARCHITECTURE_MIPS:
246             str = "Mips";
247             break;
248         case PROCESSOR_ARCHITECTURE_ALPHA:
249             str = "Alpha";
250             break;
251         case PROCESSOR_ARCHITECTURE_PPC:
252             str = "PowerPC";
253             break;
254         default:
255             str = "???";
256             break;
257         }
258         dbg_printf("  %s was running on #%d %s CPU%s",
259                    exec_name, msi->u.s.NumberOfProcessors, str, 
260                    msi->u.s.NumberOfProcessors < 2 ? "" : "s");
261         switch (msi->MajorVersion)
262         {
263         case 3:
264             switch (msi->MinorVersion)
265             {
266             case 51: str = "NT 3.51"; break;
267             default: str = "3-????"; break;
268             }
269             break;
270         case 4:
271             switch (msi->MinorVersion)
272             {
273             case 0: str = (msi->PlatformId == VER_PLATFORM_WIN32_NT) ? "NT 4.0" : "95"; break;
274             case 10: str = "98"; break;
275             case 90: str = "ME"; break;
276             default: str = "5-????"; break;
277             }
278             break;
279         case 5:
280             switch (msi->MinorVersion)
281             {
282             case 0: str = "2000"; break;
283             case 1: str = "XP"; break;
284             case 2: str = "Server 2003"; break;
285             default: str = "5-????"; break;
286             }
287             break;
288         default: str = "???"; break;
289         }
290         dbg_printf(" on Windows %s (%u)\n", str, msi->BuildNumber);
291         /* FIXME CSD: msi->CSDVersionRva */
292     }
293
294     dbg_curr_process = dbg_add_process(&be_process_minidump_io, pid, hProc);
295     dbg_curr_pid = pid;
296     dbg_curr_process->pio_data = data;
297     dbg_set_process_name(dbg_curr_process, exec_name);
298
299     SymInitialize(hProc, NULL, FALSE);
300
301     if (MiniDumpReadDumpStream(data->mapping, ThreadListStream, &dir, &stream, &size))
302     {
303         MINIDUMP_THREAD_LIST*   mtl = (MINIDUMP_THREAD_LIST*)stream;
304         ULONG                   i;
305
306         for (i = 0; i < mtl->NumberOfThreads; i++)
307         {
308             dbg_add_thread(dbg_curr_process, mtl->Threads[i].ThreadId, NULL,
309                            (void*)(DWORD_PTR)mtl->Threads[i].Teb);
310         }
311     }
312     /* first load ELF modules, then do the PE ones */
313     if (MiniDumpReadDumpStream(data->mapping, Wine_ElfModuleListStream, &dir,
314                                &stream, &size))
315     {
316         WCHAR   buffer[MAX_PATH];
317
318         mml = (MINIDUMP_MODULE_LIST*)stream;
319         for (i = 0, mm = &mml->Modules[0]; i < mml->NumberOfModules; i++, mm++)
320         {
321             mds = (MINIDUMP_STRING*)((char*)data->mapping + mm->ModuleNameRva);
322             memcpy(nameW, mds->Buffer, mds->Length);
323             nameW[mds->Length / sizeof(WCHAR)] = 0;
324             if (SymFindFileInPathW(hProc, NULL, nameW, (void*)(DWORD_PTR)mm->CheckSum,
325                                    0, 0, SSRVOPT_DWORD, buffer, validate_file, NULL))
326                 SymLoadModuleExW(hProc, NULL, buffer, NULL, mm->BaseOfImage, mm->SizeOfImage,
327                                  NULL, 0);
328             else
329                 SymLoadModuleExW(hProc, NULL, nameW, NULL, mm->BaseOfImage, mm->SizeOfImage,
330                                  NULL, SLMFLAG_VIRTUAL);
331         }
332     }
333     if (MiniDumpReadDumpStream(data->mapping, ModuleListStream, &dir, &stream, &size))
334     {
335         WCHAR   buffer[MAX_PATH];
336
337         mml = (MINIDUMP_MODULE_LIST*)stream;
338         for (i = 0, mm = &mml->Modules[0]; i < mml->NumberOfModules; i++, mm++)
339         {
340             mds = (MINIDUMP_STRING*)((char*)data->mapping + mm->ModuleNameRva);
341             memcpy(nameW, mds->Buffer, mds->Length);
342             nameW[mds->Length / sizeof(WCHAR)] = 0;
343             if (SymFindFileInPathW(hProc, NULL, nameW, (void*)(DWORD_PTR)mm->TimeDateStamp,
344                                    mm->SizeOfImage, 0, SSRVOPT_DWORD, buffer, validate_file, NULL))
345                 SymLoadModuleExW(hProc, NULL, buffer, NULL, mm->BaseOfImage, mm->SizeOfImage,
346                                  NULL, 0);
347             else if (is_pe_module_embedded(data, mm))
348                 SymLoadModuleExW(hProc, NULL, nameW, NULL, mm->BaseOfImage, mm->SizeOfImage,
349                                  NULL, 0);
350             else
351                 SymLoadModuleExW(hProc, NULL, nameW, NULL, mm->BaseOfImage, mm->SizeOfImage,
352                                  NULL, SLMFLAG_VIRTUAL);
353         }
354     }
355     if (MiniDumpReadDumpStream(data->mapping, ExceptionStream, &dir, &stream, &size))
356     {
357         MINIDUMP_EXCEPTION_STREAM*      mes = (MINIDUMP_EXCEPTION_STREAM*)stream;
358
359         if ((dbg_curr_thread = dbg_get_thread(dbg_curr_process, mes->ThreadId)))
360         {
361             ADDRESS64   addr;
362
363             dbg_curr_tid = mes->ThreadId;
364             dbg_curr_thread->in_exception = TRUE;
365             dbg_curr_thread->excpt_record.ExceptionCode = mes->ExceptionRecord.ExceptionCode;
366             dbg_curr_thread->excpt_record.ExceptionFlags = mes->ExceptionRecord.ExceptionFlags;
367             dbg_curr_thread->excpt_record.ExceptionRecord = (void*)(DWORD_PTR)mes->ExceptionRecord.ExceptionRecord;
368             dbg_curr_thread->excpt_record.ExceptionAddress = (void*)(DWORD_PTR)mes->ExceptionRecord.ExceptionAddress;
369             dbg_curr_thread->excpt_record.NumberParameters = mes->ExceptionRecord.NumberParameters;
370             for (i = 0; i < dbg_curr_thread->excpt_record.NumberParameters; i++)
371             {
372                 dbg_curr_thread->excpt_record.ExceptionInformation[i] = mes->ExceptionRecord.ExceptionInformation[i];
373             }
374             memcpy(&dbg_context, (char*)data->mapping + mes->ThreadContext.Rva,
375                    min(sizeof(dbg_context), mes->ThreadContext.DataSize));
376             memory_get_current_pc(&addr);
377             stack_fetch_frames();
378             be_cpu->print_context(dbg_curr_thread->handle, &dbg_context, 0);
379             stack_info();
380             be_cpu->print_segment_info(dbg_curr_thread->handle, &dbg_context);
381             stack_backtrace(mes->ThreadId);
382             source_list_from_addr(&addr, 0);
383         }
384     }
385     return start_ok;
386 }
387
388 static void cleanup(struct tgt_process_minidump_data* data)
389 {
390     if (data->mapping)                          UnmapViewOfFile(data->mapping);
391     if (data->hMap)                             CloseHandle(data->hMap);
392     if (data->hFile != INVALID_HANDLE_VALUE)    CloseHandle(data->hFile);
393     HeapFree(GetProcessHeap(), 0, data);
394 }
395
396 static struct be_process_io be_process_minidump_io;
397
398 enum dbg_start minidump_reload(int argc, char* argv[])
399 {
400     struct tgt_process_minidump_data*   data;
401     enum dbg_start                      ret = start_error_parse;
402
403     /* try the form <myself> minidump-file */
404     if (argc != 1) return start_error_parse;
405     
406     WINE_TRACE("Processing Minidump file %s\n", argv[0]);
407
408     data = HeapAlloc(GetProcessHeap(), 0, sizeof(struct tgt_process_minidump_data));
409     if (!data) return start_error_init;
410     data->mapping = NULL;
411     data->hMap    = NULL;
412     data->hFile   = INVALID_HANDLE_VALUE;
413
414     if ((data->hFile = CreateFileA(argv[0], GENERIC_READ, FILE_SHARE_READ, NULL, 
415                                    OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) != INVALID_HANDLE_VALUE &&
416         ((data->hMap = CreateFileMappingA(data->hFile, NULL, PAGE_READONLY, 0, 0, NULL)) != 0) &&
417         ((data->mapping = MapViewOfFile(data->hMap, FILE_MAP_READ, 0, 0, 0)) != NULL))
418     {
419         __TRY
420         {
421             if (((MINIDUMP_HEADER*)data->mapping)->Signature == MINIDUMP_SIGNATURE)
422             {
423                 ret = minidump_do_reload(data);
424             }
425         }
426         __EXCEPT_PAGE_FAULT
427         {
428             dbg_printf("Unexpected fault while reading minidump %s\n", argv[0]);
429             dbg_curr_pid = 0;
430         }
431         __ENDTRY;
432     }
433     if (ret != start_ok) cleanup(data);
434     return ret;
435 }
436
437 static BOOL tgt_process_minidump_close_process(struct dbg_process* pcs, BOOL kill)
438 {
439     struct tgt_process_minidump_data*    data = PRIVATE(pcs);
440
441     cleanup(data);
442     pcs->pio_data = NULL;
443     SymCleanup(pcs->handle);
444     dbg_del_process(pcs);
445     return TRUE;
446 }
447
448 static struct be_process_io be_process_minidump_io =
449 {
450     tgt_process_minidump_close_process,
451     tgt_process_minidump_read,
452     tgt_process_minidump_write,
453 };