1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/debugrpt.cpp
3 // Purpose: wxDebugReport and related classes implementation
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 2005 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows licence
10 ///////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 #include "wx/wxprec.h"
33 #if wxUSE_DEBUGREPORT && wxUSE_XML
35 #include "wx/debugrpt.h"
38 #include "wx/filename.h"
40 #include "wx/dynlib.h"
42 #include "wx/xml/xml.h"
45 #include "wx/stackwalk.h"
49 #include "wx/msw/crashrpt.h"
53 #include "wx/wfstream.h"
54 #include "wx/zipstrm.h"
55 #endif // wxUSE_ZIPSTREAM
57 WX_CHECK_BUILD_OPTIONS("wxQA")
59 // ----------------------------------------------------------------------------
60 // XmlStackWalker: stack walker specialization which dumps stack in XML
61 // ----------------------------------------------------------------------------
65 class XmlStackWalker
: public wxStackWalker
68 XmlStackWalker(wxXmlNode
*nodeStack
)
71 m_nodeStack
= nodeStack
;
74 bool IsOk() const { return m_isOk
; }
77 virtual void OnStackFrame(const wxStackFrame
& frame
);
79 wxXmlNode
*m_nodeStack
;
83 // ----------------------------------------------------------------------------
85 // ----------------------------------------------------------------------------
88 HexProperty(wxXmlNode
*node
, const wxChar
*name
, unsigned long value
)
90 node
->AddAttribute(name
, wxString::Format(wxT("%08lx"), value
));
94 NumProperty(wxXmlNode
*node
, const wxChar
*name
, unsigned long value
)
96 node
->AddAttribute(name
, wxString::Format(wxT("%lu"), value
));
100 TextElement(wxXmlNode
*node
, const wxChar
*name
, const wxString
& value
)
102 wxXmlNode
*nodeChild
= new wxXmlNode(wxXML_ELEMENT_NODE
, name
);
103 node
->AddChild(nodeChild
);
104 nodeChild
->AddChild(new wxXmlNode(wxXML_TEXT_NODE
, wxEmptyString
, value
));
107 #if wxUSE_CRASHREPORT && defined(__INTEL__)
110 HexElement(wxXmlNode
*node
, const wxChar
*name
, unsigned long value
)
112 TextElement(node
, name
, wxString::Format(wxT("%08lx"), value
));
115 #endif // wxUSE_CRASHREPORT
117 // ============================================================================
118 // XmlStackWalker implementation
119 // ============================================================================
121 void XmlStackWalker::OnStackFrame(const wxStackFrame
& frame
)
125 wxXmlNode
*nodeFrame
= new wxXmlNode(wxXML_ELEMENT_NODE
, wxT("frame"));
126 m_nodeStack
->AddChild(nodeFrame
);
128 NumProperty(nodeFrame
, wxT("level"), frame
.GetLevel());
129 wxString func
= frame
.GetName();
132 nodeFrame
->AddAttribute(wxT("function"), func
);
133 HexProperty(nodeFrame
, wxT("offset"), frame
.GetOffset());
136 if ( frame
.HasSourceLocation() )
138 nodeFrame
->AddAttribute(wxT("file"), frame
.GetFileName());
139 NumProperty(nodeFrame
, wxT("line"), frame
.GetLine());
142 const size_t nParams
= frame
.GetParamCount();
145 wxXmlNode
*nodeParams
= new wxXmlNode(wxXML_ELEMENT_NODE
, wxT("parameters"));
146 nodeFrame
->AddChild(nodeParams
);
148 for ( size_t n
= 0; n
< nParams
; n
++ )
151 nodeParam
= new wxXmlNode(wxXML_ELEMENT_NODE
, wxT("parameter"));
152 nodeParams
->AddChild(nodeParam
);
154 NumProperty(nodeParam
, wxT("number"), n
);
156 wxString type
, name
, value
;
157 if ( !frame
.GetParam(n
, &type
, &name
, &value
) )
161 TextElement(nodeParam
, wxT("type"), type
);
164 TextElement(nodeParam
, wxT("name"), name
);
166 if ( !value
.empty() )
167 TextElement(nodeParam
, wxT("value"), value
);
172 #endif // wxUSE_STACKWALKER
174 // ============================================================================
175 // wxDebugReport implementation
176 // ============================================================================
178 // ----------------------------------------------------------------------------
179 // initialization and cleanup
180 // ----------------------------------------------------------------------------
182 wxDebugReport::wxDebugReport()
184 // get a temporary directory name
185 wxString appname
= GetReportName();
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
190 // of course, this doesn't protect us against malicious users...
192 fn
.AssignTempFileName(appname
);
194 m_dir
.Printf(wxT("%s%c%s_dbgrpt-%lu-%s"),
195 fn
.GetPath().c_str(), wxFILE_SEP_PATH
, appname
.c_str(),
197 wxDateTime::Now().Format(wxT("%Y%m%dT%H%M%S")).c_str());
199 m_dir
.Printf(wxT("%s%c%s_dbgrpt-%lu"),
200 fn
.GetPath().c_str(), wxFILE_SEP_PATH
, appname
.c_str(),
204 // as we are going to save the process state there use restrictive
206 if ( !wxMkdir(m_dir
, 0700) )
208 wxLogSysError(_("Failed to create directory \"%s\""), m_dir
.c_str());
209 wxLogError(_("Debug report couldn't be created."));
215 wxDebugReport::~wxDebugReport()
217 if ( !m_dir
.empty() )
219 // remove all files in this directory
222 for ( bool cont
= dir
.GetFirst(&file
); cont
; cont
= dir
.GetNext(&file
) )
224 if ( wxRemove(wxFileName(m_dir
, file
).GetFullPath()) != 0 )
226 wxLogSysError(_("Failed to remove debug report file \"%s\""),
234 if ( !m_dir
.empty() )
236 // Temp fix: what should this be? eVC++ doesn't like wxRmDir
238 if ( wxRmdir(m_dir
.fn_str()) != 0 )
240 if ( wxRmDir(m_dir
.fn_str()) != 0 )
243 wxLogSysError(_("Failed to clean up debug report directory \"%s\""),
249 // ----------------------------------------------------------------------------
251 // ----------------------------------------------------------------------------
253 wxString
wxDebugReport::GetReportName() const
256 return wxTheApp
->GetAppName();
262 wxDebugReport::AddFile(const wxString
& filename
, const wxString
& description
)
265 wxFileName
fn(filename
);
266 if ( fn
.IsAbsolute() )
268 // we need to copy the file to the debug report directory: give it the
270 name
= fn
.GetFullName();
272 if (!wxCopyFile(fn
.GetFullPath(),
273 wxFileName(GetDirectory(), name
).GetFullPath()))
276 else // file relative to the report directory
280 wxASSERT_MSG( wxFileName(GetDirectory(), name
).FileExists(),
281 wxT("file should exist in debug report directory") );
285 m_descriptions
.Add(description
);
289 wxDebugReport::AddText(const wxString
& filename
,
290 const wxString
& text
,
291 const wxString
& description
)
293 wxASSERT_MSG( !wxFileName(filename
).IsAbsolute(),
294 wxT("filename should be relative to debug report directory") );
296 wxFileName
fn(GetDirectory(), filename
);
297 wxFFile
file(fn
.GetFullPath(), wxT("w"));
298 if ( !file
.IsOpened() || !file
.Write(text
) )
301 AddFile(filename
, description
);
306 void wxDebugReport::RemoveFile(const wxString
& name
)
308 const int n
= m_files
.Index(name
);
309 wxCHECK_RET( n
!= wxNOT_FOUND
, wxT("No such file in wxDebugReport") );
312 m_descriptions
.RemoveAt(n
);
314 wxRemove(wxFileName(GetDirectory(), name
).GetFullPath());
317 bool wxDebugReport::GetFile(size_t n
, wxString
*name
, wxString
*desc
) const
319 if ( n
>= m_files
.GetCount() )
325 *desc
= m_descriptions
[n
];
330 void wxDebugReport::AddAll(Context context
)
332 #if wxUSE_STACKWALKER
334 #endif // wxUSE_STACKWALKER
336 #if wxUSE_CRASHREPORT
338 #endif // wxUSE_CRASHREPORT
340 #if !wxUSE_STACKWALKER && !wxUSE_CRASHREPORT
341 wxUnusedVar(context
);
345 // ----------------------------------------------------------------------------
346 // adding basic text information about current context
347 // ----------------------------------------------------------------------------
349 #if wxUSE_STACKWALKER
351 bool wxDebugReport::DoAddSystemInfo(wxXmlNode
*nodeSystemInfo
)
353 nodeSystemInfo
->AddAttribute(wxT("description"), wxGetOsDescription());
358 bool wxDebugReport::DoAddLoadedModules(wxXmlNode
*nodeModules
)
360 wxDynamicLibraryDetailsArray
modules(wxDynamicLibrary::ListLoaded());
361 const size_t count
= modules
.GetCount();
365 for ( size_t n
= 0; n
< count
; n
++ )
367 const wxDynamicLibraryDetails
& info
= modules
[n
];
369 wxXmlNode
*nodeModule
= new wxXmlNode(wxXML_ELEMENT_NODE
, wxT("module"));
370 nodeModules
->AddChild(nodeModule
);
372 wxString path
= info
.GetPath();
374 path
= info
.GetName();
376 nodeModule
->AddAttribute(wxT("path"), path
);
380 if ( info
.GetAddress(&addr
, &len
) )
382 HexProperty(nodeModule
, wxT("address"), wxPtrToUInt(addr
));
383 HexProperty(nodeModule
, wxT("size"), len
);
386 wxString ver
= info
.GetVersion();
389 nodeModule
->AddAttribute(wxT("version"), ver
);
396 bool wxDebugReport::DoAddExceptionInfo(wxXmlNode
*nodeContext
)
398 #if wxUSE_CRASHREPORT
403 wxXmlNode
*nodeExc
= new wxXmlNode(wxXML_ELEMENT_NODE
, wxT("exception"));
404 nodeContext
->AddChild(nodeExc
);
406 HexProperty(nodeExc
, wxT("code"), c
.code
);
407 nodeExc
->AddAttribute(wxT("name"), c
.GetExceptionString());
408 HexProperty(nodeExc
, wxT("address"), wxPtrToUInt(c
.addr
));
411 wxXmlNode
*nodeRegs
= new wxXmlNode(wxXML_ELEMENT_NODE
, wxT("registers"));
412 nodeContext
->AddChild(nodeRegs
);
413 HexElement(nodeRegs
, wxT("eax"), c
.regs
.eax
);
414 HexElement(nodeRegs
, wxT("ebx"), c
.regs
.ebx
);
415 HexElement(nodeRegs
, wxT("ecx"), c
.regs
.edx
);
416 HexElement(nodeRegs
, wxT("edx"), c
.regs
.edx
);
417 HexElement(nodeRegs
, wxT("esi"), c
.regs
.esi
);
418 HexElement(nodeRegs
, wxT("edi"), c
.regs
.edi
);
420 HexElement(nodeRegs
, wxT("ebp"), c
.regs
.ebp
);
421 HexElement(nodeRegs
, wxT("esp"), c
.regs
.esp
);
422 HexElement(nodeRegs
, wxT("eip"), c
.regs
.eip
);
424 HexElement(nodeRegs
, wxT("cs"), c
.regs
.cs
);
425 HexElement(nodeRegs
, wxT("ds"), c
.regs
.ds
);
426 HexElement(nodeRegs
, wxT("es"), c
.regs
.es
);
427 HexElement(nodeRegs
, wxT("fs"), c
.regs
.fs
);
428 HexElement(nodeRegs
, wxT("gs"), c
.regs
.gs
);
429 HexElement(nodeRegs
, wxT("ss"), c
.regs
.ss
);
431 HexElement(nodeRegs
, wxT("flags"), c
.regs
.flags
);
435 #else // !wxUSE_CRASHREPORT
436 wxUnusedVar(nodeContext
);
439 #endif // wxUSE_CRASHREPORT/!wxUSE_CRASHREPORT
442 bool wxDebugReport::AddContext(wxDebugReport::Context ctx
)
444 wxCHECK_MSG( IsOk(), false, wxT("use IsOk() first") );
446 // create XML dump of current context
447 wxXmlDocument xmldoc
;
448 wxXmlNode
*nodeRoot
= new wxXmlNode(wxXML_ELEMENT_NODE
, wxT("report"));
449 xmldoc
.SetRoot(nodeRoot
);
450 nodeRoot
->AddAttribute(wxT("version"), wxT("1.0"));
451 nodeRoot
->AddAttribute(wxT("kind"), ctx
== Context_Current
? wxT("user")
454 // add system information
455 wxXmlNode
*nodeSystemInfo
= new wxXmlNode(wxXML_ELEMENT_NODE
, wxT("system"));
456 if ( DoAddSystemInfo(nodeSystemInfo
) )
457 nodeRoot
->AddChild(nodeSystemInfo
);
459 delete nodeSystemInfo
;
461 // add information about the loaded modules
462 wxXmlNode
*nodeModules
= new wxXmlNode(wxXML_ELEMENT_NODE
, wxT("modules"));
463 if ( DoAddLoadedModules(nodeModules
) )
464 nodeRoot
->AddChild(nodeModules
);
468 // add CPU context information: this only makes sense for exceptions as our
469 // current context is not very interesting otherwise
470 if ( ctx
== Context_Exception
)
472 wxXmlNode
*nodeContext
= new wxXmlNode(wxXML_ELEMENT_NODE
, wxT("context"));
473 if ( DoAddExceptionInfo(nodeContext
) )
474 nodeRoot
->AddChild(nodeContext
);
479 // add stack traceback
480 #if wxUSE_STACKWALKER
481 wxXmlNode
*nodeStack
= new wxXmlNode(wxXML_ELEMENT_NODE
, wxT("stack"));
482 XmlStackWalker
sw(nodeStack
);
483 #if wxUSE_ON_FATAL_EXCEPTION
484 if ( ctx
== Context_Exception
)
486 sw
.WalkFromException();
488 else // Context_Current
489 #endif // wxUSE_ON_FATAL_EXCEPTION
495 nodeRoot
->AddChild(nodeStack
);
498 #endif // wxUSE_STACKWALKER
500 // finally let the user add any extra information he needs
501 DoAddCustomContext(nodeRoot
);
504 // save the entire context dump in a file
505 wxFileName
fn(m_dir
, GetReportName(), wxT("xml"));
507 if ( !xmldoc
.Save(fn
.GetFullPath()) )
510 AddFile(fn
.GetFullName(), _("process context description"));
515 #endif // wxUSE_STACKWALKER
517 // ----------------------------------------------------------------------------
519 // ----------------------------------------------------------------------------
521 #if wxUSE_CRASHREPORT
523 bool wxDebugReport::AddDump(Context ctx
)
525 wxCHECK_MSG( IsOk(), false, wxT("use IsOk() first") );
527 wxFileName
fn(m_dir
, GetReportName(), wxT("dmp"));
528 wxCrashReport::SetFileName(fn
.GetFullPath());
530 if ( !(ctx
== Context_Exception
? wxCrashReport::Generate()
531 : wxCrashReport::GenerateNow()) )
534 AddFile(fn
.GetFullName(), _("dump of the process state (binary)"));
539 #endif // wxUSE_CRASHREPORT
541 // ----------------------------------------------------------------------------
543 // ----------------------------------------------------------------------------
545 bool wxDebugReport::Process()
547 if ( !GetFilesCount() )
549 wxLogError(_("Debug report generation has failed."));
556 wxLogError(_("Processing debug report has failed, leaving the files in \"%s\" directory."),
557 GetDirectory().c_str());
567 bool wxDebugReport::DoProcess()
569 wxString
msg(_("A debug report has been generated. It can be found in"));
571 wxT("\t") << GetDirectory() << wxT("\n\n")
572 << _("And includes the following files:\n");
575 const size_t count
= GetFilesCount();
576 for ( size_t n
= 0; n
< count
; n
++ )
578 GetFile(n
, &name
, &desc
);
579 msg
+= wxString::Format("\t%s: %s\n", name
, desc
);
582 msg
+= _("\nPlease send this report to the program maintainer, thank you!\n");
584 wxLogMessage(wxT("%s"), msg
.c_str());
586 // we have to do this or the report would be deleted, and we don't even
587 // have any way to ask the user if he wants to keep it from here
593 // ============================================================================
594 // wxDebugReport-derived classes
595 // ============================================================================
599 // ----------------------------------------------------------------------------
600 // wxDebugReportCompress
601 // ----------------------------------------------------------------------------
603 void wxDebugReportCompress::SetCompressedFileDirectory(const wxString
& dir
)
605 wxASSERT_MSG( m_zipfile
.empty(), "Too late: call this before Process()" );
610 void wxDebugReportCompress::SetCompressedFileBaseName(const wxString
& name
)
612 wxASSERT_MSG( m_zipfile
.empty(), "Too late: call this before Process()" );
617 bool wxDebugReportCompress::DoProcess()
619 const size_t count
= GetFilesCount();
623 // create the compressed report file outside of the directory with the
624 // report files as it will be deleted by wxDebugReport dtor but we want to
625 // keep this one: for this we simply treat the directory name as the name
626 // of the file so that its last component becomes our base name
627 wxFileName
fn(GetDirectory());
628 if ( !m_zipDir
.empty() )
629 fn
.SetPath(m_zipDir
);
630 if ( !m_zipName
.empty() )
631 fn
.SetName(m_zipName
);
634 // create the streams
635 wxFFileOutputStream
os(fn
.GetFullPath(), wxT("wb"));
636 wxZipOutputStream
zos(os
, 9);
638 // add all files to the ZIP one
640 for ( size_t n
= 0; n
< count
; n
++ )
642 GetFile(n
, &name
, &desc
);
644 wxZipEntry
*ze
= new wxZipEntry(name
);
645 ze
->SetComment(desc
);
647 if ( !zos
.PutNextEntry(ze
) )
650 const wxFileName
filename(GetDirectory(), name
);
651 wxFFileInputStream
is(filename
.GetFullPath());
652 if ( !is
.IsOk() || !zos
.Write(is
).IsOk() )
659 m_zipfile
= fn
.GetFullPath();
664 // ----------------------------------------------------------------------------
665 // wxDebugReportUpload
666 // ----------------------------------------------------------------------------
668 wxDebugReportUpload::wxDebugReportUpload(const wxString
& url
,
669 const wxString
& input
,
670 const wxString
& action
,
671 const wxString
& curl
)
676 if ( m_uploadURL
.Last() != wxT('/') )
677 m_uploadURL
+= wxT('/');
678 m_uploadURL
+= action
;
681 bool wxDebugReportUpload::DoProcess()
683 if ( !wxDebugReportCompress::DoProcess() )
687 wxArrayString output
, errors
;
688 int rc
= wxExecute(wxString::Format
690 wxT("%s -F \"%s=@%s\" %s"),
692 m_inputField
.c_str(),
693 GetCompressedFileName().c_str(),
700 wxLogError(_("Failed to execute curl, please install it in PATH."));
704 const size_t count
= errors
.GetCount();
707 for ( size_t n
= 0; n
< count
; n
++ )
709 wxLogWarning(wxT("%s"), errors
[n
].c_str());
713 wxLogError(_("Failed to upload the debug report (error code %d)."), rc
);
717 if ( OnServerReply(output
) )
724 #endif // wxUSE_ZIPSTREAM
726 #endif // wxUSE_DEBUGREPORT