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"
42 #include "wx/filename.h"
44 #include "wx/dynlib.h"
46 #include "wx/xml/xml.h"
49 #include "wx/stackwalk.h"
53 #include "wx/msw/crashrpt.h"
57 #include "wx/wfstream.h"
58 #include "wx/zipstrm.h"
59 #endif // wxUSE_ZIPSTREAM
61 WX_CHECK_BUILD_OPTIONS("wxQA")
63 // ----------------------------------------------------------------------------
64 // XmlStackWalker: stack walker specialization which dumps stack in XML
65 // ----------------------------------------------------------------------------
69 class XmlStackWalker
: public wxStackWalker
72 XmlStackWalker(wxXmlNode
*nodeStack
)
75 m_nodeStack
= nodeStack
;
78 bool IsOk() const { return m_isOk
; }
81 virtual void OnStackFrame(const wxStackFrame
& frame
);
83 wxXmlNode
*m_nodeStack
;
87 // ----------------------------------------------------------------------------
89 // ----------------------------------------------------------------------------
92 HexProperty(wxXmlNode
*node
, const wxChar
*name
, unsigned long value
)
94 node
->AddAttribute(name
, wxString::Format(wxT("%08lx"), value
));
98 NumProperty(wxXmlNode
*node
, const wxChar
*name
, unsigned long value
)
100 node
->AddAttribute(name
, wxString::Format(wxT("%lu"), value
));
104 TextElement(wxXmlNode
*node
, const wxChar
*name
, const wxString
& value
)
106 wxXmlNode
*nodeChild
= new wxXmlNode(wxXML_ELEMENT_NODE
, name
);
107 node
->AddChild(nodeChild
);
108 nodeChild
->AddChild(new wxXmlNode(wxXML_TEXT_NODE
, wxEmptyString
, value
));
111 #if wxUSE_CRASHREPORT && defined(__INTEL__)
114 HexElement(wxXmlNode
*node
, const wxChar
*name
, unsigned long value
)
116 TextElement(node
, name
, wxString::Format(wxT("%08lx"), value
));
119 #endif // wxUSE_CRASHREPORT
121 // ============================================================================
122 // XmlStackWalker implementation
123 // ============================================================================
125 void XmlStackWalker::OnStackFrame(const wxStackFrame
& frame
)
129 wxXmlNode
*nodeFrame
= new wxXmlNode(wxXML_ELEMENT_NODE
, wxT("frame"));
130 m_nodeStack
->AddChild(nodeFrame
);
132 NumProperty(nodeFrame
, wxT("level"), frame
.GetLevel());
133 wxString func
= frame
.GetName();
136 nodeFrame
->AddAttribute(wxT("function"), func
);
137 HexProperty(nodeFrame
, wxT("offset"), frame
.GetOffset());
140 if ( frame
.HasSourceLocation() )
142 nodeFrame
->AddAttribute(wxT("file"), frame
.GetFileName());
143 NumProperty(nodeFrame
, wxT("line"), frame
.GetLine());
146 const size_t nParams
= frame
.GetParamCount();
149 wxXmlNode
*nodeParams
= new wxXmlNode(wxXML_ELEMENT_NODE
, wxT("parameters"));
150 nodeFrame
->AddChild(nodeParams
);
152 for ( size_t n
= 0; n
< nParams
; n
++ )
155 nodeParam
= new wxXmlNode(wxXML_ELEMENT_NODE
, wxT("parameter"));
156 nodeParams
->AddChild(nodeParam
);
158 NumProperty(nodeParam
, wxT("number"), n
);
160 wxString type
, name
, value
;
161 if ( !frame
.GetParam(n
, &type
, &name
, &value
) )
165 TextElement(nodeParam
, wxT("type"), type
);
168 TextElement(nodeParam
, wxT("name"), name
);
170 if ( !value
.empty() )
171 TextElement(nodeParam
, wxT("value"), value
);
176 #endif // wxUSE_STACKWALKER
178 // ============================================================================
179 // wxDebugReport implementation
180 // ============================================================================
182 // ----------------------------------------------------------------------------
183 // initialization and cleanup
184 // ----------------------------------------------------------------------------
186 wxDebugReport::wxDebugReport()
188 // get a temporary directory name
189 wxString appname
= GetReportName();
191 // we can't use CreateTempFileName() because it creates a file, not a
192 // directory, so do our best to create a unique name ourselves
194 // of course, this doesn't protect us against malicious users...
196 m_dir
.Printf(wxT("%s%c%s_dbgrpt-%lu-%s"),
197 wxFileName::GetTempDir(), wxFILE_SEP_PATH
, appname
,
199 wxDateTime::Now().Format(wxT("%Y%m%dT%H%M%S")));
201 m_dir
.Printf(wxT("%s%c%s_dbgrpt-%lu"),
202 wxFileName::GetTempDir(), wxFILE_SEP_PATH
, appname
,
206 // as we are going to save the process state there use restrictive
208 if ( !wxMkdir(m_dir
, 0700) )
210 wxLogSysError(_("Failed to create directory \"%s\""), m_dir
.c_str());
211 wxLogError(_("Debug report couldn't be created."));
217 wxDebugReport::~wxDebugReport()
219 if ( !m_dir
.empty() )
221 // remove all files in this directory
224 for ( bool cont
= dir
.GetFirst(&file
); cont
; cont
= dir
.GetNext(&file
) )
226 if ( wxRemove(wxFileName(m_dir
, file
).GetFullPath()) != 0 )
228 wxLogSysError(_("Failed to remove debug report file \"%s\""),
236 if ( !m_dir
.empty() )
238 // Temp fix: what should this be? eVC++ doesn't like wxRmDir
240 if ( wxRmdir(m_dir
.fn_str()) != 0 )
242 if ( wxRmDir(m_dir
.fn_str()) != 0 )
245 wxLogSysError(_("Failed to clean up debug report directory \"%s\""),
251 // ----------------------------------------------------------------------------
253 // ----------------------------------------------------------------------------
255 wxString
wxDebugReport::GetReportName() const
258 return wxTheApp
->GetAppName();
264 wxDebugReport::AddFile(const wxString
& filename
, const wxString
& description
)
267 wxFileName
fn(filename
);
268 if ( fn
.IsAbsolute() )
270 // we need to copy the file to the debug report directory: give it the
272 name
= fn
.GetFullName();
274 if (!wxCopyFile(fn
.GetFullPath(),
275 wxFileName(GetDirectory(), name
).GetFullPath()))
278 else // file relative to the report directory
282 wxASSERT_MSG( wxFileName(GetDirectory(), name
).FileExists(),
283 wxT("file should exist in debug report directory") );
287 m_descriptions
.Add(description
);
291 wxDebugReport::AddText(const wxString
& filename
,
292 const wxString
& text
,
293 const wxString
& description
)
295 #if wxUSE_FFILE || wxUSE_FILE
296 wxASSERT_MSG( !wxFileName(filename
).IsAbsolute(),
297 wxT("filename should be relative to debug report directory") );
299 const wxString fullPath
= wxFileName(GetDirectory(), filename
).GetFullPath();
301 wxFFile
file(fullPath
, wxT("w"));
303 wxFile
file(fullPath
, wxFile::write
);
305 if ( !file
.IsOpened() || !file
.Write(text
, wxConvAuto()) )
308 AddFile(filename
, description
);
311 #else // !wxUSE_FFILE && !wxUSE_FILE
316 void wxDebugReport::RemoveFile(const wxString
& name
)
318 const int n
= m_files
.Index(name
);
319 wxCHECK_RET( n
!= wxNOT_FOUND
, wxT("No such file in wxDebugReport") );
322 m_descriptions
.RemoveAt(n
);
324 wxRemove(wxFileName(GetDirectory(), name
).GetFullPath());
327 bool wxDebugReport::GetFile(size_t n
, wxString
*name
, wxString
*desc
) const
329 if ( n
>= m_files
.GetCount() )
335 *desc
= m_descriptions
[n
];
340 void wxDebugReport::AddAll(Context context
)
342 #if wxUSE_STACKWALKER
344 #endif // wxUSE_STACKWALKER
346 #if wxUSE_CRASHREPORT
348 #endif // wxUSE_CRASHREPORT
350 #if !wxUSE_STACKWALKER && !wxUSE_CRASHREPORT
351 wxUnusedVar(context
);
355 // ----------------------------------------------------------------------------
356 // adding basic text information about current context
357 // ----------------------------------------------------------------------------
359 #if wxUSE_STACKWALKER
361 bool wxDebugReport::DoAddSystemInfo(wxXmlNode
*nodeSystemInfo
)
363 nodeSystemInfo
->AddAttribute(wxT("description"), wxGetOsDescription());
368 bool wxDebugReport::DoAddLoadedModules(wxXmlNode
*nodeModules
)
370 wxDynamicLibraryDetailsArray
modules(wxDynamicLibrary::ListLoaded());
371 const size_t count
= modules
.GetCount();
375 for ( size_t n
= 0; n
< count
; n
++ )
377 const wxDynamicLibraryDetails
& info
= modules
[n
];
379 wxXmlNode
*nodeModule
= new wxXmlNode(wxXML_ELEMENT_NODE
, wxT("module"));
380 nodeModules
->AddChild(nodeModule
);
382 wxString path
= info
.GetPath();
384 path
= info
.GetName();
386 nodeModule
->AddAttribute(wxT("path"), path
);
390 if ( info
.GetAddress(&addr
, &len
) )
392 HexProperty(nodeModule
, wxT("address"), wxPtrToUInt(addr
));
393 HexProperty(nodeModule
, wxT("size"), len
);
396 wxString ver
= info
.GetVersion();
399 nodeModule
->AddAttribute(wxT("version"), ver
);
406 bool wxDebugReport::DoAddExceptionInfo(wxXmlNode
*nodeContext
)
408 #if wxUSE_CRASHREPORT
413 wxXmlNode
*nodeExc
= new wxXmlNode(wxXML_ELEMENT_NODE
, wxT("exception"));
414 nodeContext
->AddChild(nodeExc
);
416 HexProperty(nodeExc
, wxT("code"), c
.code
);
417 nodeExc
->AddAttribute(wxT("name"), c
.GetExceptionString());
418 HexProperty(nodeExc
, wxT("address"), wxPtrToUInt(c
.addr
));
421 wxXmlNode
*nodeRegs
= new wxXmlNode(wxXML_ELEMENT_NODE
, wxT("registers"));
422 nodeContext
->AddChild(nodeRegs
);
423 HexElement(nodeRegs
, wxT("eax"), c
.regs
.eax
);
424 HexElement(nodeRegs
, wxT("ebx"), c
.regs
.ebx
);
425 HexElement(nodeRegs
, wxT("ecx"), c
.regs
.edx
);
426 HexElement(nodeRegs
, wxT("edx"), c
.regs
.edx
);
427 HexElement(nodeRegs
, wxT("esi"), c
.regs
.esi
);
428 HexElement(nodeRegs
, wxT("edi"), c
.regs
.edi
);
430 HexElement(nodeRegs
, wxT("ebp"), c
.regs
.ebp
);
431 HexElement(nodeRegs
, wxT("esp"), c
.regs
.esp
);
432 HexElement(nodeRegs
, wxT("eip"), c
.regs
.eip
);
434 HexElement(nodeRegs
, wxT("cs"), c
.regs
.cs
);
435 HexElement(nodeRegs
, wxT("ds"), c
.regs
.ds
);
436 HexElement(nodeRegs
, wxT("es"), c
.regs
.es
);
437 HexElement(nodeRegs
, wxT("fs"), c
.regs
.fs
);
438 HexElement(nodeRegs
, wxT("gs"), c
.regs
.gs
);
439 HexElement(nodeRegs
, wxT("ss"), c
.regs
.ss
);
441 HexElement(nodeRegs
, wxT("flags"), c
.regs
.flags
);
445 #else // !wxUSE_CRASHREPORT
446 wxUnusedVar(nodeContext
);
449 #endif // wxUSE_CRASHREPORT/!wxUSE_CRASHREPORT
452 bool wxDebugReport::AddContext(wxDebugReport::Context ctx
)
454 wxCHECK_MSG( IsOk(), false, wxT("use IsOk() first") );
456 // create XML dump of current context
457 wxXmlDocument xmldoc
;
458 wxXmlNode
*nodeRoot
= new wxXmlNode(wxXML_ELEMENT_NODE
, wxT("report"));
459 xmldoc
.SetRoot(nodeRoot
);
460 nodeRoot
->AddAttribute(wxT("version"), wxT("1.0"));
461 nodeRoot
->AddAttribute(wxT("kind"), ctx
== Context_Current
? wxT("user")
464 // add system information
465 wxXmlNode
*nodeSystemInfo
= new wxXmlNode(wxXML_ELEMENT_NODE
, wxT("system"));
466 if ( DoAddSystemInfo(nodeSystemInfo
) )
467 nodeRoot
->AddChild(nodeSystemInfo
);
469 delete nodeSystemInfo
;
471 // add information about the loaded modules
472 wxXmlNode
*nodeModules
= new wxXmlNode(wxXML_ELEMENT_NODE
, wxT("modules"));
473 if ( DoAddLoadedModules(nodeModules
) )
474 nodeRoot
->AddChild(nodeModules
);
478 // add CPU context information: this only makes sense for exceptions as our
479 // current context is not very interesting otherwise
480 if ( ctx
== Context_Exception
)
482 wxXmlNode
*nodeContext
= new wxXmlNode(wxXML_ELEMENT_NODE
, wxT("context"));
483 if ( DoAddExceptionInfo(nodeContext
) )
484 nodeRoot
->AddChild(nodeContext
);
489 // add stack traceback
490 #if wxUSE_STACKWALKER
491 wxXmlNode
*nodeStack
= new wxXmlNode(wxXML_ELEMENT_NODE
, wxT("stack"));
492 XmlStackWalker
sw(nodeStack
);
493 #if wxUSE_ON_FATAL_EXCEPTION
494 if ( ctx
== Context_Exception
)
496 sw
.WalkFromException();
498 else // Context_Current
499 #endif // wxUSE_ON_FATAL_EXCEPTION
505 nodeRoot
->AddChild(nodeStack
);
508 #endif // wxUSE_STACKWALKER
510 // finally let the user add any extra information he needs
511 DoAddCustomContext(nodeRoot
);
514 // save the entire context dump in a file
515 wxFileName
fn(m_dir
, GetReportName(), wxT("xml"));
517 if ( !xmldoc
.Save(fn
.GetFullPath()) )
520 AddFile(fn
.GetFullName(), _("process context description"));
525 #endif // wxUSE_STACKWALKER
527 // ----------------------------------------------------------------------------
529 // ----------------------------------------------------------------------------
531 #if wxUSE_CRASHREPORT
533 bool wxDebugReport::AddDump(Context ctx
)
535 wxCHECK_MSG( IsOk(), false, wxT("use IsOk() first") );
537 wxFileName
fn(m_dir
, GetReportName(), wxT("dmp"));
538 wxCrashReport::SetFileName(fn
.GetFullPath());
540 if ( !(ctx
== Context_Exception
? wxCrashReport::Generate()
541 : wxCrashReport::GenerateNow()) )
544 AddFile(fn
.GetFullName(), _("dump of the process state (binary)"));
549 #endif // wxUSE_CRASHREPORT
551 // ----------------------------------------------------------------------------
553 // ----------------------------------------------------------------------------
555 bool wxDebugReport::Process()
557 if ( !GetFilesCount() )
559 wxLogError(_("Debug report generation has failed."));
566 wxLogError(_("Processing debug report has failed, leaving the files in \"%s\" directory."),
567 GetDirectory().c_str());
577 bool wxDebugReport::DoProcess()
579 wxString
msg(_("A debug report has been generated. It can be found in"));
581 wxT("\t") << GetDirectory() << wxT("\n\n")
582 << _("And includes the following files:\n");
585 const size_t count
= GetFilesCount();
586 for ( size_t n
= 0; n
< count
; n
++ )
588 GetFile(n
, &name
, &desc
);
589 msg
+= wxString::Format("\t%s: %s\n", name
, desc
);
592 msg
+= _("\nPlease send this report to the program maintainer, thank you!\n");
594 wxLogMessage(wxT("%s"), msg
.c_str());
596 // we have to do this or the report would be deleted, and we don't even
597 // have any way to ask the user if he wants to keep it from here
603 // ============================================================================
604 // wxDebugReport-derived classes
605 // ============================================================================
609 // ----------------------------------------------------------------------------
610 // wxDebugReportCompress
611 // ----------------------------------------------------------------------------
613 void wxDebugReportCompress::SetCompressedFileDirectory(const wxString
& dir
)
615 wxASSERT_MSG( m_zipfile
.empty(), "Too late: call this before Process()" );
620 void wxDebugReportCompress::SetCompressedFileBaseName(const wxString
& name
)
622 wxASSERT_MSG( m_zipfile
.empty(), "Too late: call this before Process()" );
627 bool wxDebugReportCompress::DoProcess()
629 #define HAS_FILE_STREAMS (wxUSE_STREAMS && (wxUSE_FILE || wxUSE_FFILE))
631 const size_t count
= GetFilesCount();
635 // create the compressed report file outside of the directory with the
636 // report files as it will be deleted by wxDebugReport dtor but we want to
637 // keep this one: for this we simply treat the directory name as the name
638 // of the file so that its last component becomes our base name
639 wxFileName
fn(GetDirectory());
640 if ( !m_zipDir
.empty() )
641 fn
.SetPath(m_zipDir
);
642 if ( !m_zipName
.empty() )
643 fn
.SetName(m_zipName
);
646 // create the streams
647 const wxString ofullPath
= fn
.GetFullPath();
649 wxFFileOutputStream
os(ofullPath
, wxT("wb"));
651 wxFileOutputStream
os(ofullPath
);
655 wxZipOutputStream
zos(os
, 9);
657 // add all files to the ZIP one
659 for ( size_t n
= 0; n
< count
; n
++ )
661 GetFile(n
, &name
, &desc
);
663 wxZipEntry
*ze
= new wxZipEntry(name
);
664 ze
->SetComment(desc
);
666 if ( !zos
.PutNextEntry(ze
) )
669 const wxString ifullPath
= wxFileName(GetDirectory(), name
).GetFullPath();
671 wxFFileInputStream
is(ifullPath
);
673 wxFileInputStream
is(ifullPath
);
675 if ( !is
.IsOk() || !zos
.Write(is
).IsOk() )
682 m_zipfile
= ofullPath
;
687 #endif // HAS_FILE_STREAMS
690 // ----------------------------------------------------------------------------
691 // wxDebugReportUpload
692 // ----------------------------------------------------------------------------
694 wxDebugReportUpload::wxDebugReportUpload(const wxString
& url
,
695 const wxString
& input
,
696 const wxString
& action
,
697 const wxString
& curl
)
702 if ( m_uploadURL
.Last() != wxT('/') )
703 m_uploadURL
+= wxT('/');
704 m_uploadURL
+= action
;
707 bool wxDebugReportUpload::DoProcess()
709 if ( !wxDebugReportCompress::DoProcess() )
713 wxArrayString output
, errors
;
714 int rc
= wxExecute(wxString::Format
716 wxT("%s -F \"%s=@%s\" %s"),
718 m_inputField
.c_str(),
719 GetCompressedFileName().c_str(),
726 wxLogError(_("Failed to execute curl, please install it in PATH."));
730 const size_t count
= errors
.GetCount();
733 for ( size_t n
= 0; n
< count
; n
++ )
735 wxLogWarning(wxT("%s"), errors
[n
].c_str());
739 wxLogError(_("Failed to upload the debug report (error code %d)."), rc
);
743 if ( OnServerReply(output
) )
750 #endif // wxUSE_ZIPSTREAM
752 #endif // wxUSE_DEBUGREPORT