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