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