kernel32: Allow any amount of whitespace between the words ANSI and SCSI in /proc...
[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 or AMD Athlon"; break;
226             case 15: str = "Pentium 4 or AMD Athlon64"; break;
227             default: str = "???"; break;
228             }
229             strcat(tmp, str);
230             if (msi->ProcessorLevel == 3 || msi->ProcessorLevel == 4)
231             {
232                 if (HIWORD(msi->ProcessorRevision) == 0xFF)
233                     sprintf(tmp + strlen(tmp), " (%c%d)",
234                             'A' + HIBYTE(LOWORD(msi->ProcessorRevision)),
235                             LOBYTE(LOWORD(msi->ProcessorRevision)));
236                 else
237                     sprintf(tmp + strlen(tmp), " (%c%d)",
238                             'A' + HIWORD(msi->ProcessorRevision),
239                             LOWORD(msi->ProcessorRevision));
240             }
241             else sprintf(tmp + strlen(tmp), " (%d.%d)",
242                          HIWORD(msi->ProcessorRevision),
243                          LOWORD(msi->ProcessorRevision));
244             str = tmp;
245             break;
246         case PROCESSOR_ARCHITECTURE_MIPS:
247             str = "Mips";
248             break;
249         case PROCESSOR_ARCHITECTURE_ALPHA:
250             str = "Alpha";
251             break;
252         case PROCESSOR_ARCHITECTURE_PPC:
253             str = "PowerPC";
254             break;
255         default:
256             str = "???";
257             break;
258         }
259         dbg_printf("  %s was running on #%d %s CPU%s",
260                    exec_name, msi->u.s.NumberOfProcessors, str,
261                    msi->u.s.NumberOfProcessors < 2 ? "" : "s");
262         switch (msi->MajorVersion)
263         {
264         case 3:
265             switch (msi->MinorVersion)
266             {
267             case 51: str = "NT 3.51"; break;
268             default: str = "3-????"; break;
269             }
270             break;
271         case 4:
272             switch (msi->MinorVersion)
273             {
274             case 0: str = (msi->PlatformId == VER_PLATFORM_WIN32_NT) ? "NT 4.0" : "95"; break;
275             case 10: str = "98"; break;
276             case 90: str = "ME"; break;
277             default: str = "5-????"; break;
278             }
279             break;
280         case 5:
281             switch (msi->MinorVersion)
282             {
283             case 0: str = "2000"; break;
284             case 1: str = "XP"; break;
285             case 2: str = "Server 2003"; break;
286             default: str = "5-????"; break;
287             }
288             break;
289         default: str = "???"; break;
290         }
291         dbg_printf(" on Windows %s (%u)\n", str, msi->BuildNumber);
292         /* FIXME CSD: msi->CSDVersionRva */
293     }
294
295     dbg_curr_process = dbg_add_process(&be_process_minidump_io, pid, hProc);
296     dbg_curr_pid = pid;
297     dbg_curr_process->pio_data = data;
298     dbg_set_process_name(dbg_curr_process, exec_name);
299
300     SymInitialize(hProc, NULL, FALSE);
301
302     if (MiniDumpReadDumpStream(data->mapping, ThreadListStream, &dir, &stream, &size))
303     {
304         MINIDUMP_THREAD_LIST*   mtl = (MINIDUMP_THREAD_LIST*)stream;
305         ULONG                   i;
306
307         for (i = 0; i < mtl->NumberOfThreads; i++)
308         {
309             dbg_add_thread(dbg_curr_process, mtl->Threads[i].ThreadId, NULL,
310                            (void*)(DWORD_PTR)mtl->Threads[i].Teb);
311         }
312     }
313     /* first load ELF modules, then do the PE ones */
314     if (MiniDumpReadDumpStream(data->mapping, Wine_ElfModuleListStream, &dir,
315                                &stream, &size))
316     {
317         WCHAR   buffer[MAX_PATH];
318
319         mml = (MINIDUMP_MODULE_LIST*)stream;
320         for (i = 0, mm = &mml->Modules[0]; i < mml->NumberOfModules; i++, mm++)
321         {
322             mds = (MINIDUMP_STRING*)((char*)data->mapping + mm->ModuleNameRva);
323             memcpy(nameW, mds->Buffer, mds->Length);
324             nameW[mds->Length / sizeof(WCHAR)] = 0;
325             if (SymFindFileInPathW(hProc, NULL, nameW, (void*)(DWORD_PTR)mm->CheckSum,
326                                    0, 0, SSRVOPT_DWORD, buffer, validate_file, NULL))
327                 SymLoadModuleExW(hProc, NULL, buffer, NULL, mm->BaseOfImage, mm->SizeOfImage,
328                                  NULL, 0);
329             else
330                 SymLoadModuleExW(hProc, NULL, nameW, NULL, mm->BaseOfImage, mm->SizeOfImage,
331                                  NULL, SLMFLAG_VIRTUAL);
332         }
333     }
334     if (MiniDumpReadDumpStream(data->mapping, ModuleListStream, &dir, &stream, &size))
335     {
336         WCHAR   buffer[MAX_PATH];
337
338         mml = (MINIDUMP_MODULE_LIST*)stream;
339         for (i = 0, mm = &mml->Modules[0]; i < mml->NumberOfModules; i++, mm++)
340         {
341             mds = (MINIDUMP_STRING*)((char*)data->mapping + mm->ModuleNameRva);
342             memcpy(nameW, mds->Buffer, mds->Length);
343             nameW[mds->Length / sizeof(WCHAR)] = 0;
344             if (SymFindFileInPathW(hProc, NULL, nameW, (void*)(DWORD_PTR)mm->TimeDateStamp,
345                                    mm->SizeOfImage, 0, SSRVOPT_DWORD, buffer, validate_file, NULL))
346                 SymLoadModuleExW(hProc, NULL, buffer, NULL, mm->BaseOfImage, mm->SizeOfImage,
347                                  NULL, 0);
348             else if (is_pe_module_embedded(data, mm))
349                 SymLoadModuleExW(hProc, NULL, nameW, NULL, mm->BaseOfImage, mm->SizeOfImage,
350                                  NULL, 0);
351             else
352                 SymLoadModuleExW(hProc, NULL, nameW, NULL, mm->BaseOfImage, mm->SizeOfImage,
353                                  NULL, SLMFLAG_VIRTUAL);
354         }
355     }
356     if (MiniDumpReadDumpStream(data->mapping, ExceptionStream, &dir, &stream, &size))
357     {
358         MINIDUMP_EXCEPTION_STREAM*      mes = (MINIDUMP_EXCEPTION_STREAM*)stream;
359
360         if ((dbg_curr_thread = dbg_get_thread(dbg_curr_process, mes->ThreadId)))
361         {
362             ADDRESS64   addr;
363
364             dbg_curr_tid = mes->ThreadId;
365             dbg_curr_thread->in_exception = TRUE;
366             dbg_curr_thread->excpt_record.ExceptionCode = mes->ExceptionRecord.ExceptionCode;
367             dbg_curr_thread->excpt_record.ExceptionFlags = mes->ExceptionRecord.ExceptionFlags;
368             dbg_curr_thread->excpt_record.ExceptionRecord = (void*)(DWORD_PTR)mes->ExceptionRecord.ExceptionRecord;
369             dbg_curr_thread->excpt_record.ExceptionAddress = (void*)(DWORD_PTR)mes->ExceptionRecord.ExceptionAddress;
370             dbg_curr_thread->excpt_record.NumberParameters = mes->ExceptionRecord.NumberParameters;
371             for (i = 0; i < dbg_curr_thread->excpt_record.NumberParameters; i++)
372             {
373                 dbg_curr_thread->excpt_record.ExceptionInformation[i] = mes->ExceptionRecord.ExceptionInformation[i];
374             }
375             memcpy(&dbg_context, (char*)data->mapping + mes->ThreadContext.Rva,
376                    min(sizeof(dbg_context), mes->ThreadContext.DataSize));
377             memory_get_current_pc(&addr);
378             stack_fetch_frames();
379             be_cpu->print_context(dbg_curr_thread->handle, &dbg_context, 0);
380             stack_info();
381             be_cpu->print_segment_info(dbg_curr_thread->handle, &dbg_context);
382             stack_backtrace(mes->ThreadId);
383             source_list_from_addr(&addr, 0);
384         }
385     }
386     return start_ok;
387 }
388
389 static void cleanup(struct tgt_process_minidump_data* data)
390 {
391     if (data->mapping)                          UnmapViewOfFile(data->mapping);
392     if (data->hMap)                             CloseHandle(data->hMap);
393     if (data->hFile != INVALID_HANDLE_VALUE)    CloseHandle(data->hFile);
394     HeapFree(GetProcessHeap(), 0, data);
395 }
396
397 static struct be_process_io be_process_minidump_io;
398
399 enum dbg_start minidump_reload(int argc, char* argv[])
400 {
401     struct tgt_process_minidump_data*   data;
402     enum dbg_start                      ret = start_error_parse;
403
404     /* try the form <myself> minidump-file */
405     if (argc != 1) return start_error_parse;
406     
407     WINE_TRACE("Processing Minidump file %s\n", argv[0]);
408
409     data = HeapAlloc(GetProcessHeap(), 0, sizeof(struct tgt_process_minidump_data));
410     if (!data) return start_error_init;
411     data->mapping = NULL;
412     data->hMap    = NULL;
413     data->hFile   = INVALID_HANDLE_VALUE;
414
415     if ((data->hFile = CreateFileA(argv[0], GENERIC_READ, FILE_SHARE_READ, NULL, 
416                                    OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) != INVALID_HANDLE_VALUE &&
417         ((data->hMap = CreateFileMappingA(data->hFile, NULL, PAGE_READONLY, 0, 0, NULL)) != 0) &&
418         ((data->mapping = MapViewOfFile(data->hMap, FILE_MAP_READ, 0, 0, 0)) != NULL))
419     {
420         __TRY
421         {
422             if (((MINIDUMP_HEADER*)data->mapping)->Signature == MINIDUMP_SIGNATURE)
423             {
424                 ret = minidump_do_reload(data);
425             }
426         }
427         __EXCEPT_PAGE_FAULT
428         {
429             dbg_printf("Unexpected fault while reading minidump %s\n", argv[0]);
430             dbg_curr_pid = 0;
431         }
432         __ENDTRY;
433     }
434     if (ret != start_ok) cleanup(data);
435     return ret;
436 }
437
438 static BOOL tgt_process_minidump_close_process(struct dbg_process* pcs, BOOL kill)
439 {
440     struct tgt_process_minidump_data*    data = PRIVATE(pcs);
441
442     cleanup(data);
443     pcs->pio_data = NULL;
444     SymCleanup(pcs->handle);
445     dbg_del_process(pcs);
446     return TRUE;
447 }
448
449 static struct be_process_io be_process_minidump_io =
450 {
451     tgt_process_minidump_close_process,
452     tgt_process_minidump_read,
453     tgt_process_minidump_write,
454 };