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