ntdll: Fixed tape.c compilation on Solaris.
[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     DWORD                               wine_opt;
48
49     hFile = CreateFile(file, GENERIC_READ|GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
50                        FILE_ATTRIBUTE_NORMAL, NULL);
51
52     if (hFile == INVALID_HANDLE_VALUE) return;
53
54     if (rec)
55     {
56         mei.ThreadId = dbg_curr_thread->tid;
57         mei.ExceptionPointers = &ep;
58         ep.ExceptionRecord = (EXCEPTION_RECORD*)rec;
59         ep.ContextRecord = &dbg_context;
60         mei.ClientPointers = FALSE;
61     }
62     /* this is a wine specific options to return also ELF modules in the
63      * dumping
64      */
65     SymSetOptions((wine_opt = SymGetOptions()) | 0x40000000);
66     MiniDumpWriteDump(dbg_curr_process->handle, dbg_curr_process->pid,
67                       hFile, MiniDumpNormal/*|MiniDumpWithDataSegs*/,
68                       rec ? &mei : NULL, NULL, NULL);
69     SymSetOptions(wine_opt);
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, DWORD len, DWORD* 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 (mmd->StartOfMemoryRange <= (DWORD_PTR)addr &&
105                 (DWORD_PTR)addr < mmd->StartOfMemoryRange + mmd->Memory.DataSize)
106             {
107                 len = min(len, mmd->StartOfMemoryRange + mmd->Memory.DataSize - (DWORD_PTR)addr);
108                 memcpy(buffer, 
109                        (char*)PRIVATE(dbg_curr_process)->mapping + mmd->Memory.Rva + (DWORD_PTR)addr - mmd->StartOfMemoryRange,
110                        len);
111                 if (rlen) *rlen = len;
112                 return TRUE;
113             }
114         }
115     }
116     /* FIXME: this is a dirty hack to let the last frame in a bt to work
117      * However, we need to check who's to blame, this code or the current 
118      * dbghelp!StackWalk implementation
119      */
120     if ((DWORD_PTR)addr < 32)
121     {
122         memset(buffer, 0, len); 
123         if (rlen) *rlen = len;
124         return TRUE;
125     }
126     return FALSE;
127 }
128
129 static BOOL WINAPI tgt_process_minidump_write(HANDLE hProcess, void* addr,
130                                              const void* buffer, DWORD len, DWORD* wlen)
131 {
132     return FALSE;
133 }
134
135 BOOL CALLBACK validate_file(PSTR name, void* user)
136 {
137     return FALSE; /* get the first file we find !! */
138 }
139
140 static enum dbg_start minidump_do_reload(struct tgt_process_minidump_data* data)
141 {
142     ULONG                       size;
143     MINIDUMP_DIRECTORY*         dir;
144     void*                       stream;
145     DWORD                       pid = 1; /* by default */
146     HANDLE                      hProc = (HANDLE)0x900DBAAD;
147     int                         i;
148     MINIDUMP_MODULE_LIST*       mml;
149     MINIDUMP_MODULE*            mm;
150     MINIDUMP_STRING*            mds;
151     char                        exec_name[1024];
152     char                        name[1024];
153     unsigned                    len;
154
155     /* fetch PID */
156     if (MiniDumpReadDumpStream(data->mapping, MiscInfoStream, &dir, &stream, &size))
157     {
158         MINIDUMP_MISC_INFO* mmi = (MINIDUMP_MISC_INFO*)stream;
159         if (mmi->Flags1 & MINIDUMP_MISC1_PROCESS_ID)
160             pid = mmi->ProcessId;
161     }
162
163     /* fetch executable name (it's normally the first one in module list) */
164     strcpy(exec_name, "<minidump-exec>"); /* default */
165     if (MiniDumpReadDumpStream(data->mapping, ModuleListStream, &dir, &stream, &size))
166     {
167         mml = (MINIDUMP_MODULE_LIST*)stream;
168         if (mml->NumberOfModules)
169         {
170             char*               ptr;
171
172             mm = &mml->Modules[0];
173             mds = (MINIDUMP_STRING*)((char*)data->mapping + mm->ModuleNameRva);
174             len = WideCharToMultiByte(CP_ACP, 0, mds->Buffer,
175                                       mds->Length / sizeof(WCHAR), 
176                                       name, sizeof(name) - 1, NULL, NULL);
177             name[len] = 0;
178             for (ptr = name + len - 1; ptr >= name; ptr--)
179             {
180                 if (*ptr == '/' || *ptr == '\\')
181                 {
182                     strcpy(exec_name, ptr + 1);
183                     break;
184                 }
185             }
186             if (ptr < name) strcpy(exec_name, name);
187         }
188     }
189
190     if (MiniDumpReadDumpStream(data->mapping, SystemInfoStream, &dir, &stream, &size))
191     {
192         MINIDUMP_SYSTEM_INFO*   msi = (MINIDUMP_SYSTEM_INFO*)stream;
193         const char *str;
194         char tmp[128];
195
196         dbg_printf("WineDbg starting on minidump on pid %lu\n", pid);
197         switch (msi->ProcessorArchitecture)
198         {
199         case PROCESSOR_ARCHITECTURE_UNKNOWN: 
200             str = "Unknown";
201             break;
202         case PROCESSOR_ARCHITECTURE_INTEL:
203             strcpy(tmp, "Intel ");
204             switch (msi->ProcessorLevel)
205             {
206             case 3: str = "80386"; break;
207             case 4: str = "80486"; break;
208             case 5: str = "Pentium"; break;
209             case 6: str = "Pentium Pro/II"; break;
210             default: str = "???"; break;
211             }
212             strcat(tmp, str);
213             if (msi->ProcessorLevel == 3 || msi->ProcessorLevel == 4)
214             {
215                 if (HIWORD(msi->ProcessorRevision) == 0xFF)
216                     sprintf(tmp + strlen(tmp), "-%c%d",
217                             'A' + HIBYTE(LOWORD(msi->ProcessorRevision)),
218                             LOBYTE(LOWORD(msi->ProcessorRevision)));
219                 else
220                     sprintf(tmp + strlen(tmp), "-%c%d",
221                             'A' + HIWORD(msi->ProcessorRevision),
222                             LOWORD(msi->ProcessorRevision));
223             }
224             else sprintf(tmp + strlen(tmp), "-%d.%d",
225                          HIWORD(msi->ProcessorRevision),
226                          LOWORD(msi->ProcessorRevision));
227             str = tmp;
228             break;
229         case PROCESSOR_ARCHITECTURE_MIPS:
230             str = "Mips";
231             break;
232         case PROCESSOR_ARCHITECTURE_ALPHA:
233             str = "Alpha";
234             break;
235         case PROCESSOR_ARCHITECTURE_PPC:
236             str = "PowerPC";
237             break;
238         default:
239             str = "???";
240             break;
241         }
242         dbg_printf("  %s was running on #%d %s CPU%s",
243                    exec_name, msi->u.s.NumberOfProcessors, str, 
244                    msi->u.s.NumberOfProcessors < 2 ? "" : "s");
245         switch (msi->MajorVersion)
246         {
247         case 3:
248             switch (msi->MinorVersion)
249             {
250             case 51: str = "NT 3.51"; break;
251             default: str = "3-????"; break;
252             }
253             break;
254         case 4:
255             switch (msi->MinorVersion)
256             {
257             case 0: str = (msi->PlatformId == VER_PLATFORM_WIN32_NT) ? "NT 4.0" : "95"; break;
258             case 10: str = "98"; break;
259             case 90: str = "ME"; break;
260             default: str = "5-????"; break;
261             }
262             break;
263         case 5:
264             switch (msi->MinorVersion)
265             {
266             case 0: str = "2000"; break;
267             case 1: str = "XP"; break;
268             case 2: str = "Server 2003"; break;
269             default: str = "5-????"; break;
270             }
271             break;
272         default: str = "???"; break;
273         }
274         dbg_printf(" on Windows %s (%lu)\n", str, msi->BuildNumber);
275         /* FIXME CSD: msi->CSDVersionRva */
276     }
277
278     dbg_curr_process = dbg_add_process(&be_process_minidump_io, pid, hProc);
279     dbg_curr_pid = pid;
280     dbg_curr_process->pio_data = data;
281     dbg_set_process_name(dbg_curr_process, exec_name);
282
283     SymInitialize(hProc, NULL, FALSE);
284
285     if (MiniDumpReadDumpStream(data->mapping, ThreadListStream, &dir, &stream, &size))
286     {
287         MINIDUMP_THREAD_LIST*     mtl = (MINIDUMP_THREAD_LIST*)stream;
288         MINIDUMP_THREAD*          mt = &mtl->Threads[0];
289
290         dbg_add_thread(dbg_curr_process, mt->ThreadId, NULL, 
291                        (void*)(DWORD_PTR)mt->Teb);
292     }
293     /* first load ELF modules, then do the PE ones */
294     if (MiniDumpReadDumpStream(data->mapping, Wine_ElfModuleListStream, &dir,
295                                &stream, &size))
296     {
297         char    buffer[MAX_PATH];
298
299         mml = (MINIDUMP_MODULE_LIST*)stream;
300         for (i = 0, mm = &mml->Modules[0]; i < mml->NumberOfModules; i++, mm++)
301         {
302             mds = (MINIDUMP_STRING*)((char*)data->mapping + mm->ModuleNameRva);
303             len = WideCharToMultiByte(CP_ACP, 0, mds->Buffer,
304                                       mds->Length / sizeof(WCHAR), 
305                                       name, sizeof(name) - 1, NULL, NULL);
306             name[len] = 0;
307             if (SymFindFileInPath(hProc, NULL, name, (void*)(DWORD_PTR)mm->CheckSum,
308                                   0, 0, SSRVOPT_DWORD, buffer, validate_file, NULL))
309                 SymLoadModule(hProc, NULL, buffer, NULL, mm->BaseOfImage, mm->SizeOfImage);
310             else
311                 SymLoadModuleEx(hProc, NULL, name, NULL, mm->BaseOfImage, mm->SizeOfImage,
312                                 NULL, SLMFLAG_VIRTUAL);
313         }
314     }
315     if (MiniDumpReadDumpStream(data->mapping, ModuleListStream, &dir, &stream, &size))
316     {
317         mml = (MINIDUMP_MODULE_LIST*)stream;
318         for (i = 0, mm = &mml->Modules[0]; i < mml->NumberOfModules; i++, mm++)
319         {
320             mds = (MINIDUMP_STRING*)((char*)data->mapping + mm->ModuleNameRva);
321             len = WideCharToMultiByte(CP_ACP, 0, mds->Buffer,
322                                       mds->Length / sizeof(WCHAR), 
323                                       name, sizeof(name) - 1, NULL, NULL);
324             name[len] = 0;
325             SymLoadModule(hProc, NULL, name, NULL, 
326                           mm->BaseOfImage, mm->SizeOfImage);
327         }
328     }
329     if (MiniDumpReadDumpStream(data->mapping, ExceptionStream, &dir, &stream, &size))
330     {
331         MINIDUMP_EXCEPTION_STREAM*      mes = (MINIDUMP_EXCEPTION_STREAM*)stream;
332
333         if ((dbg_curr_thread = dbg_get_thread(dbg_curr_process, mes->ThreadId)))
334         {
335             ADDRESS     addr;
336
337             dbg_curr_tid = mes->ThreadId;
338             dbg_curr_thread->in_exception = TRUE;
339             dbg_curr_thread->excpt_record.ExceptionCode = mes->ExceptionRecord.ExceptionCode;
340             dbg_curr_thread->excpt_record.ExceptionFlags = mes->ExceptionRecord.ExceptionFlags;
341             dbg_curr_thread->excpt_record.ExceptionRecord = (void*)(DWORD_PTR)mes->ExceptionRecord.ExceptionRecord;
342             dbg_curr_thread->excpt_record.ExceptionAddress = (void*)(DWORD_PTR)mes->ExceptionRecord.ExceptionAddress;
343             dbg_curr_thread->excpt_record.NumberParameters = mes->ExceptionRecord.NumberParameters;
344             for (i = 0; i < dbg_curr_thread->excpt_record.NumberParameters; i++)
345             {
346                 dbg_curr_thread->excpt_record.ExceptionInformation[i] = mes->ExceptionRecord.ExceptionInformation[i];
347             }
348             memcpy(&dbg_context, (char*)data->mapping + mes->ThreadContext.Rva,
349                    min(sizeof(dbg_context), mes->ThreadContext.DataSize));
350             memory_get_current_pc(&addr);
351             stack_fetch_frames();
352             be_cpu->print_context(dbg_curr_thread->handle, &dbg_context, 0);
353             stack_info();
354             be_cpu->print_segment_info(dbg_curr_thread->handle, &dbg_context);
355             stack_backtrace(mes->ThreadId);
356             source_list_from_addr(&addr, 0);
357         }
358     }
359     return start_ok;
360 }
361
362 static void cleanup(struct tgt_process_minidump_data* data)
363 {
364     if (data->mapping)                          UnmapViewOfFile(data->mapping);
365     if (data->hMap)                             CloseHandle(data->hMap);
366     if (data->hFile != INVALID_HANDLE_VALUE)    CloseHandle(data->hFile);
367     HeapFree(GetProcessHeap(), 0, data);
368 }
369
370 static struct be_process_io be_process_minidump_io;
371
372 enum dbg_start minidump_reload(int argc, char* argv[])
373 {
374     struct tgt_process_minidump_data*   data;
375     enum dbg_start                      ret = start_error_parse;
376
377     /* try the form <myself> minidump-file */
378     if (argc != 1) return start_error_parse;
379     
380     WINE_TRACE("Processing Minidump file %s\n", argv[0]);
381
382     data = HeapAlloc(GetProcessHeap(), 0, sizeof(struct tgt_process_minidump_data));
383     if (!data) return start_error_init;
384     data->mapping = NULL;
385     data->hMap    = NULL;
386     data->hFile   = INVALID_HANDLE_VALUE;
387
388     if ((data->hFile = CreateFileA(argv[0], GENERIC_READ, FILE_SHARE_READ, NULL, 
389                                    OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) != INVALID_HANDLE_VALUE &&
390         ((data->hMap = CreateFileMappingA(data->hFile, NULL, PAGE_READONLY, 0, 0, NULL)) != 0) &&
391         ((data->mapping = MapViewOfFile(data->hMap, FILE_MAP_READ, 0, 0, 0)) != NULL))
392     {
393         __TRY
394         {
395             if (((MINIDUMP_HEADER*)data->mapping)->Signature == MINIDUMP_SIGNATURE)
396             {
397                 ret = minidump_do_reload(data);
398             }
399         }
400         __EXCEPT_PAGE_FAULT
401         {
402             dbg_printf("Unexpected fault while reading minidump %s\n", argv[0]);
403             dbg_curr_pid = 0;
404         }
405         __ENDTRY;
406     }
407     if (ret != start_ok) cleanup(data);
408     return ret;
409 }
410
411 static BOOL tgt_process_minidump_close_process(struct dbg_process* pcs, BOOL kill)
412 {
413     struct tgt_process_minidump_data*    data = PRIVATE(pcs);
414
415     cleanup(data);
416     pcs->pio_data = NULL;
417     SymCleanup(pcs->handle);
418     dbg_del_process(pcs);
419     return TRUE;
420 }
421
422 static struct be_process_io be_process_minidump_io =
423 {
424     tgt_process_minidump_close_process,
425     tgt_process_minidump_read,
426     tgt_process_minidump_write,
427 };