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