]> git.saurik.com Git - wxWidgets.git/blame - src/common/debugrpt.cpp
Use the current font for the DoGetBestSize calculation
[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
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
254void wxDebugReport::AddFile(const wxString& name, const wxString& description)
255{
256 m_files.Add(name);
257 m_descriptions.Add(description);
258}
259
260void wxDebugReport::RemoveFile(const wxString& name)
261{
262 const int n = m_files.Index(name);
263 wxCHECK_RET( n != wxNOT_FOUND, _T("No such file in wxDebugReport") );
264
265 m_files.RemoveAt(n);
266 m_descriptions.RemoveAt(n);
267
268 wxRemove(wxFileName(GetDirectory(), name).GetFullPath());
269}
270
271bool wxDebugReport::GetFile(size_t n, wxString *name, wxString *desc) const
272{
273 if ( n >= m_files.GetCount() )
274 return false;
275
276 if ( name )
277 *name = m_files[n];
278 if ( desc )
279 *desc = m_descriptions[n];
280
281 return true;
282}
283
284void wxDebugReport::AddAll(Context context)
285{
286#if wxUSE_STACKWALKER
287 AddContext(context);
288#endif // wxUSE_STACKWALKER
289
290#if wxUSE_CRASHREPORT
291 AddDump(context);
292#endif // wxUSE_CRASHREPORT
2cdd63c6
WS
293
294#if !wxUSE_STACKWALKER && !wxUSE_CRASHREPORT
295 wxUnusedVar(context);
296#endif
ce4fd7b5
VZ
297}
298
299// ----------------------------------------------------------------------------
300// adding basic text information about current context
301// ----------------------------------------------------------------------------
302
303#if wxUSE_STACKWALKER
304
305bool wxDebugReport::DoAddSystemInfo(wxXmlNode *nodeSystemInfo)
306{
307 nodeSystemInfo->AddProperty(_T("description"), wxGetOsDescription());
308
309 return true;
310}
311
312bool wxDebugReport::DoAddLoadedModules(wxXmlNode *nodeModules)
313{
314 wxDynamicLibraryDetailsArray modules(wxDynamicLibrary::ListLoaded());
315 const size_t count = modules.GetCount();
316 if ( !count )
317 return false;
318
319 for ( size_t n = 0; n < count; n++ )
320 {
321 const wxDynamicLibraryDetails& info = modules[n];
322
323 wxXmlNode *nodeModule = new wxXmlNode(wxXML_ELEMENT_NODE, _T("module"));
324 nodeModules->AddChild(nodeModule);
325
326 wxString path = info.GetPath();
327 if ( path.empty() )
328 path = info.GetName();
329 if ( !path.empty() )
330 nodeModule->AddProperty(_T("path"), path);
331
332 void *addr;
333 size_t len;
334 if ( info.GetAddress(&addr, &len) )
335 {
336 HexProperty(nodeModule, _T("address"), (unsigned long)addr);
337 HexProperty(nodeModule, _T("size"), len);
338 }
339
340 wxString ver = info.GetVersion();
341 if ( !ver.empty() )
342 {
343 nodeModule->AddProperty(_T("version"), ver);
344 }
345 }
346
347 return true;
348}
349
350bool wxDebugReport::DoAddExceptionInfo(wxXmlNode *nodeContext)
351{
352#if wxUSE_CRASHREPORT
353 wxCrashContext c;
354 if ( !c.code )
355 return false;
356
357 wxXmlNode *nodeExc = new wxXmlNode(wxXML_ELEMENT_NODE, _T("exception"));
358 nodeContext->AddChild(nodeExc);
359
360 HexProperty(nodeExc, _T("code"), c.code);
361 nodeExc->AddProperty(_T("name"), c.GetExceptionString());
362 HexProperty(nodeExc, _T("address"), (unsigned long)c.addr);
363
364#ifdef __INTEL__
365 wxXmlNode *nodeRegs = new wxXmlNode(wxXML_ELEMENT_NODE, _T("registers"));
366 nodeContext->AddChild(nodeRegs);
367 HexElement(nodeRegs, _T("eax"), c.regs.eax);
368 HexElement(nodeRegs, _T("ebx"), c.regs.ebx);
369 HexElement(nodeRegs, _T("ecx"), c.regs.edx);
370 HexElement(nodeRegs, _T("edx"), c.regs.edx);
371 HexElement(nodeRegs, _T("esi"), c.regs.esi);
372 HexElement(nodeRegs, _T("edi"), c.regs.edi);
373
374 HexElement(nodeRegs, _T("ebp"), c.regs.ebp);
375 HexElement(nodeRegs, _T("esp"), c.regs.esp);
376 HexElement(nodeRegs, _T("eip"), c.regs.eip);
377
378 HexElement(nodeRegs, _T("cs"), c.regs.cs);
379 HexElement(nodeRegs, _T("ds"), c.regs.ds);
380 HexElement(nodeRegs, _T("es"), c.regs.es);
381 HexElement(nodeRegs, _T("fs"), c.regs.fs);
382 HexElement(nodeRegs, _T("gs"), c.regs.gs);
383 HexElement(nodeRegs, _T("ss"), c.regs.ss);
384
385 HexElement(nodeRegs, _T("flags"), c.regs.flags);
386#endif // __INTEL__
387
388 return true;
389#else // !wxUSE_CRASHREPORT
390 wxUnusedVar(nodeContext);
391
392 return false;
393#endif // wxUSE_CRASHREPORT/!wxUSE_CRASHREPORT
394}
395
396bool wxDebugReport::AddContext(wxDebugReport::Context ctx)
397{
398 wxCHECK_MSG( IsOk(), false, _T("use IsOk() first") );
399
400 // create XML dump of current context
401 wxXmlDocument xmldoc;
402 wxXmlNode *nodeRoot = new wxXmlNode(wxXML_ELEMENT_NODE, _T("report"));
403 xmldoc.SetRoot(nodeRoot);
404 nodeRoot->AddProperty(_T("version"), _T("1.0"));
478cde32
VZ
405 nodeRoot->AddProperty(_T("kind"), ctx == Context_Current ? _T("user")
406 : _T("exception"));
ce4fd7b5
VZ
407
408 // add system information
409 wxXmlNode *nodeSystemInfo = new wxXmlNode(wxXML_ELEMENT_NODE, _T("system"));
410 if ( DoAddSystemInfo(nodeSystemInfo) )
411 nodeRoot->AddChild(nodeSystemInfo);
412 else
413 delete nodeSystemInfo;
414
415 // add information about the loaded modules
416 wxXmlNode *nodeModules = new wxXmlNode(wxXML_ELEMENT_NODE, _T("modules"));
417 if ( DoAddLoadedModules(nodeModules) )
418 nodeRoot->AddChild(nodeModules);
419 else
420 delete nodeModules;
421
422 // add CPU context information: this only makes sense for exceptions as our
423 // current context is not very interesting otherwise
424 if ( ctx == Context_Exception )
425 {
426 wxXmlNode *nodeContext = new wxXmlNode(wxXML_ELEMENT_NODE, _T("context"));
427 if ( DoAddExceptionInfo(nodeContext) )
428 nodeRoot->AddChild(nodeContext);
429 else
430 delete nodeContext;
431 }
432
433 // add stack traceback
434#if wxUSE_STACKWALKER
435 wxXmlNode *nodeStack = new wxXmlNode(wxXML_ELEMENT_NODE, _T("stack"));
436 XmlStackWalker sw(nodeStack);
437 if ( ctx == Context_Exception )
438 {
439 sw.WalkFromException();
440 }
478cde32 441 else // Context_Current
ce4fd7b5
VZ
442 {
443 sw.Walk();
444 }
445
446 if ( sw.IsOk() )
447 nodeRoot->AddChild(nodeStack);
448 else
449 delete nodeStack;
450#endif // wxUSE_STACKWALKER
451
452 // finally let the user add any extra information he needs
453 DoAddCustomContext(nodeRoot);
454
455
456 // save the entire context dump in a file
457 wxFileName fn(m_dir, GetReportName(), _T("xml"));
458
459 if ( !xmldoc.Save(fn.GetFullPath()) )
460 return false;
461
462 AddFile(fn.GetFullName(), _("process context description"));
463
464 return true;
465}
466
467#endif // wxUSE_STACKWALKER
468
469// ----------------------------------------------------------------------------
470// adding core dump
471// ----------------------------------------------------------------------------
472
473#if wxUSE_CRASHREPORT
474
475bool wxDebugReport::AddDump(Context ctx)
476{
477 wxCHECK_MSG( IsOk(), false, _T("use IsOk() first") );
478
479 wxFileName fn(m_dir, GetReportName(), _T("dmp"));
480 wxCrashReport::SetFileName(fn.GetFullPath());
481
482 if ( !(ctx == Context_Exception ? wxCrashReport::Generate()
483 : wxCrashReport::GenerateNow()) )
484 return false;
485
486 AddFile(fn.GetFullName(), _("dump of the process state (binary)"));
487
488 return true;
489}
490
491#endif // wxUSE_CRASHREPORT
492
493// ----------------------------------------------------------------------------
494// report processing
495// ----------------------------------------------------------------------------
496
497bool wxDebugReport::Process()
498{
499 if ( !GetFilesCount() )
500 {
501 wxLogError(_("Debug report generation has failed."));
502
503 return false;
504 }
505
506 if ( !DoProcess() )
507 {
508 wxLogError(_("Processing debug report has failed, leaving the files in \"%s\" directory."),
509 GetDirectory().c_str());
510
511 Reset();
512
513 return false;
514 }
515
516 return true;
517}
518
519bool wxDebugReport::DoProcess()
520{
521 wxString msg = _("*** A debug report has been generated\n");
522 msg += wxString::Format(_("*** It can be found in \"%s\"\n"),
523 GetDirectory().c_str());
524 msg += _("*** And includes the following files:\n");
525
526 wxString name, desc;
527 const size_t count = GetFilesCount();
528 for ( size_t n = 0; n < count; n++ )
529 {
530 GetFile(n, &name, &desc);
531 msg += wxString::Format(_("\t%s: %s\n"), name.c_str(), desc.c_str());
532 }
533
534 msg += _("\nPlease send this report to the program maintainer, thank you!\n");
535
536 wxLogMessage(_T("%s"), msg.c_str());
537
538 // we have to do this or the report would be deleted, and we don't even
539 // have any way to ask the user if he wants to keep it from here
540 Reset();
541
542 return true;
543}
544
545// ============================================================================
546// wxDebugReport-derived classes
547// ============================================================================
548
549#if wxUSE_ZIPSTREAM
550
551// ----------------------------------------------------------------------------
552// wxDebugReportCompress
553// ----------------------------------------------------------------------------
554
555bool wxDebugReportCompress::DoProcess()
556{
557 const size_t count = GetFilesCount();
558 if ( !count )
559 return false;
560
561 // create the streams
562 wxFileName fn(GetDirectory(), GetReportName(), _T("zip"));
563 wxFFileOutputStream os(fn.GetFullPath(), _T("wb"));
564 wxZipOutputStream zos(os, 9);
565
566 // add all files to the ZIP one
567 wxString name, desc;
568 for ( size_t n = 0; n < count; n++ )
569 {
570 GetFile(n, &name, &desc);
571
572 wxZipEntry *ze = new wxZipEntry(name);
573 ze->SetComment(desc);
574
575 if ( !zos.PutNextEntry(ze) )
576 return false;
577
2cdd63c6
WS
578 wxFileName filename(fn.GetPath(), name);
579 wxFFileInputStream is(filename.GetFullPath());
ce4fd7b5
VZ
580 if ( !is.IsOk() || !zos.Write(is).IsOk() )
581 return false;
582 }
583
584 if ( !zos.Close() )
585 return false;
586
587 m_zipfile = fn.GetFullPath();
588
589 return true;
590}
591
592// ----------------------------------------------------------------------------
593// wxDebugReportUpload
594// ----------------------------------------------------------------------------
595
596wxDebugReportUpload::wxDebugReportUpload(const wxString& url,
597 const wxString& input,
598 const wxString& action,
599 const wxString& curl)
600 : m_uploadURL(url),
601 m_inputField(input),
602 m_curlCmd(curl)
603{
604 if ( m_uploadURL.Last() != _T('/') )
605 m_uploadURL += _T('/');
606 m_uploadURL += action;
607}
608
609bool wxDebugReportUpload::DoProcess()
610{
611 if ( !wxDebugReportCompress::DoProcess() )
612 return false;
613
614
615 wxArrayString output, errors;
616 int rc = wxExecute(wxString::Format
617 (
618 _T("%s -F %s=@%s %s"),
619 m_curlCmd.c_str(),
620 m_inputField.c_str(),
621 GetCompressedFileName().c_str(),
622 m_uploadURL.c_str()
623 ),
624 output,
625 errors);
626 if ( rc == -1 )
627 {
628 wxLogError(_("Failed to execute curl, please install it in PATH."));
629 }
630 else if ( rc != 0 )
631 {
632 const size_t count = errors.GetCount();
633 if ( count )
634 {
635 for ( size_t n = 0; n < count; n++ )
636 {
637 wxLogWarning(_T("%s"), errors[n].c_str());
638 }
639 }
640
641 wxLogError(_("Failed to upload the debug report (error code %d)."), rc);
642 }
643 else // rc == 0
644 {
645 if ( OnServerReply(output) )
646 return true;
647 }
648
649 return false;
650}
651
652#endif // wxUSE_ZIPSTREAM
653
654#endif // wxUSE_DEBUGREPORT
655