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