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