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