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