kernel32: Display correct parameters in comm traces.
[wine] / dlls / dbghelp / minidump.c
1 /*
2  * File minidump.c - management of dumps (read & write)
3  *
4  * Copyright (C) 2004-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 #include <time.h>
22
23 #define NONAMELESSUNION
24 #define NONAMELESSSTRUCT
25
26 #include "ntstatus.h"
27 #define WIN32_NO_STATUS
28 #include "dbghelp_private.h"
29 #include "winnls.h"
30 #include "winreg.h"
31 #include "winternl.h"
32 #include "psapi.h"
33 #include "wine/debug.h"
34
35 WINE_DEFAULT_DEBUG_CHANNEL(dbghelp);
36
37 struct dump_memory
38 {
39     ULONG                               base;
40     ULONG                               size;
41     ULONG                               rva;
42 };
43
44 struct dump_module
45 {
46     unsigned                            is_elf;
47     ULONG                               base;
48     ULONG                               size;
49     DWORD                               timestamp;
50     DWORD                               checksum;
51     char                                name[MAX_PATH];
52 };
53
54 struct dump_context
55 {
56     /* process & thread information */
57     HANDLE                              hProcess;
58     DWORD                               pid;
59     void*                               pcs_buffer;
60     SYSTEM_PROCESS_INFORMATION*         spi;
61     /* module information */
62     struct dump_module*                 module;
63     unsigned                            num_module;
64     /* exception information */
65     /* output information */
66     MINIDUMP_TYPE                       type;
67     HANDLE                              hFile;
68     RVA                                 rva;
69     struct dump_memory*                 mem;
70     unsigned                            num_mem;
71     /* callback information */
72     MINIDUMP_CALLBACK_INFORMATION*      cb;
73 };
74
75 /******************************************************************
76  *              fetch_process_info
77  *
78  * reads system wide process information, and make spi point to the record
79  * for process of id 'pid'
80  */
81 static BOOL fetch_process_info(struct dump_context* dc)
82 {
83     ULONG       buf_size = 0x1000;
84     NTSTATUS    nts;
85
86     dc->pcs_buffer = NULL;
87     if (!(dc->pcs_buffer = HeapAlloc(GetProcessHeap(), 0, buf_size))) return FALSE;
88     for (;;)
89     {
90         nts = NtQuerySystemInformation(SystemProcessInformation, 
91                                        dc->pcs_buffer, buf_size, NULL);
92         if (nts != STATUS_INFO_LENGTH_MISMATCH) break;
93         dc->pcs_buffer = HeapReAlloc(GetProcessHeap(), 0, dc->pcs_buffer, 
94                                      buf_size *= 2);
95         if (!dc->pcs_buffer) return FALSE;
96     }
97
98     if (nts == STATUS_SUCCESS)
99     {
100         dc->spi = dc->pcs_buffer;
101         for (;;)
102         {
103             if (dc->spi->dwProcessID == dc->pid) return TRUE;
104             if (!dc->spi->dwOffset) break;
105             dc->spi = (SYSTEM_PROCESS_INFORMATION*)     
106                 ((char*)dc->spi + dc->spi->dwOffset);
107         }
108     }
109     HeapFree(GetProcessHeap(), 0, dc->pcs_buffer);
110     dc->pcs_buffer = NULL;
111     dc->spi = NULL;
112     return FALSE;
113 }
114
115 static void fetch_thread_stack(struct dump_context* dc, void* teb_addr,
116                                const CONTEXT* ctx, MINIDUMP_MEMORY_DESCRIPTOR* mmd)
117 {
118     NT_TIB      tib;
119
120     if (ReadProcessMemory(dc->hProcess, teb_addr, &tib, sizeof(tib), NULL))
121     {
122 #ifdef __i386__
123         /* limiting the stack dumping to the size actually used */
124         if (ctx->Esp)
125             mmd->StartOfMemoryRange = (ctx->Esp - 4);
126         else
127             mmd->StartOfMemoryRange = (ULONG_PTR)tib.StackLimit;
128 #elif defined(__powerpc__)
129         if (ctx->Iar)
130             mmd->StartOfMemoryRange = ctx->Iar - 4;
131         else
132             mmd->StartOfMemoryRange = (ULONG_PTR)tib.StackLimit;
133 #elif defined(__x86_64__)
134         if (ctx->Rsp)
135             mmd->StartOfMemoryRange = (ctx->Rsp - 8);
136         else
137             mmd->StartOfMemoryRange = (ULONG_PTR)tib.StackLimit;
138 #else
139 #error unsupported CPU
140 #endif
141         mmd->Memory.DataSize = (ULONG_PTR)tib.StackBase - mmd->StartOfMemoryRange;
142     }
143 }
144
145 /******************************************************************
146  *              fetch_thread_info
147  *
148  * fetches some information about thread of id 'tid'
149  */
150 static BOOL fetch_thread_info(struct dump_context* dc, int thd_idx,
151                               const MINIDUMP_EXCEPTION_INFORMATION* except,
152                               MINIDUMP_THREAD* mdThd, CONTEXT* ctx)
153 {
154     DWORD                       tid = dc->spi->ti[thd_idx].dwThreadID;
155     HANDLE                      hThread;
156     THREAD_BASIC_INFORMATION    tbi;
157
158     memset(ctx, 0, sizeof(*ctx));
159
160     mdThd->ThreadId = dc->spi->ti[thd_idx].dwThreadID;
161     mdThd->SuspendCount = 0;
162     mdThd->Teb = 0;
163     mdThd->Stack.StartOfMemoryRange = 0;
164     mdThd->Stack.Memory.DataSize = 0;
165     mdThd->Stack.Memory.Rva = 0;
166     mdThd->ThreadContext.DataSize = 0;
167     mdThd->ThreadContext.Rva = 0;
168     mdThd->PriorityClass = dc->spi->ti[thd_idx].dwBasePriority; /* FIXME */
169     mdThd->Priority = dc->spi->ti[thd_idx].dwCurrentPriority;
170
171     if ((hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, tid)) == NULL)
172     {
173         FIXME("Couldn't open thread %u (%u)\n",
174               dc->spi->ti[thd_idx].dwThreadID, GetLastError());
175         return FALSE;
176     }
177     
178     if (NtQueryInformationThread(hThread, ThreadBasicInformation,
179                                  &tbi, sizeof(tbi), NULL) == STATUS_SUCCESS)
180     {
181         mdThd->Teb = (ULONG_PTR)tbi.TebBaseAddress;
182         if (tbi.ExitStatus == STILL_ACTIVE)
183         {
184             if (tid != GetCurrentThreadId() &&
185                 (mdThd->SuspendCount = SuspendThread(hThread)) != (DWORD)-1)
186             {
187                 mdThd->SuspendCount--;
188                 ctx->ContextFlags = CONTEXT_FULL;
189                 if (!GetThreadContext(hThread, ctx))
190                     memset(ctx, 0, sizeof(*ctx));
191
192                 fetch_thread_stack(dc, tbi.TebBaseAddress, ctx, &mdThd->Stack);
193                 ResumeThread(hThread);
194             }
195             else if (tid == GetCurrentThreadId() && except)
196             {
197                 CONTEXT lctx, *pctx;
198                 if (except->ClientPointers)
199                 {
200                     EXCEPTION_POINTERS      ep;
201
202                     ReadProcessMemory(dc->hProcess, except->ExceptionPointers,
203                                       &ep, sizeof(ep), NULL);
204                     ReadProcessMemory(dc->hProcess, ep.ContextRecord,
205                                       &ctx, sizeof(ctx), NULL);
206                     pctx = &lctx;
207                 }
208                 else pctx = except->ExceptionPointers->ContextRecord;
209                 fetch_thread_stack(dc, tbi.TebBaseAddress, pctx, &mdThd->Stack);
210             }
211         }
212     }
213     CloseHandle(hThread);
214     return TRUE;
215 }
216
217 /******************************************************************
218  *              add_module
219  *
220  * Add a module to a dump context
221  */
222 static BOOL add_module(struct dump_context* dc, const char* name,
223                        DWORD base, DWORD size, DWORD timestamp, DWORD checksum,
224                        BOOL is_elf)
225 {
226     if (!dc->module)
227         dc->module = HeapAlloc(GetProcessHeap(), 0,
228                                ++dc->num_module * sizeof(*dc->module));
229     else
230         dc->module = HeapReAlloc(GetProcessHeap(), 0, dc->module,
231                                  ++dc->num_module * sizeof(*dc->module));
232     if (!dc->module) return FALSE;
233     if (is_elf ||
234         !GetModuleFileNameExA(dc->hProcess, (HMODULE)base, 
235                               dc->module[dc->num_module - 1].name,
236                               sizeof(dc->module[dc->num_module - 1].name)))
237         lstrcpynA(dc->module[dc->num_module - 1].name, name,
238                   sizeof(dc->module[dc->num_module - 1].name));
239     dc->module[dc->num_module - 1].base = base;
240     dc->module[dc->num_module - 1].size = size;
241     dc->module[dc->num_module - 1].timestamp = timestamp;
242     dc->module[dc->num_module - 1].checksum = checksum;
243     dc->module[dc->num_module - 1].is_elf = is_elf;
244
245     return TRUE;
246 }
247
248 /******************************************************************
249  *              fetch_pe_module_info_cb
250  *
251  * Callback for accumulating in dump_context a PE modules set
252  */
253 static BOOL WINAPI fetch_pe_module_info_cb(char* name, DWORD base, DWORD size,
254                                            void* user)
255 {
256     struct dump_context*        dc = (struct dump_context*)user;
257     IMAGE_NT_HEADERS            nth;
258
259     if (pe_load_nt_header(dc->hProcess, base, &nth))
260         add_module((struct dump_context*)user, name, base, size, 
261                    nth.FileHeader.TimeDateStamp, nth.OptionalHeader.CheckSum,
262                    FALSE);
263     return TRUE;
264 }
265
266 /******************************************************************
267  *              fetch_elf_module_info_cb
268  *
269  * Callback for accumulating in dump_context an ELF modules set
270  */
271 static BOOL fetch_elf_module_info_cb(const char* name, unsigned long base, 
272                                      void* user)
273 {
274     struct dump_context*        dc = (struct dump_context*)user;
275     DWORD rbase, size, checksum;
276
277     /* FIXME: there's no relevant timestamp on ELF modules */
278     /* NB: if we have a non-null base from the live-target use it (whenever
279      * the ELF module is relocatable or not). If we have a null base (ELF
280      * module isn't relocatable) then grab its base address from ELF file
281      */
282     if (!elf_fetch_file_info(name, &rbase, &size, &checksum))
283         size = checksum = 0;
284     add_module(dc, name, base ? base : rbase, size, 0 /* FIXME */, checksum, TRUE);
285     return TRUE;
286 }
287
288 static void fetch_module_info(struct dump_context* dc)
289 {
290     EnumerateLoadedModules(dc->hProcess, fetch_pe_module_info_cb, dc);
291     /* Since we include ELF modules in a separate stream from the regular PE ones,
292      * we can always include those ELF modules (they don't eat lots of space)
293      * And it's always a good idea to have a trace of the loaded ELF modules for
294      * a given application in a post mortem debugging condition.
295      */
296     elf_enum_modules(dc->hProcess, fetch_elf_module_info_cb, dc);
297 }
298
299 /******************************************************************
300  *              add_memory_block
301  *
302  * Add a memory block to be dumped in a minidump
303  * If rva is non 0, it's the rva in the minidump where has to be stored
304  * also the rva of the memory block when written (this allows to reference
305  * a memory block from outside the list of memory blocks).
306  */
307 static void add_memory_block(struct dump_context* dc, ULONG64 base, ULONG size, ULONG rva)
308 {
309     if (dc->mem)
310         dc->mem = HeapReAlloc(GetProcessHeap(), 0, dc->mem, 
311                               ++dc->num_mem * sizeof(*dc->mem));
312     else
313         dc->mem = HeapAlloc(GetProcessHeap(), 0, ++dc->num_mem * sizeof(*dc->mem));
314     if (dc->mem)
315     {
316         dc->mem[dc->num_mem - 1].base = base;
317         dc->mem[dc->num_mem - 1].size = size;
318         dc->mem[dc->num_mem - 1].rva  = rva;
319     }
320     else dc->num_mem = 0;
321 }
322
323 /******************************************************************
324  *              writeat
325  *
326  * Writes a chunk of data at a given position in the minidump
327  */
328 static void writeat(struct dump_context* dc, RVA rva, void* data, unsigned size)
329 {
330     DWORD       written;
331
332     SetFilePointer(dc->hFile, rva, NULL, FILE_BEGIN);
333     WriteFile(dc->hFile, data, size, &written, NULL);
334 }
335
336 /******************************************************************
337  *              append
338  *
339  * writes a new chunk of data to the minidump, increasing the current
340  * rva in dc
341  */
342 static void append(struct dump_context* dc, void* data, unsigned size)
343 {
344     writeat(dc, dc->rva, data, size);
345     dc->rva += size;
346 }
347
348 /******************************************************************
349  *              dump_exception_info
350  *
351  * Write in File the exception information from pcs
352  */
353 static  void    dump_exception_info(struct dump_context* dc,
354                                     const MINIDUMP_EXCEPTION_INFORMATION* except)
355 {
356     MINIDUMP_EXCEPTION_STREAM   mdExcpt;
357     EXCEPTION_RECORD            rec, *prec;
358     CONTEXT                     ctx, *pctx;
359     int                         i;
360
361     mdExcpt.ThreadId = except->ThreadId;
362     mdExcpt.__alignment = 0;
363     if (except->ClientPointers)
364     {
365         EXCEPTION_POINTERS      ep;
366
367         ReadProcessMemory(dc->hProcess, 
368                           except->ExceptionPointers, &ep, sizeof(ep), NULL);
369         ReadProcessMemory(dc->hProcess, 
370                           ep.ExceptionRecord, &rec, sizeof(rec), NULL);
371         ReadProcessMemory(dc->hProcess, 
372                           ep.ContextRecord, &ctx, sizeof(ctx), NULL);
373         prec = &rec;
374         pctx = &ctx;
375     }
376     else
377     {
378         prec = except->ExceptionPointers->ExceptionRecord;
379         pctx = except->ExceptionPointers->ContextRecord;
380     }
381     mdExcpt.ExceptionRecord.ExceptionCode = prec->ExceptionCode;
382     mdExcpt.ExceptionRecord.ExceptionFlags = prec->ExceptionFlags;
383     mdExcpt.ExceptionRecord.ExceptionRecord = (DWORD_PTR)prec->ExceptionRecord;
384     mdExcpt.ExceptionRecord.ExceptionAddress = (DWORD_PTR)prec->ExceptionAddress;
385     mdExcpt.ExceptionRecord.NumberParameters = prec->NumberParameters;
386     mdExcpt.ExceptionRecord.__unusedAlignment = 0;
387     for (i = 0; i < mdExcpt.ExceptionRecord.NumberParameters; i++)
388         mdExcpt.ExceptionRecord.ExceptionInformation[i] = (DWORD_PTR)prec->ExceptionInformation[i];
389     mdExcpt.ThreadContext.DataSize = sizeof(*pctx);
390     mdExcpt.ThreadContext.Rva = dc->rva + sizeof(mdExcpt);
391
392     append(dc, &mdExcpt, sizeof(mdExcpt));
393     append(dc, pctx, sizeof(*pctx));
394 }
395
396 /******************************************************************
397  *              dump_modules
398  *
399  * Write in File the modules from pcs
400  */
401 static  void    dump_modules(struct dump_context* dc, BOOL dump_elf)
402 {
403     MINIDUMP_MODULE             mdModule;
404     MINIDUMP_MODULE_LIST        mdModuleList;
405     char                        tmp[1024];
406     MINIDUMP_STRING*            ms = (MINIDUMP_STRING*)tmp;
407     ULONG                       i, nmod;
408     RVA                         rva_base;
409     DWORD                       flags_out;
410
411     for (i = nmod = 0; i < dc->num_module; i++)
412     {
413         if ((dc->module[i].is_elf && dump_elf) ||
414             (!dc->module[i].is_elf && !dump_elf))
415             nmod++;
416     }
417
418     mdModuleList.NumberOfModules = 0;
419     /* reserve space for mdModuleList
420      * FIXME: since we don't support 0 length arrays, we cannot use the
421      * size of mdModuleList
422      * FIXME: if we don't ask for all modules in cb, we'll get a hole in the file
423      */
424     rva_base = dc->rva;
425     dc->rva += sizeof(mdModuleList.NumberOfModules) + sizeof(mdModule) * nmod;
426     for (i = 0; i < dc->num_module; i++)
427     {
428         if ((dc->module[i].is_elf && !dump_elf) ||
429             (!dc->module[i].is_elf && dump_elf))
430             continue;
431
432         flags_out = ModuleWriteModule | ModuleWriteMiscRecord | ModuleWriteCvRecord;
433         if (dc->type & MiniDumpWithDataSegs)
434             flags_out |= ModuleWriteDataSeg;
435         if (dc->type & MiniDumpWithProcessThreadData)
436             flags_out |= ModuleWriteTlsData;
437         if (dc->type & MiniDumpWithCodeSegs)
438             flags_out |= ModuleWriteCodeSegs;
439         ms->Length = MultiByteToWideChar(CP_ACP, 0, 
440                                          dc->module[i].name, -1,
441                                          NULL, 0) * sizeof(WCHAR);
442         if (sizeof(ULONG) + ms->Length > sizeof(tmp))
443             FIXME("Buffer overflow!!!\n");
444         MultiByteToWideChar(CP_ACP, 0, dc->module[i].name, -1,
445                             ms->Buffer, ms->Length/sizeof(WCHAR));
446
447         if (dc->cb)
448         {
449             MINIDUMP_CALLBACK_INPUT     cbin;
450             MINIDUMP_CALLBACK_OUTPUT    cbout;
451
452             cbin.ProcessId = dc->pid;
453             cbin.ProcessHandle = dc->hProcess;
454             cbin.CallbackType = ModuleCallback;
455
456             cbin.u.Module.FullPath = ms->Buffer;
457             cbin.u.Module.BaseOfImage = dc->module[i].base;
458             cbin.u.Module.SizeOfImage = dc->module[i].size;
459             cbin.u.Module.CheckSum = dc->module[i].checksum;
460             cbin.u.Module.TimeDateStamp = dc->module[i].timestamp;
461             memset(&cbin.u.Module.VersionInfo, 0, sizeof(cbin.u.Module.VersionInfo));
462             cbin.u.Module.CvRecord = NULL;
463             cbin.u.Module.SizeOfCvRecord = 0;
464             cbin.u.Module.MiscRecord = NULL;
465             cbin.u.Module.SizeOfMiscRecord = 0;
466
467             cbout.u.ModuleWriteFlags = flags_out;
468             if (!dc->cb->CallbackRoutine(dc->cb->CallbackParam, &cbin, &cbout))
469                 continue;
470             flags_out &= cbout.u.ModuleWriteFlags;
471         }
472         if (flags_out & ModuleWriteModule)
473         {
474             mdModule.BaseOfImage = dc->module[i].base;
475             mdModule.SizeOfImage = dc->module[i].size;
476             mdModule.CheckSum = dc->module[i].checksum;
477             mdModule.TimeDateStamp = dc->module[i].timestamp;
478             mdModule.ModuleNameRva = dc->rva;
479             ms->Length -= sizeof(WCHAR);
480             append(dc, ms, sizeof(ULONG) + ms->Length);
481             memset(&mdModule.VersionInfo, 0, sizeof(mdModule.VersionInfo)); /* FIXME */
482             mdModule.CvRecord.DataSize = 0; /* FIXME */
483             mdModule.CvRecord.Rva = 0; /* FIXME */
484             mdModule.MiscRecord.DataSize = 0; /* FIXME */
485             mdModule.MiscRecord.Rva = 0; /* FIXME */
486             mdModule.Reserved0 = 0; /* FIXME */
487             mdModule.Reserved1 = 0; /* FIXME */
488             writeat(dc,
489                     rva_base + sizeof(mdModuleList.NumberOfModules) + 
490                         mdModuleList.NumberOfModules++ * sizeof(mdModule), 
491                     &mdModule, sizeof(mdModule));
492         }
493     }
494     writeat(dc, rva_base, &mdModuleList.NumberOfModules, 
495             sizeof(mdModuleList.NumberOfModules));
496 }
497
498 /******************************************************************
499  *              dump_system_info
500  *
501  * Dumps into File the information about the system
502  */
503 static  void    dump_system_info(struct dump_context* dc)
504 {
505     MINIDUMP_SYSTEM_INFO        mdSysInfo;
506     SYSTEM_INFO                 sysInfo;
507     OSVERSIONINFOW              osInfo;
508     DWORD                       written;
509     ULONG                       slen;
510
511     GetSystemInfo(&sysInfo);
512     osInfo.dwOSVersionInfoSize = sizeof(osInfo);
513     GetVersionExW(&osInfo);
514
515     mdSysInfo.ProcessorArchitecture = sysInfo.u.s.wProcessorArchitecture;
516     mdSysInfo.ProcessorLevel = sysInfo.wProcessorLevel;
517     mdSysInfo.ProcessorRevision = sysInfo.wProcessorRevision;
518     mdSysInfo.u.s.NumberOfProcessors = sysInfo.dwNumberOfProcessors;
519     mdSysInfo.u.s.ProductType = VER_NT_WORKSTATION; /* FIXME */
520     mdSysInfo.MajorVersion = osInfo.dwMajorVersion;
521     mdSysInfo.MinorVersion = osInfo.dwMinorVersion;
522     mdSysInfo.BuildNumber = osInfo.dwBuildNumber;
523     mdSysInfo.PlatformId = osInfo.dwPlatformId;
524
525     mdSysInfo.CSDVersionRva = dc->rva + sizeof(mdSysInfo);
526     mdSysInfo.u1.Reserved1 = 0;
527
528     memset(&mdSysInfo.Cpu, 0, sizeof(mdSysInfo.Cpu));
529
530     append(dc, &mdSysInfo, sizeof(mdSysInfo));
531
532     slen = lstrlenW(osInfo.szCSDVersion) * sizeof(WCHAR);
533     WriteFile(dc->hFile, &slen, sizeof(slen), &written, NULL);
534     WriteFile(dc->hFile, osInfo.szCSDVersion, slen, &written, NULL);
535     dc->rva += sizeof(ULONG) + slen;
536 }
537
538 /******************************************************************
539  *              dump_threads
540  *
541  * Dumps into File the information about running threads
542  */
543 static  void    dump_threads(struct dump_context* dc,
544                              const MINIDUMP_EXCEPTION_INFORMATION* except)
545 {
546     MINIDUMP_THREAD             mdThd;
547     MINIDUMP_THREAD_LIST        mdThdList;
548     unsigned                    i;
549     RVA                         rva_base;
550     DWORD                       flags_out;
551     CONTEXT                     ctx;
552
553     mdThdList.NumberOfThreads = 0;
554
555     rva_base = dc->rva;
556     dc->rva += sizeof(mdThdList.NumberOfThreads) +
557         dc->spi->dwThreadCount * sizeof(mdThd);
558
559     for (i = 0; i < dc->spi->dwThreadCount; i++)
560     {
561         fetch_thread_info(dc, i, except, &mdThd, &ctx);
562
563         flags_out = ThreadWriteThread | ThreadWriteStack | ThreadWriteContext |
564             ThreadWriteInstructionWindow;
565         if (dc->type & MiniDumpWithProcessThreadData)
566             flags_out |= ThreadWriteThreadData;
567         if (dc->type & MiniDumpWithThreadInfo)
568             flags_out |= ThreadWriteThreadInfo;
569
570         if (dc->cb)
571         {
572             MINIDUMP_CALLBACK_INPUT     cbin;
573             MINIDUMP_CALLBACK_OUTPUT    cbout;
574
575             cbin.ProcessId = dc->pid;
576             cbin.ProcessHandle = dc->hProcess;
577             cbin.CallbackType = ThreadCallback;
578             cbin.u.Thread.ThreadId = dc->spi->ti[i].dwThreadID;
579             cbin.u.Thread.ThreadHandle = 0; /* FIXME */
580             memcpy(&cbin.u.Thread.Context, &ctx, sizeof(CONTEXT));
581             cbin.u.Thread.SizeOfContext = sizeof(CONTEXT);
582             cbin.u.Thread.StackBase = mdThd.Stack.StartOfMemoryRange;
583             cbin.u.Thread.StackEnd = mdThd.Stack.StartOfMemoryRange +
584                 mdThd.Stack.Memory.DataSize;
585
586             cbout.u.ThreadWriteFlags = flags_out;
587             if (!dc->cb->CallbackRoutine(dc->cb->CallbackParam, &cbin, &cbout))
588                 continue;
589             flags_out &= cbout.u.ThreadWriteFlags;
590         }
591         if (flags_out & ThreadWriteThread)
592         {
593             if (ctx.ContextFlags && (flags_out & ThreadWriteContext))
594             {
595                 mdThd.ThreadContext.Rva = dc->rva;
596                 mdThd.ThreadContext.DataSize = sizeof(CONTEXT);
597                 append(dc, &ctx, sizeof(CONTEXT));
598             }
599             if (mdThd.Stack.Memory.DataSize && (flags_out & ThreadWriteStack))
600             {
601                 add_memory_block(dc, mdThd.Stack.StartOfMemoryRange,
602                                  mdThd.Stack.Memory.DataSize,
603                                  rva_base + sizeof(mdThdList.NumberOfThreads) +
604                                      mdThdList.NumberOfThreads * sizeof(mdThd) +
605                                      FIELD_OFFSET(MINIDUMP_THREAD, Stack.Memory.Rva));
606             }
607             writeat(dc, 
608                     rva_base + sizeof(mdThdList.NumberOfThreads) +
609                         mdThdList.NumberOfThreads * sizeof(mdThd),
610                     &mdThd, sizeof(mdThd));
611             mdThdList.NumberOfThreads++;
612         }
613         if (ctx.ContextFlags && (flags_out & ThreadWriteInstructionWindow))
614         {
615             /* FIXME: - Native dbghelp also dumps 0x80 bytes around EIP
616              *        - also crop values across module boundaries, 
617              *        - and don't make it i386 dependent 
618              */
619             /* add_memory_block(dc, ctx.Eip - 0x80, ctx.Eip + 0x80, 0); */
620         }
621     }
622     writeat(dc, rva_base,
623             &mdThdList.NumberOfThreads, sizeof(mdThdList.NumberOfThreads));
624 }
625
626 /******************************************************************
627  *              dump_memory_info
628  *
629  * dumps information about the memory of the process (stack of the threads)
630  */
631 static void dump_memory_info(struct dump_context* dc)
632 {
633     MINIDUMP_MEMORY_LIST        mdMemList;
634     MINIDUMP_MEMORY_DESCRIPTOR  mdMem;
635     DWORD                       written;
636     unsigned                    i, pos, len;
637     RVA                         rva_base;
638     char                        tmp[1024];
639
640     mdMemList.NumberOfMemoryRanges = dc->num_mem;
641     append(dc, &mdMemList.NumberOfMemoryRanges,
642            sizeof(mdMemList.NumberOfMemoryRanges));
643     rva_base = dc->rva;
644     dc->rva += mdMemList.NumberOfMemoryRanges * sizeof(mdMem);
645
646     for (i = 0; i < dc->num_mem; i++)
647     {
648         mdMem.StartOfMemoryRange = dc->mem[i].base;
649         mdMem.Memory.Rva = dc->rva;
650         mdMem.Memory.DataSize = dc->mem[i].size;
651         SetFilePointer(dc->hFile, dc->rva, NULL, FILE_BEGIN);
652         for (pos = 0; pos < dc->mem[i].size; pos += sizeof(tmp))
653         {
654             len = min(dc->mem[i].size - pos, sizeof(tmp));
655             if (ReadProcessMemory(dc->hProcess, 
656                                   (void*)(ULONG)(dc->mem[i].base + pos), 
657                                   tmp, len, NULL))
658                 WriteFile(dc->hFile, tmp, len, &written, NULL);
659         }
660         dc->rva += mdMem.Memory.DataSize;
661         writeat(dc, rva_base + i * sizeof(mdMem), &mdMem, sizeof(mdMem));
662         if (dc->mem[i].rva)
663         {
664             writeat(dc, dc->mem[i].rva, &mdMem.Memory.Rva, sizeof(mdMem.Memory.Rva));
665         }
666     }
667 }
668
669 static void dump_misc_info(struct dump_context* dc)
670 {
671     MINIDUMP_MISC_INFO  mmi;
672
673     mmi.SizeOfInfo = sizeof(mmi);
674     mmi.Flags1 = MINIDUMP_MISC1_PROCESS_ID;
675     mmi.ProcessId = dc->pid;
676     /* FIXME: create/user/kernel time */
677     append(dc, &mmi, sizeof(mmi));
678 }
679
680 /******************************************************************
681  *              MiniDumpWriteDump (DEBUGHLP.@)
682  *
683  */
684 BOOL WINAPI MiniDumpWriteDump(HANDLE hProcess, DWORD pid, HANDLE hFile,
685                               MINIDUMP_TYPE DumpType,
686                               PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam,
687                               PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam,
688                               PMINIDUMP_CALLBACK_INFORMATION CallbackParam)
689 {
690     MINIDUMP_HEADER     mdHead;
691     MINIDUMP_DIRECTORY  mdDir;
692     DWORD               i, nStreams, idx_stream;
693     struct dump_context dc;
694
695     dc.hProcess = hProcess;
696     dc.hFile = hFile;
697     dc.pid = pid;
698     dc.module = NULL;
699     dc.num_module = 0;
700     dc.cb = CallbackParam;
701     dc.type = DumpType;
702     dc.mem = NULL;
703     dc.num_mem = 0;
704     dc.rva = 0;
705
706     if (!fetch_process_info(&dc)) return FALSE;
707     fetch_module_info(&dc);
708
709     /* 1) init */
710     nStreams = 6 + (ExceptionParam ? 1 : 0) +
711         (UserStreamParam ? UserStreamParam->UserStreamCount : 0);
712
713     if (DumpType & MiniDumpWithDataSegs)
714         FIXME("NIY MiniDumpWithDataSegs\n");
715     if (DumpType & MiniDumpWithFullMemory)
716         FIXME("NIY MiniDumpWithFullMemory\n");
717     if (DumpType & MiniDumpWithHandleData)
718         FIXME("NIY MiniDumpWithHandleData\n");
719     if (DumpType & MiniDumpFilterMemory)
720         FIXME("NIY MiniDumpFilterMemory\n");
721     if (DumpType & MiniDumpScanMemory)
722         FIXME("NIY MiniDumpScanMemory\n");
723
724     /* 2) write header */
725     mdHead.Signature = MINIDUMP_SIGNATURE;
726     mdHead.Version = MINIDUMP_VERSION;
727     mdHead.NumberOfStreams = nStreams;
728     mdHead.StreamDirectoryRva = sizeof(mdHead);
729     mdHead.u.TimeDateStamp = time(NULL);
730     mdHead.Flags = DumpType;
731     append(&dc, &mdHead, sizeof(mdHead));
732
733     /* 3) write stream directories */
734     dc.rva += nStreams * sizeof(mdDir);
735     idx_stream = 0;
736
737     /* 3.1) write data stream directories */
738
739     mdDir.StreamType = ThreadListStream;
740     mdDir.Location.Rva = dc.rva;
741     dump_threads(&dc, ExceptionParam);
742     mdDir.Location.DataSize = dc.rva - mdDir.Location.Rva;
743     writeat(&dc, mdHead.StreamDirectoryRva + idx_stream++ * sizeof(mdDir), 
744             &mdDir, sizeof(mdDir));
745
746     mdDir.StreamType = ModuleListStream;
747     mdDir.Location.Rva = dc.rva;
748     dump_modules(&dc, FALSE);
749     mdDir.Location.DataSize = dc.rva - mdDir.Location.Rva;
750     writeat(&dc, mdHead.StreamDirectoryRva + idx_stream++ * sizeof(mdDir),
751             &mdDir, sizeof(mdDir));
752
753     mdDir.StreamType = 0xfff0; /* FIXME: this is part of MS reserved streams */
754     mdDir.Location.Rva = dc.rva;
755     dump_modules(&dc, TRUE);
756     mdDir.Location.DataSize = dc.rva - mdDir.Location.Rva;
757     writeat(&dc, mdHead.StreamDirectoryRva + idx_stream++ * sizeof(mdDir),
758             &mdDir, sizeof(mdDir));
759
760     mdDir.StreamType = MemoryListStream;
761     mdDir.Location.Rva = dc.rva;
762     dump_memory_info(&dc);
763     mdDir.Location.DataSize = dc.rva - mdDir.Location.Rva;
764     writeat(&dc, mdHead.StreamDirectoryRva + idx_stream++ * sizeof(mdDir),
765             &mdDir, sizeof(mdDir));
766
767     mdDir.StreamType = SystemInfoStream;
768     mdDir.Location.Rva = dc.rva;
769     dump_system_info(&dc);
770     mdDir.Location.DataSize = dc.rva - mdDir.Location.Rva;
771     writeat(&dc, mdHead.StreamDirectoryRva + idx_stream++ * sizeof(mdDir),
772             &mdDir, sizeof(mdDir));
773
774     mdDir.StreamType = MiscInfoStream;
775     mdDir.Location.Rva = dc.rva;
776     dump_misc_info(&dc);
777     mdDir.Location.DataSize = dc.rva - mdDir.Location.Rva;
778     writeat(&dc, mdHead.StreamDirectoryRva + idx_stream++ * sizeof(mdDir),
779             &mdDir, sizeof(mdDir));
780
781     /* 3.2) write exception information (if any) */
782     if (ExceptionParam)
783     {
784         mdDir.StreamType = ExceptionStream;
785         mdDir.Location.Rva = dc.rva;
786         dump_exception_info(&dc, ExceptionParam);
787         mdDir.Location.DataSize = dc.rva - mdDir.Location.Rva;
788         writeat(&dc, mdHead.StreamDirectoryRva + idx_stream++ * sizeof(mdDir),
789                 &mdDir, sizeof(mdDir));
790     }
791
792     /* 3.3) write user defined streams (if any) */
793     if (UserStreamParam)
794     {
795         for (i = 0; i < UserStreamParam->UserStreamCount; i++)
796         {
797             mdDir.StreamType = UserStreamParam->UserStreamArray[i].Type;
798             mdDir.Location.DataSize = UserStreamParam->UserStreamArray[i].BufferSize;
799             mdDir.Location.Rva = dc.rva;
800             writeat(&dc, mdHead.StreamDirectoryRva + idx_stream++ * sizeof(mdDir),
801                     &mdDir, sizeof(mdDir));
802             append(&dc, UserStreamParam->UserStreamArray[i].Buffer, 
803                    UserStreamParam->UserStreamArray[i].BufferSize);
804         }
805     }
806
807     HeapFree(GetProcessHeap(), 0, dc.pcs_buffer);
808     HeapFree(GetProcessHeap(), 0, dc.mem);
809     HeapFree(GetProcessHeap(), 0, dc.module);
810
811     return TRUE;
812 }
813
814 /******************************************************************
815  *              MiniDumpReadDumpStream (DEBUGHLP.@)
816  *
817  *
818  */
819 BOOL WINAPI MiniDumpReadDumpStream(void* base, ULONG str_idx,
820                                    PMINIDUMP_DIRECTORY* pdir,
821                                    void** stream, ULONG* size)
822 {
823     MINIDUMP_HEADER*    mdHead = (MINIDUMP_HEADER*)base;
824
825     if (mdHead->Signature == MINIDUMP_SIGNATURE)
826     {
827         MINIDUMP_DIRECTORY* dir;
828         int                 i;
829
830         dir = (MINIDUMP_DIRECTORY*)((char*)base + mdHead->StreamDirectoryRva);
831         for (i = 0; i < mdHead->NumberOfStreams; i++, dir++)
832         {
833             if (dir->StreamType == str_idx)
834             {
835                 *pdir = dir;
836                 *stream = (char*)base + dir->Location.Rva;
837                 *size = dir->Location.DataSize;
838                 return TRUE;
839             }
840         }
841     }
842     SetLastError(ERROR_INVALID_PARAMETER);
843     return FALSE;
844 }