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