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