1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/debugrpt.cpp
3 // Purpose: wxDebugReport and related classes implementation
4 // Author: Vadim Zeitlin
7 // Copyright: (c) 2005 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
8 // Licence: wxWindows licence
9 ///////////////////////////////////////////////////////////////////////////////
11 // ============================================================================
13 // ============================================================================
15 // ----------------------------------------------------------------------------
17 // ----------------------------------------------------------------------------
19 #include "wx/wxprec.h"
32 #if wxUSE_DEBUGREPORT && wxUSE_XML
34 #include "wx/debugrpt.h"
41 #include "wx/filename.h"
43 #include "wx/dynlib.h"
45 #include "wx/xml/xml.h"
48 #include "wx/stackwalk.h"
52 #include "wx/msw/crashrpt.h"
56 #include "wx/wfstream.h"
57 #include "wx/zipstrm.h"
58 #endif // wxUSE_ZIPSTREAM
60 WX_CHECK_BUILD_OPTIONS("wxQA")
62 // ----------------------------------------------------------------------------
63 // XmlStackWalker: stack walker specialization which dumps stack in XML
64 // ----------------------------------------------------------------------------
68 class XmlStackWalker
: public wxStackWalker
71 XmlStackWalker(wxXmlNode
*nodeStack
)
74 m_nodeStack
= nodeStack
;
77 bool IsOk() const { return m_isOk
; }
80 virtual void OnStackFrame(const wxStackFrame
& frame
);
82 wxXmlNode
*m_nodeStack
;
86 // ----------------------------------------------------------------------------
88 // ----------------------------------------------------------------------------
91 HexProperty(wxXmlNode
*node
, const wxChar
*name
, unsigned long value
)
93 node
->AddAttribute(name
, wxString::Format(wxT("%08lx"), value
));
97 NumProperty(wxXmlNode
*node
, const wxChar
*name
, unsigned long value
)
99 node
->AddAttribute(name
, wxString::Format(wxT("%lu"), value
));
103 TextElement(wxXmlNode
*node
, const wxChar
*name
, const wxString
& value
)
105 wxXmlNode
*nodeChild
= new wxXmlNode(wxXML_ELEMENT_NODE
, name
);
106 node
->AddChild(nodeChild
);
107 nodeChild
->AddChild(new wxXmlNode(wxXML_TEXT_NODE
, wxEmptyString
, value
));
110 #if wxUSE_CRASHREPORT && defined(__INTEL__)
113 HexElement(wxXmlNode
*node
, const wxChar
*name
, unsigned long value
)
115 TextElement(node
, name
, wxString::Format(wxT("%08lx"), value
));
118 #endif // wxUSE_CRASHREPORT
120 // ============================================================================
121 // XmlStackWalker implementation
122 // ============================================================================
124 void XmlStackWalker::OnStackFrame(const wxStackFrame
& frame
)
128 wxXmlNode
*nodeFrame
= new wxXmlNode(wxXML_ELEMENT_NODE
, wxT("frame"));
129 m_nodeStack
->AddChild(nodeFrame
);
131 NumProperty(nodeFrame
, wxT("level"), frame
.GetLevel());
132 wxString func
= frame
.GetName();
135 nodeFrame
->AddAttribute(wxT("function"), func
);
136 HexProperty(nodeFrame
, wxT("offset"), frame
.GetOffset());
139 if ( frame
.HasSourceLocation() )
141 nodeFrame
->AddAttribute(wxT("file"), frame
.GetFileName());
142 NumProperty(nodeFrame
, wxT("line"), frame
.GetLine());
145 const size_t nParams
= frame
.GetParamCount();
148 wxXmlNode
*nodeParams
= new wxXmlNode(wxXML_ELEMENT_NODE
, wxT("parameters"));
149 nodeFrame
->AddChild(nodeParams
);
151 for ( size_t n
= 0; n
< nParams
; n
++ )
154 nodeParam
= new wxXmlNode(wxXML_ELEMENT_NODE
, wxT("parameter"));
155 nodeParams
->AddChild(nodeParam
);
157 NumProperty(nodeParam
, wxT("number"), n
);
159 wxString type
, name
, value
;
160 if ( !frame
.GetParam(n
, &type
, &name
, &value
) )
164 TextElement(nodeParam
, wxT("type"), type
);
167 TextElement(nodeParam
, wxT("name"), name
);
169 if ( !value
.empty() )
170 TextElement(nodeParam
, wxT("value"), value
);
175 #endif // wxUSE_STACKWALKER
177 // ============================================================================
178 // wxDebugReport implementation
179 // ============================================================================
181 // ----------------------------------------------------------------------------
182 // initialization and cleanup
183 // ----------------------------------------------------------------------------
185 wxDebugReport::wxDebugReport()
187 // get a temporary directory name
188 wxString appname
= GetReportName();
190 // we can't use CreateTempFileName() because it creates a file, not a
191 // directory, so do our best to create a unique name ourselves
193 // of course, this doesn't protect us against malicious users...
195 m_dir
.Printf(wxT("%s%c%s_dbgrpt-%lu-%s"),
196 wxFileName::GetTempDir(), wxFILE_SEP_PATH
, appname
,
198 wxDateTime::Now().Format(wxT("%Y%m%dT%H%M%S")));
200 m_dir
.Printf(wxT("%s%c%s_dbgrpt-%lu"),
201 wxFileName::GetTempDir(), wxFILE_SEP_PATH
, appname
,
205 // as we are going to save the process state there use restrictive
207 if ( !wxMkdir(m_dir
, 0700) )
209 wxLogSysError(_("Failed to create directory \"%s\""), m_dir
.c_str());
210 wxLogError(_("Debug report couldn't be created."));
216 wxDebugReport::~wxDebugReport()
218 if ( !m_dir
.empty() )
220 // remove all files in this directory
223 for ( bool cont
= dir
.GetFirst(&file
); cont
; cont
= dir
.GetNext(&file
) )
225 if ( wxRemove(wxFileName(m_dir
, file
).GetFullPath()) != 0 )
227 wxLogSysError(_("Failed to remove debug report file \"%s\""),
235 if ( !m_dir
.empty() )
237 // Temp fix: what should this be? eVC++ doesn't like wxRmDir
239 if ( wxRmdir(m_dir
.fn_str()) != 0 )
241 if ( wxRmDir(m_dir
.fn_str()) != 0 )
244 wxLogSysError(_("Failed to clean up debug report directory \"%s\""),
250 // ----------------------------------------------------------------------------
252 // ----------------------------------------------------------------------------
254 wxString
wxDebugReport::GetReportName() const
257 return wxTheApp
->GetAppName();
263 wxDebugReport::AddFile(const wxString
& filename
, const wxString
& description
)
266 wxFileName
fn(filename
);
267 if ( fn
.IsAbsolute() )
269 // we need to copy the file to the debug report directory: give it the
271 name
= fn
.GetFullName();
273 if (!wxCopyFile(fn
.GetFullPath(),
274 wxFileName(GetDirectory(), name
).GetFullPath()))
277 else // file relative to the report directory
281 wxASSERT_MSG( wxFileName(GetDirectory(), name
).FileExists(),
282 wxT("file should exist in debug report directory") );
286 m_descriptions
.Add(description
);
290 wxDebugReport::AddText(const wxString
& filename
,
291 const wxString
& text
,
292 const wxString
& description
)
294 #if wxUSE_FFILE || wxUSE_FILE
295 wxASSERT_MSG( !wxFileName(filename
).IsAbsolute(),
296 wxT("filename should be relative to debug report directory") );
298 const wxString fullPath
= wxFileName(GetDirectory(), filename
).GetFullPath();
300 wxFFile
file(fullPath
, wxT("w"));
302 wxFile
file(fullPath
, wxFile::write
);
304 if ( !file
.IsOpened() || !file
.Write(text
, wxConvAuto()) )
307 AddFile(filename
, description
);
310 #else // !wxUSE_FFILE && !wxUSE_FILE
315 void wxDebugReport::RemoveFile(const wxString
& name
)
317 const int n
= m_files
.Index(name
);
318 wxCHECK_RET( n
!= wxNOT_FOUND
, wxT("No such file in wxDebugReport") );
321 m_descriptions
.RemoveAt(n
);
323 wxRemove(wxFileName(GetDirectory(), name
).GetFullPath());
326 bool wxDebugReport::GetFile(size_t n
, wxString
*name
, wxString
*desc
) const
328 if ( n
>= m_files
.GetCount() )
334 *desc
= m_descriptions
[n
];
339 void wxDebugReport::AddAll(Context context
)
341 #if wxUSE_STACKWALKER
343 #endif // wxUSE_STACKWALKER
345 #if wxUSE_CRASHREPORT
347 #endif // wxUSE_CRASHREPORT
349 #if !wxUSE_STACKWALKER && !wxUSE_CRASHREPORT
350 wxUnusedVar(context
);
354 // ----------------------------------------------------------------------------
355 // adding basic text information about current context
356 // ----------------------------------------------------------------------------
358 #if wxUSE_STACKWALKER
360 bool wxDebugReport::DoAddSystemInfo(wxXmlNode
*nodeSystemInfo
)
362 nodeSystemInfo
->AddAttribute(wxT("description"), wxGetOsDescription());
367 bool wxDebugReport::DoAddLoadedModules(wxXmlNode
*nodeModules
)
369 wxDynamicLibraryDetailsArray
modules(wxDynamicLibrary::ListLoaded());
370 const size_t count
= modules
.GetCount();
374 for ( size_t n
= 0; n
< count
; n
++ )
376 const wxDynamicLibraryDetails
& info
= modules
[n
];
378 wxXmlNode
*nodeModule
= new wxXmlNode(wxXML_ELEMENT_NODE
, wxT("module"));
379 nodeModules
->AddChild(nodeModule
);
381 wxString path
= info
.GetPath();
383 path
= info
.GetName();
385 nodeModule
->AddAttribute(wxT("path"), path
);
389 if ( info
.GetAddress(&addr
, &len
) )
391 HexProperty(nodeModule
, wxT("address"), wxPtrToUInt(addr
));
392 HexProperty(nodeModule
, wxT("size"), len
);
395 wxString ver
= info
.GetVersion();
398 nodeModule
->AddAttribute(wxT("version"), ver
);
405 bool wxDebugReport::DoAddExceptionInfo(wxXmlNode
*nodeContext
)
407 #if wxUSE_CRASHREPORT
412 wxXmlNode
*nodeExc
= new wxXmlNode(wxXML_ELEMENT_NODE
, wxT("exception"));
413 nodeContext
->AddChild(nodeExc
);
415 HexProperty(nodeExc
, wxT("code"), c
.code
);
416 nodeExc
->AddAttribute(wxT("name"), c
.GetExceptionString());
417 HexProperty(nodeExc
, wxT("address"), wxPtrToUInt(c
.addr
));
420 wxXmlNode
*nodeRegs
= new wxXmlNode(wxXML_ELEMENT_NODE
, wxT("registers"));
421 nodeContext
->AddChild(nodeRegs
);
422 HexElement(nodeRegs
, wxT("eax"), c
.regs
.eax
);
423 HexElement(nodeRegs
, wxT("ebx"), c
.regs
.ebx
);
424 HexElement(nodeRegs
, wxT("ecx"), c
.regs
.edx
);
425 HexElement(nodeRegs
, wxT("edx"), c
.regs
.edx
);
426 HexElement(nodeRegs
, wxT("esi"), c
.regs
.esi
);
427 HexElement(nodeRegs
, wxT("edi"), c
.regs
.edi
);
429 HexElement(nodeRegs
, wxT("ebp"), c
.regs
.ebp
);
430 HexElement(nodeRegs
, wxT("esp"), c
.regs
.esp
);
431 HexElement(nodeRegs
, wxT("eip"), c
.regs
.eip
);
433 HexElement(nodeRegs
, wxT("cs"), c
.regs
.cs
);
434 HexElement(nodeRegs
, wxT("ds"), c
.regs
.ds
);
435 HexElement(nodeRegs
, wxT("es"), c
.regs
.es
);
436 HexElement(nodeRegs
, wxT("fs"), c
.regs
.fs
);
437 HexElement(nodeRegs
, wxT("gs"), c
.regs
.gs
);
438 HexElement(nodeRegs
, wxT("ss"), c
.regs
.ss
);
440 HexElement(nodeRegs
, wxT("flags"), c
.regs
.flags
);
444 #else // !wxUSE_CRASHREPORT
445 wxUnusedVar(nodeContext
);
448 #endif // wxUSE_CRASHREPORT/!wxUSE_CRASHREPORT
451 bool wxDebugReport::AddContext(wxDebugReport::Context ctx
)
453 wxCHECK_MSG( IsOk(), false, wxT("use IsOk() first") );
455 // create XML dump of current context
456 wxXmlDocument xmldoc
;
457 wxXmlNode
*nodeRoot
= new wxXmlNode(wxXML_ELEMENT_NODE
, wxT("report"));
458 xmldoc
.SetRoot(nodeRoot
);
459 nodeRoot
->AddAttribute(wxT("version"), wxT("1.0"));
460 nodeRoot
->AddAttribute(wxT("kind"), ctx
== Context_Current
? wxT("user")
463 // add system information
464 wxXmlNode
*nodeSystemInfo
= new wxXmlNode(wxXML_ELEMENT_NODE
, wxT("system"));
465 if ( DoAddSystemInfo(nodeSystemInfo
) )
466 nodeRoot
->AddChild(nodeSystemInfo
);
468 delete nodeSystemInfo
;
470 // add information about the loaded modules
471 wxXmlNode
*nodeModules
= new wxXmlNode(wxXML_ELEMENT_NODE
, wxT("modules"));
472 if ( DoAddLoadedModules(nodeModules
) )
473 nodeRoot
->AddChild(nodeModules
);
477 // add CPU context information: this only makes sense for exceptions as our
478 // current context is not very interesting otherwise
479 if ( ctx
== Context_Exception
)
481 wxXmlNode
*nodeContext
= new wxXmlNode(wxXML_ELEMENT_NODE
, wxT("context"));
482 if ( DoAddExceptionInfo(nodeContext
) )
483 nodeRoot
->AddChild(nodeContext
);
488 // add stack traceback
489 #if wxUSE_STACKWALKER
490 wxXmlNode
*nodeStack
= new wxXmlNode(wxXML_ELEMENT_NODE
, wxT("stack"));
491 XmlStackWalker
sw(nodeStack
);
492 #if wxUSE_ON_FATAL_EXCEPTION
493 if ( ctx
== Context_Exception
)
495 sw
.WalkFromException();
497 else // Context_Current
498 #endif // wxUSE_ON_FATAL_EXCEPTION
504 nodeRoot
->AddChild(nodeStack
);
507 #endif // wxUSE_STACKWALKER
509 // finally let the user add any extra information he needs
510 DoAddCustomContext(nodeRoot
);
513 // save the entire context dump in a file
514 wxFileName
fn(m_dir
, GetReportName(), wxT("xml"));
516 if ( !xmldoc
.Save(fn
.GetFullPath()) )
519 AddFile(fn
.GetFullName(), _("process context description"));
524 #endif // wxUSE_STACKWALKER
526 // ----------------------------------------------------------------------------
528 // ----------------------------------------------------------------------------
530 #if wxUSE_CRASHREPORT
532 bool wxDebugReport::AddDump(Context ctx
)
534 wxCHECK_MSG( IsOk(), false, wxT("use IsOk() first") );
536 wxFileName
fn(m_dir
, GetReportName(), wxT("dmp"));
537 wxCrashReport::SetFileName(fn
.GetFullPath());
539 if ( !(ctx
== Context_Exception
? wxCrashReport::Generate()
540 : wxCrashReport::GenerateNow()) )
543 AddFile(fn
.GetFullName(), _("dump of the process state (binary)"));
548 #endif // wxUSE_CRASHREPORT
550 // ----------------------------------------------------------------------------
552 // ----------------------------------------------------------------------------
554 bool wxDebugReport::Process()
556 if ( !GetFilesCount() )
558 wxLogError(_("Debug report generation has failed."));
565 wxLogError(_("Processing debug report has failed, leaving the files in \"%s\" directory."),
566 GetDirectory().c_str());
576 bool wxDebugReport::DoProcess()
578 wxString
msg(_("A debug report has been generated. It can be found in"));
580 wxT("\t") << GetDirectory() << wxT("\n\n")
581 << _("And includes the following files:\n");
584 const size_t count
= GetFilesCount();
585 for ( size_t n
= 0; n
< count
; n
++ )
587 GetFile(n
, &name
, &desc
);
588 msg
+= wxString::Format("\t%s: %s\n", name
, desc
);
591 msg
+= _("\nPlease send this report to the program maintainer, thank you!\n");
593 wxLogMessage(wxT("%s"), msg
.c_str());
595 // we have to do this or the report would be deleted, and we don't even
596 // have any way to ask the user if he wants to keep it from here
602 // ============================================================================
603 // wxDebugReport-derived classes
604 // ============================================================================
608 // ----------------------------------------------------------------------------
609 // wxDebugReportCompress
610 // ----------------------------------------------------------------------------
612 void wxDebugReportCompress::SetCompressedFileDirectory(const wxString
& dir
)
614 wxASSERT_MSG( m_zipfile
.empty(), "Too late: call this before Process()" );
619 void wxDebugReportCompress::SetCompressedFileBaseName(const wxString
& name
)
621 wxASSERT_MSG( m_zipfile
.empty(), "Too late: call this before Process()" );
626 bool wxDebugReportCompress::DoProcess()
628 #define HAS_FILE_STREAMS (wxUSE_STREAMS && (wxUSE_FILE || wxUSE_FFILE))
630 const size_t count
= GetFilesCount();
634 // create the compressed report file outside of the directory with the
635 // report files as it will be deleted by wxDebugReport dtor but we want to
636 // keep this one: for this we simply treat the directory name as the name
637 // of the file so that its last component becomes our base name
638 wxFileName
fn(GetDirectory());
639 if ( !m_zipDir
.empty() )
640 fn
.SetPath(m_zipDir
);
641 if ( !m_zipName
.empty() )
642 fn
.SetName(m_zipName
);
645 // create the streams
646 const wxString ofullPath
= fn
.GetFullPath();
648 wxFFileOutputStream
os(ofullPath
, wxT("wb"));
650 wxFileOutputStream
os(ofullPath
);
654 wxZipOutputStream
zos(os
, 9);
656 // add all files to the ZIP one
658 for ( size_t n
= 0; n
< count
; n
++ )
660 GetFile(n
, &name
, &desc
);
662 wxZipEntry
*ze
= new wxZipEntry(name
);
663 ze
->SetComment(desc
);
665 if ( !zos
.PutNextEntry(ze
) )
668 const wxString ifullPath
= wxFileName(GetDirectory(), name
).GetFullPath();
670 wxFFileInputStream
is(ifullPath
);
672 wxFileInputStream
is(ifullPath
);
674 if ( !is
.IsOk() || !zos
.Write(is
).IsOk() )
681 m_zipfile
= ofullPath
;
686 #endif // HAS_FILE_STREAMS
689 // ----------------------------------------------------------------------------
690 // wxDebugReportUpload
691 // ----------------------------------------------------------------------------
693 wxDebugReportUpload::wxDebugReportUpload(const wxString
& url
,
694 const wxString
& input
,
695 const wxString
& action
,
696 const wxString
& curl
)
701 if ( m_uploadURL
.Last() != wxT('/') )
702 m_uploadURL
+= wxT('/');
703 m_uploadURL
+= action
;
706 bool wxDebugReportUpload::DoProcess()
708 if ( !wxDebugReportCompress::DoProcess() )
712 wxArrayString output
, errors
;
713 int rc
= wxExecute(wxString::Format
715 wxT("%s -F \"%s=@%s\" %s"),
717 m_inputField
.c_str(),
718 GetCompressedFileName().c_str(),
725 wxLogError(_("Failed to execute curl, please install it in PATH."));
729 const size_t count
= errors
.GetCount();
732 for ( size_t n
= 0; n
< count
; n
++ )
734 wxLogWarning(wxT("%s"), errors
[n
].c_str());
738 wxLogError(_("Failed to upload the debug report (error code %d)."), rc
);
742 if ( OnServerReply(output
) )
749 #endif // wxUSE_ZIPSTREAM
751 #endif // wxUSE_DEBUGREPORT