]> git.saurik.com Git - wxWidgets.git/blob - src/common/debugrpt.cpp
Add comments explaining the workaround for mingw 3.2.3
[wxWidgets.git] / src / common / debugrpt.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/debugrpt.cpp
3 // Purpose: wxDebugReport and related classes implementation
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 2005-01-17
7 // RCS-ID: $Id$
8 // Copyright: (c) 2005 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // License: wxWindows licence
10 ///////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 #include "wx/wxprec.h"
21
22 #ifdef __BORLANDC__
23 #pragma hdrstop
24 #endif
25
26 #ifndef WX_PRECOMP
27 #include "wx/app.h"
28 #include "wx/log.h"
29 #include "wx/intl.h"
30 #include "wx/utils.h"
31 #endif // WX_PRECOMP
32
33 #if wxUSE_DEBUGREPORT
34
35 #include "wx/debugrpt.h"
36
37 #include "wx/filename.h"
38 #include "wx/dir.h"
39 #include "wx/dynlib.h"
40
41 #include "wx/xml/xml.h"
42
43 #if wxUSE_STACKWALKER
44 #include "wx/stackwalk.h"
45 #endif
46
47 #if wxUSE_CRASHREPORT
48 #include "wx/msw/crashrpt.h"
49 #endif
50
51 #if wxUSE_ZIPSTREAM
52 #include "wx/wfstream.h"
53 #include "wx/zipstrm.h"
54 #include "wx/ptr_scpd.h"
55 #endif // wxUSE_ZIPSTREAM
56
57 WX_CHECK_BUILD_OPTIONS("wxQA")
58
59 // ----------------------------------------------------------------------------
60 // XmlStackWalker: stack walker specialization which dumps stack in XML
61 // ----------------------------------------------------------------------------
62
63 #if wxUSE_STACKWALKER
64
65 class XmlStackWalker : public wxStackWalker
66 {
67 public:
68 XmlStackWalker(wxXmlNode *nodeStack)
69 {
70 m_isOk = false;
71 m_nodeStack = nodeStack;
72 }
73
74 bool IsOk() const { return m_isOk; }
75
76 protected:
77 virtual void OnStackFrame(const wxStackFrame& frame);
78
79 wxXmlNode *m_nodeStack;
80 bool m_isOk;
81 };
82
83 #endif // wxUSE_STACKWALKER
84
85 // ----------------------------------------------------------------------------
86 // local functions
87 // ----------------------------------------------------------------------------
88
89 static inline void
90 HexProperty(wxXmlNode *node, const wxChar *name, unsigned long value)
91 {
92 node->AddProperty(name, wxString::Format(_T("%08lx"), value));
93 }
94
95 static inline void
96 NumProperty(wxXmlNode *node, const wxChar *name, unsigned long value)
97 {
98 node->AddProperty(name, wxString::Format(_T("%lu"), value));
99 }
100
101 static inline void
102 TextElement(wxXmlNode *node, const wxChar *name, const wxString& value)
103 {
104 wxXmlNode *nodeChild = new wxXmlNode(wxXML_ELEMENT_NODE, name);
105 node->AddChild(nodeChild);
106 nodeChild->AddChild(new wxXmlNode(wxXML_TEXT_NODE, _T(""), value));
107 }
108
109 static inline void
110 HexElement(wxXmlNode *node, const wxChar *name, unsigned long value)
111 {
112 TextElement(node, name, wxString::Format(_T("%08lx"), value));
113 }
114
115 #if wxUSE_STACKWALKER
116
117 // ============================================================================
118 // XmlStackWalker implementation
119 // ============================================================================
120
121 void XmlStackWalker::OnStackFrame(const wxStackFrame& frame)
122 {
123 m_isOk = true;
124
125 wxXmlNode *nodeFrame = new wxXmlNode(wxXML_ELEMENT_NODE, _T("frame"));
126 m_nodeStack->AddChild(nodeFrame);
127
128 NumProperty(nodeFrame, _T("level"), frame.GetLevel());
129 wxString func = frame.GetName();
130 if ( !func.empty() )
131 {
132 nodeFrame->AddProperty(_T("function"), func);
133 HexProperty(nodeFrame, _T("offset"), frame.GetOffset());
134 }
135
136 if ( frame.HasSourceLocation() )
137 {
138 nodeFrame->AddProperty(_T("file"), frame.GetFileName());
139 NumProperty(nodeFrame, _T("line"), frame.GetLine());
140 }
141
142 const size_t nParams = frame.GetParamCount();
143 if ( nParams )
144 {
145 wxXmlNode *nodeParams = new wxXmlNode(wxXML_ELEMENT_NODE, _T("parameters"));
146 nodeFrame->AddChild(nodeParams);
147
148 for ( size_t n = 0; n < nParams; n++ )
149 {
150 wxXmlNode *
151 nodeParam = new wxXmlNode(wxXML_ELEMENT_NODE, _T("parameter"));
152 nodeParams->AddChild(nodeParam);
153
154 NumProperty(nodeParam, _T("number"), n);
155
156 wxString type, name, value;
157 if ( !frame.GetParam(n, &type, &name, &value) )
158 continue;
159
160 if ( !type.empty() )
161 TextElement(nodeParam, _T("type"), type);
162
163 if ( !name.empty() )
164 TextElement(nodeParam, _T("name"), name);
165
166 if ( !value.empty() )
167 TextElement(nodeParam, _T("value"), value);
168 }
169 }
170 }
171
172 #endif // wxUSE_STACKWALKER
173
174 // ============================================================================
175 // wxDebugReport implementation
176 // ============================================================================
177
178 // ----------------------------------------------------------------------------
179 // initialization and cleanup
180 // ----------------------------------------------------------------------------
181
182 wxDebugReport::wxDebugReport()
183 {
184 // get a temporary directory name
185 wxString appname = GetReportName();
186
187 // we can't use CreateTempFileName() because it creates a file, not a
188 // directory, so do our best to create a unique name ourselves
189 //
190 // of course, this doesn't protect us against malicious users...
191 wxFileName fn;
192 fn.AssignTempFileName(appname);
193 m_dir.Printf(_T("%s%c%s_dbgrpt-%lu-%s"),
194 fn.GetPath().c_str(), wxFILE_SEP_PATH, appname.c_str(),
195 wxGetProcessId(),
196 wxDateTime::Now().Format(_T("%Y%m%dT%H%M%S")).c_str());
197
198 // as we are going to save the process state there use restrictive
199 // permissions
200 if ( !wxMkdir(m_dir, 0700) )
201 {
202 wxLogSysError(_("Failed to create directory \"%s\""), m_dir.c_str());
203 wxLogError(_("Debug report couldn't be created."));
204
205 Reset();
206 }
207 }
208
209 wxDebugReport::~wxDebugReport()
210 {
211 if ( !m_dir.empty() )
212 {
213 // remove all files in this directory
214 wxDir dir(m_dir);
215 wxString file;
216 for ( bool cont = dir.GetFirst(&file); cont; cont = dir.GetNext(&file) )
217 {
218 if ( wxRemove(wxFileName(m_dir, file).GetFullPath()) != 0 )
219 {
220 wxLogSysError(_("Failed to remove debug report file \"%s\""),
221 file.c_str());
222 m_dir.clear();
223 break;
224 }
225 }
226 }
227
228 if ( !m_dir.empty() )
229 {
230 // Temp fix: what should this be? eVC++ doesn't like wxRmDir
231 #ifdef __WXWINCE__
232 if ( wxRmdir(m_dir.fn_str()) != 0 )
233 #else
234 if ( wxRmDir(m_dir.fn_str()) != 0 )
235 #endif
236 {
237 wxLogSysError(_("Failed to clean up debug report directory \"%s\""),
238 m_dir.c_str());
239 }
240 }
241 }
242
243 // ----------------------------------------------------------------------------
244 // various helpers
245 // ----------------------------------------------------------------------------
246
247 wxString wxDebugReport::GetReportName() const
248 {
249 if(wxTheApp)
250 return wxTheApp->GetAppName();
251
252 return _T("wx");
253 }
254
255 void wxDebugReport::AddFile(const wxString& name, const wxString& description)
256 {
257 m_files.Add(name);
258 m_descriptions.Add(description);
259 }
260
261 void wxDebugReport::RemoveFile(const wxString& name)
262 {
263 const int n = m_files.Index(name);
264 wxCHECK_RET( n != wxNOT_FOUND, _T("No such file in wxDebugReport") );
265
266 m_files.RemoveAt(n);
267 m_descriptions.RemoveAt(n);
268
269 wxRemove(wxFileName(GetDirectory(), name).GetFullPath());
270 }
271
272 bool wxDebugReport::GetFile(size_t n, wxString *name, wxString *desc) const
273 {
274 if ( n >= m_files.GetCount() )
275 return false;
276
277 if ( name )
278 *name = m_files[n];
279 if ( desc )
280 *desc = m_descriptions[n];
281
282 return true;
283 }
284
285 void wxDebugReport::AddAll(Context context)
286 {
287 #if wxUSE_STACKWALKER
288 AddContext(context);
289 #endif // wxUSE_STACKWALKER
290
291 #if wxUSE_CRASHREPORT
292 AddDump(context);
293 #endif // wxUSE_CRASHREPORT
294
295 #if !wxUSE_STACKWALKER && !wxUSE_CRASHREPORT
296 wxUnusedVar(context);
297 #endif
298 }
299
300 // ----------------------------------------------------------------------------
301 // adding basic text information about current context
302 // ----------------------------------------------------------------------------
303
304 #if wxUSE_STACKWALKER
305
306 bool wxDebugReport::DoAddSystemInfo(wxXmlNode *nodeSystemInfo)
307 {
308 nodeSystemInfo->AddProperty(_T("description"), wxGetOsDescription());
309
310 return true;
311 }
312
313 bool wxDebugReport::DoAddLoadedModules(wxXmlNode *nodeModules)
314 {
315 wxDynamicLibraryDetailsArray modules(wxDynamicLibrary::ListLoaded());
316 const size_t count = modules.GetCount();
317 if ( !count )
318 return false;
319
320 for ( size_t n = 0; n < count; n++ )
321 {
322 const wxDynamicLibraryDetails& info = modules[n];
323
324 wxXmlNode *nodeModule = new wxXmlNode(wxXML_ELEMENT_NODE, _T("module"));
325 nodeModules->AddChild(nodeModule);
326
327 wxString path = info.GetPath();
328 if ( path.empty() )
329 path = info.GetName();
330 if ( !path.empty() )
331 nodeModule->AddProperty(_T("path"), path);
332
333 void *addr = NULL;
334 size_t len = 0;
335 if ( info.GetAddress(&addr, &len) )
336 {
337 HexProperty(nodeModule, _T("address"), (unsigned long)addr);
338 HexProperty(nodeModule, _T("size"), len);
339 }
340
341 wxString ver = info.GetVersion();
342 if ( !ver.empty() )
343 {
344 nodeModule->AddProperty(_T("version"), ver);
345 }
346 }
347
348 return true;
349 }
350
351 bool wxDebugReport::DoAddExceptionInfo(wxXmlNode *nodeContext)
352 {
353 #if wxUSE_CRASHREPORT
354 wxCrashContext c;
355 if ( !c.code )
356 return false;
357
358 wxXmlNode *nodeExc = new wxXmlNode(wxXML_ELEMENT_NODE, _T("exception"));
359 nodeContext->AddChild(nodeExc);
360
361 HexProperty(nodeExc, _T("code"), c.code);
362 nodeExc->AddProperty(_T("name"), c.GetExceptionString());
363 HexProperty(nodeExc, _T("address"), (unsigned long)c.addr);
364
365 #ifdef __INTEL__
366 wxXmlNode *nodeRegs = new wxXmlNode(wxXML_ELEMENT_NODE, _T("registers"));
367 nodeContext->AddChild(nodeRegs);
368 HexElement(nodeRegs, _T("eax"), c.regs.eax);
369 HexElement(nodeRegs, _T("ebx"), c.regs.ebx);
370 HexElement(nodeRegs, _T("ecx"), c.regs.edx);
371 HexElement(nodeRegs, _T("edx"), c.regs.edx);
372 HexElement(nodeRegs, _T("esi"), c.regs.esi);
373 HexElement(nodeRegs, _T("edi"), c.regs.edi);
374
375 HexElement(nodeRegs, _T("ebp"), c.regs.ebp);
376 HexElement(nodeRegs, _T("esp"), c.regs.esp);
377 HexElement(nodeRegs, _T("eip"), c.regs.eip);
378
379 HexElement(nodeRegs, _T("cs"), c.regs.cs);
380 HexElement(nodeRegs, _T("ds"), c.regs.ds);
381 HexElement(nodeRegs, _T("es"), c.regs.es);
382 HexElement(nodeRegs, _T("fs"), c.regs.fs);
383 HexElement(nodeRegs, _T("gs"), c.regs.gs);
384 HexElement(nodeRegs, _T("ss"), c.regs.ss);
385
386 HexElement(nodeRegs, _T("flags"), c.regs.flags);
387 #endif // __INTEL__
388
389 return true;
390 #else // !wxUSE_CRASHREPORT
391 wxUnusedVar(nodeContext);
392
393 return false;
394 #endif // wxUSE_CRASHREPORT/!wxUSE_CRASHREPORT
395 }
396
397 bool wxDebugReport::AddContext(wxDebugReport::Context ctx)
398 {
399 wxCHECK_MSG( IsOk(), false, _T("use IsOk() first") );
400
401 // create XML dump of current context
402 wxXmlDocument xmldoc;
403 wxXmlNode *nodeRoot = new wxXmlNode(wxXML_ELEMENT_NODE, _T("report"));
404 xmldoc.SetRoot(nodeRoot);
405 nodeRoot->AddProperty(_T("version"), _T("1.0"));
406 nodeRoot->AddProperty(_T("kind"), ctx == Context_Current ? _T("user")
407 : _T("exception"));
408
409 // add system information
410 wxXmlNode *nodeSystemInfo = new wxXmlNode(wxXML_ELEMENT_NODE, _T("system"));
411 if ( DoAddSystemInfo(nodeSystemInfo) )
412 nodeRoot->AddChild(nodeSystemInfo);
413 else
414 delete nodeSystemInfo;
415
416 // add information about the loaded modules
417 wxXmlNode *nodeModules = new wxXmlNode(wxXML_ELEMENT_NODE, _T("modules"));
418 if ( DoAddLoadedModules(nodeModules) )
419 nodeRoot->AddChild(nodeModules);
420 else
421 delete nodeModules;
422
423 // add CPU context information: this only makes sense for exceptions as our
424 // current context is not very interesting otherwise
425 if ( ctx == Context_Exception )
426 {
427 wxXmlNode *nodeContext = new wxXmlNode(wxXML_ELEMENT_NODE, _T("context"));
428 if ( DoAddExceptionInfo(nodeContext) )
429 nodeRoot->AddChild(nodeContext);
430 else
431 delete nodeContext;
432 }
433
434 // add stack traceback
435 #if wxUSE_STACKWALKER
436 wxXmlNode *nodeStack = new wxXmlNode(wxXML_ELEMENT_NODE, _T("stack"));
437 XmlStackWalker sw(nodeStack);
438 if ( ctx == Context_Exception )
439 {
440 sw.WalkFromException();
441 }
442 else // Context_Current
443 {
444 sw.Walk();
445 }
446
447 if ( sw.IsOk() )
448 nodeRoot->AddChild(nodeStack);
449 else
450 delete nodeStack;
451 #endif // wxUSE_STACKWALKER
452
453 // finally let the user add any extra information he needs
454 DoAddCustomContext(nodeRoot);
455
456
457 // save the entire context dump in a file
458 wxFileName fn(m_dir, GetReportName(), _T("xml"));
459
460 if ( !xmldoc.Save(fn.GetFullPath()) )
461 return false;
462
463 AddFile(fn.GetFullName(), _("process context description"));
464
465 return true;
466 }
467
468 #endif // wxUSE_STACKWALKER
469
470 // ----------------------------------------------------------------------------
471 // adding core dump
472 // ----------------------------------------------------------------------------
473
474 #if wxUSE_CRASHREPORT
475
476 bool wxDebugReport::AddDump(Context ctx)
477 {
478 wxCHECK_MSG( IsOk(), false, _T("use IsOk() first") );
479
480 wxFileName fn(m_dir, GetReportName(), _T("dmp"));
481 wxCrashReport::SetFileName(fn.GetFullPath());
482
483 if ( !(ctx == Context_Exception ? wxCrashReport::Generate()
484 : wxCrashReport::GenerateNow()) )
485 return false;
486
487 AddFile(fn.GetFullName(), _("dump of the process state (binary)"));
488
489 return true;
490 }
491
492 #endif // wxUSE_CRASHREPORT
493
494 // ----------------------------------------------------------------------------
495 // report processing
496 // ----------------------------------------------------------------------------
497
498 bool wxDebugReport::Process()
499 {
500 if ( !GetFilesCount() )
501 {
502 wxLogError(_("Debug report generation has failed."));
503
504 return false;
505 }
506
507 if ( !DoProcess() )
508 {
509 wxLogError(_("Processing debug report has failed, leaving the files in \"%s\" directory."),
510 GetDirectory().c_str());
511
512 Reset();
513
514 return false;
515 }
516
517 return true;
518 }
519
520 bool wxDebugReport::DoProcess()
521 {
522 wxString msg = _("*** A debug report has been generated\n");
523 msg += wxString::Format(_("*** It can be found in \"%s\"\n"),
524 GetDirectory().c_str());
525 msg += _("*** And includes the following files:\n");
526
527 wxString name, desc;
528 const size_t count = GetFilesCount();
529 for ( size_t n = 0; n < count; n++ )
530 {
531 GetFile(n, &name, &desc);
532 msg += wxString::Format(_("\t%s: %s\n"), name.c_str(), desc.c_str());
533 }
534
535 msg += _("\nPlease send this report to the program maintainer, thank you!\n");
536
537 wxLogMessage(_T("%s"), msg.c_str());
538
539 // we have to do this or the report would be deleted, and we don't even
540 // have any way to ask the user if he wants to keep it from here
541 Reset();
542
543 return true;
544 }
545
546 // ============================================================================
547 // wxDebugReport-derived classes
548 // ============================================================================
549
550 #if wxUSE_ZIPSTREAM
551
552 // leave the default name wxZipOutputStreamPtr free for users
553 wxDECLARE_SCOPED_PTR(wxZipOutputStream, wxDbgZipOutputStreamPtr)
554 wxDEFINE_SCOPED_PTR(wxZipOutputStream, wxDbgZipOutputStreamPtr)
555
556 // ----------------------------------------------------------------------------
557 // wxDebugReportCompress
558 // ----------------------------------------------------------------------------
559
560 bool wxDebugReportCompress::DoProcess()
561 {
562 const size_t count = GetFilesCount();
563 if ( !count )
564 return false;
565
566 // create the streams
567 wxFileName fn(GetDirectory(), GetReportName(), _T("zip"));
568 wxFFileOutputStream os(fn.GetFullPath(), _T("wb"));
569
570 // create this one on the heap as a workaround since otherwise the mingw
571 // 3.2.3 linker cannot find ~wxZipOutputStream() when building a dll
572 // version of the library.
573 wxDbgZipOutputStreamPtr zos(new wxZipOutputStream(os, 9));
574
575 // add all files to the ZIP one
576 wxString name, desc;
577 for ( size_t n = 0; n < count; n++ )
578 {
579 GetFile(n, &name, &desc);
580
581 wxZipEntry *ze = new wxZipEntry(name);
582 ze->SetComment(desc);
583
584 if ( !zos->PutNextEntry(ze) )
585 return false;
586
587 wxFileName filename(fn.GetPath(), name);
588 wxFFileInputStream is(filename.GetFullPath());
589 if ( !is.IsOk() || !zos->Write(is).IsOk() )
590 return false;
591 }
592
593 if ( !zos->Close() )
594 return false;
595
596 m_zipfile = fn.GetFullPath();
597
598 return true;
599 }
600
601 // ----------------------------------------------------------------------------
602 // wxDebugReportUpload
603 // ----------------------------------------------------------------------------
604
605 wxDebugReportUpload::wxDebugReportUpload(const wxString& url,
606 const wxString& input,
607 const wxString& action,
608 const wxString& curl)
609 : m_uploadURL(url),
610 m_inputField(input),
611 m_curlCmd(curl)
612 {
613 if ( m_uploadURL.Last() != _T('/') )
614 m_uploadURL += _T('/');
615 m_uploadURL += action;
616 }
617
618 bool wxDebugReportUpload::DoProcess()
619 {
620 if ( !wxDebugReportCompress::DoProcess() )
621 return false;
622
623
624 wxArrayString output, errors;
625 int rc = wxExecute(wxString::Format
626 (
627 _T("%s -F %s=@%s %s"),
628 m_curlCmd.c_str(),
629 m_inputField.c_str(),
630 GetCompressedFileName().c_str(),
631 m_uploadURL.c_str()
632 ),
633 output,
634 errors);
635 if ( rc == -1 )
636 {
637 wxLogError(_("Failed to execute curl, please install it in PATH."));
638 }
639 else if ( rc != 0 )
640 {
641 const size_t count = errors.GetCount();
642 if ( count )
643 {
644 for ( size_t n = 0; n < count; n++ )
645 {
646 wxLogWarning(_T("%s"), errors[n].c_str());
647 }
648 }
649
650 wxLogError(_("Failed to upload the debug report (error code %d)."), rc);
651 }
652 else // rc == 0
653 {
654 if ( OnServerReply(output) )
655 return true;
656 }
657
658 return false;
659 }
660
661 #endif // wxUSE_ZIPSTREAM
662
663 #endif // wxUSE_DEBUGREPORT
664