source: branches/eraser6/BlackBox/Eraser.Util/BlackBox.cs @ 1422

Revision 1422, 22.1 KB checked in by lowjoel, 5 years ago (diff)

Allow reports to be deleted. Also allow the Path to the report be discovered so users can navigate to the report contents.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
Line 
1/*
2 * $Id$
3 * Copyright 2008-2009 The Eraser Project
4 * Original Author: Joel Low <lowjoel@users.sourceforge.net>
5 * Modified By:
6 *
7 * This file is part of Eraser.
8 *
9 * Eraser is free software: you can redistribute it and/or modify it under the
10 * terms of the GNU General Public License as published by the Free Software
11 * Foundation, either version 3 of the License, or (at your option) any later
12 * version.
13 *
14 * Eraser is distributed in the hope that it will be useful, but WITHOUT ANY
15 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
17 *
18 * A copy of the GNU General Public License can be found at
19 * <http://www.gnu.org/licenses/>.
20 */
21
22using System;
23using System.Collections.Generic;
24using System.Text;
25using System.Windows.Forms;
26using System.IO;
27using System.Runtime.InteropServices;
28using Microsoft.Win32.SafeHandles;
29using System.Diagnostics;
30using System.Threading;
31using System.Drawing;
32using System.Drawing.Imaging;
33using System.Reflection;
34using System.Collections.ObjectModel;
35
36namespace Eraser.Util
37{
38    /// <summary>
39    /// Handles application exceptions, stores minidumps and uploads them to the
40    /// Eraser server.
41    /// </summary>
42    public class BlackBox
43    {
44        /// <summary>
45        /// Stores DLL references for this class.
46        /// </summary>
47        private static class NativeMethods
48        {
49            /// <summary>
50            /// Writes user-mode minidump information to the specified file.
51            /// </summary>
52            /// <param name="hProcess">A handle to the process for which the information
53            /// is to be generated.</param>
54            /// <param name="ProcessId">The identifier of the process for which the information
55            /// is to be generated.</param>
56            /// <param name="hFile">A handle to the file in which the information is to be
57            /// written.</param>
58            /// <param name="DumpType">The type of information to be generated. This parameter
59            /// can be one or more of the values from the MINIDUMP_TYPE enumeration.</param>
60            /// <param name="ExceptionParam">A pointer to a MiniDumpExceptionInfo structure
61            /// describing the client exception that caused the minidump to be generated.
62            /// If the value of this parameter is NULL, no exception information is included
63            /// in the minidump file.</param>
64            /// <param name="UserStreamParam">Not supported. Use IntPtr.Zero</param>
65            /// <param name="CallbackParam">Not supported. Use IntPtr.Zero</param>
66            /// <returns>If the function succeeds, the return value is true; otherwise, the
67            /// return value is false. To retrieve extended error information, call GetLastError.
68            /// Note that the last error will be an HRESULT value.</returns>
69            [DllImport("dbghelp.dll", SetLastError = true)]
70            [return: MarshalAs(UnmanagedType.Bool)]
71            public static extern bool MiniDumpWriteDump(IntPtr hProcess, uint ProcessId,
72                SafeFileHandle hFile, MiniDumpType DumpType,
73                ref MiniDumpExceptionInfo ExceptionParam, IntPtr UserStreamParam,
74                IntPtr CallbackParam);
75
76            /// <summary>
77            /// Identifies the type of information that will be written to the minidump file
78            /// by the MiniDumpWriteDump function.
79            /// </summary>
80            public enum MiniDumpType
81            {
82                /// <summary>
83                /// Include just the information necessary to capture stack traces for all
84                /// existing threads in a process.
85                /// </summary>
86                MiniDumpNormal = 0x00000000,
87
88                /// <summary>
89                /// Include the data sections from all loaded modules. This results in the
90                /// inclusion of global variables, which can make the minidump file significantly
91                /// larger. For per-module control, use the ModuleWriteDataSeg enumeration
92                /// value from MODULE_WRITE_FLAGS.
93                /// </summary>
94                MiniDumpWithDataSegs = 0x00000001,
95
96                /// <summary>
97                /// Include all accessible memory in the process. The raw memory data is
98                /// included at the end, so that the initial structures can be mapped directly
99                /// without the raw memory information. This option can result in a very large
100                /// file.
101                /// </summary>
102                MiniDumpWithFullMemory = 0x00000002,
103
104                /// <summary>
105                /// Include high-level information about the operating system handles that are
106                /// active when the minidump is made.
107                /// </summary>
108                MiniDumpWithHandleData = 0x00000004,
109
110                /// <summary>
111                /// Stack and backing store memory written to the minidump file should be
112                /// filtered to remove all but the pointer values necessary to reconstruct a
113                /// stack trace. Typically, this removes any private information.
114                /// </summary>
115                MiniDumpFilterMemory = 0x00000008,
116
117                /// <summary>
118                /// Stack and backing store memory should be scanned for pointer references
119                /// to modules in the module list. If a module is referenced by stack or backing
120                /// store memory, the ModuleWriteFlags member of the MINIDUMP_CALLBACK_OUTPUT
121                /// structure is set to ModuleReferencedByMemory.
122                /// </summary>
123                MiniDumpScanMemory = 0x00000010,
124
125                /// <summary>
126                /// Include information from the list of modules that were recently unloaded,
127                /// if this information is maintained by the operating system.
128                /// </summary>
129                MiniDumpWithUnloadedModules = 0x00000020,
130
131                /// <summary>
132                /// Include pages with data referenced by locals or other stack memory.
133                /// This option can increase the size of the minidump file significantly.
134                /// </summary>
135                MiniDumpWithIndirectlyReferencedMemory = 0x00000040,
136
137                /// <summary>
138                /// Filter module paths for information such as user names or important
139                /// directories. This option may prevent the system from locating the image
140                /// file and should be used only in special situations.
141                /// </summary>
142                MiniDumpFilterModulePaths = 0x00000080,
143
144                /// <summary>
145                /// Include complete per-process and per-thread information from the operating
146                /// system.
147                /// </summary>
148                MiniDumpWithProcessThreadData = 0x00000100,
149
150                /// <summary>
151                /// Scan the virtual address space for PAGE_READWRITE memory to be included.
152                /// </summary>
153                MiniDumpWithPrivateReadWriteMemory = 0x00000200,
154
155                /// <summary>
156                /// Reduce the data that is dumped by eliminating memory regions that are not
157                /// essential to meet criteria specified for the dump. This can avoid dumping
158                /// memory that may contain data that is private to the user. However, it is
159                /// not a guarantee that no private information will be present.
160                /// </summary>
161                MiniDumpWithoutOptionalData = 0x00000400,
162
163                /// <summary>
164                /// Include memory region information. For more information, see
165                /// MINIDUMP_MEMORY_INFO_LIST.
166                /// </summary>
167                MiniDumpWithFullMemoryInfo = 0x00000800,
168
169                /// <summary>
170                /// Include thread state information. For more information, see
171                /// MINIDUMP_THREAD_INFO_LIST.
172                /// </summary>
173                MiniDumpWithThreadInfo = 0x00001000,
174
175                /// <summary>
176                /// Include all code and code-related sections from loaded modules to capture
177                /// executable content. For per-module control, use the ModuleWriteCodeSegs
178                /// enumeration value from MODULE_WRITE_FLAGS.
179                /// </summary>
180                MiniDumpWithCodeSegs = 0x00002000,
181
182                /// <summary>
183                /// Turns off secondary auxiliary-supported memory gathering.
184                /// </summary>
185                MiniDumpWithoutAuxiliaryState = 0x00004000,
186
187                /// <summary>
188                /// Requests that auxiliary data providers include their state in the dump
189                /// image; the state data that is included is provider dependent. This option
190                /// can result in a large dump image.
191                /// </summary>
192                MiniDumpWithFullAuxiliaryState = 0x00008000,
193
194                /// <summary>
195                /// Scans the virtual address space for PAGE_WRITECOPY memory to be included.
196                /// </summary>
197                MiniDumpWithPrivateWriteCopyMemory = 0x00010000,
198
199                /// <summary>
200                /// If you specify MiniDumpWithFullMemory, the MiniDumpWriteDump function will
201                /// fail if the function cannot read the memory regions; however, if you include
202                /// MiniDumpIgnoreInaccessibleMemory, the MiniDumpWriteDump function will
203                /// ignore the memory read failures and continue to generate the dump. Note that
204                /// the inaccessible memory regions are not included in the dump.
205                /// </summary>
206                MiniDumpIgnoreInaccessibleMemory = 0x00020000,
207
208                /// <summary>
209                /// Adds security token related data. This will make the "!token" extension work
210                /// when processing a user-mode dump.
211                /// </summary>
212                MiniDumpWithTokenInformation = 0x00040000
213            }
214
215            /// <summary>
216            /// Contains the exception information written to the minidump file by the
217            /// MiniDumpWriteDump function.
218            /// </summary>
219            [StructLayout(LayoutKind.Sequential, Pack = 4)]
220            public struct MiniDumpExceptionInfo
221            {
222                /// <summary>
223                /// The identifier of the thread throwing the exception.
224                /// </summary>
225                public uint ThreadId;
226
227                /// <summary>
228                ///  A pointer to an EXCEPTION_POINTERS structure specifying a
229                ///  computer-independent description of the exception and the processor
230                ///  context at the time of the exception.
231                /// </summary>
232                public IntPtr ExceptionPointers;
233
234                /// <summary>
235                /// Determines where to get the memory regions pointed to by the
236                /// ExceptionPointers member. Set to TRUE if the memory resides in the
237                /// process being debugged (the target process of the debugger). Otherwise,
238                /// set to FALSE if the memory resides in the address space of the calling
239                /// program (the debugger process). If you are accessing local memory (in
240                /// the calling process) you should not set this member to TRUE.
241                /// </summary>
242                [MarshalAs(UnmanagedType.Bool)]
243                public bool ClientPointers;
244            }
245        }
246
247        /// <summary>
248        /// Initialises the BlackBox handler. Call this initialiser once throughout
249        /// the lifespan of the application.
250        /// </summary>
251        /// <returns>The global BlackBox instance.</returns>
252        public static BlackBox Get()
253        {
254            if (Instance == null)
255                Instance = new BlackBox();
256            return Instance;
257        }
258
259        /// <summary>
260        /// Enumerates the list of crash dumps waiting for upload.
261        /// </summary>
262        /// <returns>A string array containing the list of dumps waiting for upload.</returns>
263        public BlackBoxReport[] GetDumps()
264        {
265            DirectoryInfo dirInfo = new DirectoryInfo(CrashReportsPath);
266            List<BlackBoxReport> result = new List<BlackBoxReport>();
267            foreach (DirectoryInfo subDir in dirInfo.GetDirectories())
268                result.Add(new BlackBoxReport(Path.Combine(CrashReportsPath, subDir.Name)));
269
270            return result.ToArray();
271        }
272
273        /// <summary>
274        /// Constructor. Use the <see cref="Initialise"/> function to use this class.
275        /// </summary>
276        private BlackBox()
277        {
278            AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
279            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
280            Application.Idle += OnApplicationIdle;
281        }
282
283        /// <summary>
284        /// Called when the application has reached the idle state. This is used to
285        /// process and upload crash reports to the Eraser server.
286        /// </summary>
287        private void OnApplicationIdle(object sender, EventArgs e)
288        {
289            Application.Idle -= OnApplicationIdle;
290        }
291
292        /// <summary>
293        /// Called when an unhandled exception is raised in the application.
294        /// </summary>
295        private void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
296        {
297            //Generate a unique identifier for this report.
298            string crashName = DateTime.Now.ToString();
299            crashName = crashName.Replace('/', '-').Replace(":", "");
300            string currentCrashReport = Path.Combine(CrashReportsPath, crashName);
301            Directory.CreateDirectory(currentCrashReport);
302
303            //Write a memory dump to the folder
304            Exception exception = (e.ExceptionObject as Exception);
305            WriteMemoryDump(currentCrashReport, exception);
306
307            //Then write a user-readable summary
308            WriteDebugLog(currentCrashReport, exception);
309
310            //Take a screenshot
311            WriteScreenshot(currentCrashReport);
312        }
313
314        /// <summary>
315        /// Dumps the contents of memory to a dumpfile.
316        /// </summary>
317        /// <param name="dumpFolder">Path to the folder to store the dump file.</param>
318        /// <param name="e">The exception which is being handled.</param>
319        private void WriteMemoryDump(string dumpFolder, Exception e)
320        {
321            //Open a file stream
322            using (FileStream stream = new FileStream(Path.Combine(dumpFolder, MemoryDumpFileName),
323                FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
324            {
325                //Store the exception information
326                NativeMethods.MiniDumpExceptionInfo exception =
327                    new NativeMethods.MiniDumpExceptionInfo();
328                exception.ClientPointers = false;
329                exception.ExceptionPointers = Marshal.GetExceptionPointers();
330                exception.ThreadId = (uint)AppDomain.GetCurrentThreadId();
331
332                NativeMethods.MiniDumpWriteDump(Process.GetCurrentProcess().Handle,
333                    (uint)Process.GetCurrentProcess().Id, stream.SafeFileHandle,
334                    NativeMethods.MiniDumpType.MiniDumpWithFullMemory,
335                    ref exception, IntPtr.Zero, IntPtr.Zero);
336            }
337        }
338
339        /// <summary>
340        /// Writes a debug log to the given directory.
341        /// </summary>
342        /// <param name="screenshotPath">The path to store the screenshot into.</param>
343        /// <param name="exception">The exception to log about.</param>
344        private void WriteDebugLog(string dumpFolder, Exception exception)
345        {
346            using (FileStream file = new FileStream(Path.Combine(dumpFolder, DebugLogFileName),
347                FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
348            using (StreamWriter stream = new StreamWriter(file))
349            {
350                //Application information
351                string separator = new string('-', 76);
352                string lineFormat = "{0,15}: {1}";
353                stream.WriteLine("Application Information");
354                stream.WriteLine(separator);
355                stream.WriteLine(string.Format(lineFormat, "Version",
356                    Assembly.GetEntryAssembly().GetName().Version));
357                StringBuilder commandLine = new StringBuilder();
358                foreach (string param in Environment.GetCommandLineArgs())
359                {
360                    commandLine.Append(param);
361                    commandLine.Append(' ');
362                }
363                stream.WriteLine(string.Format(lineFormat, "Command Line",
364                    commandLine.ToString().Trim()));
365
366                //Exception Information
367                stream.WriteLine();
368                stream.WriteLine("Exception Information (Outermost to innermost)");
369                stream.WriteLine(separator);
370
371                //Open a stream to the Stack Trace Log file. We want to separate the stack
372                //trace do we can check against the server to see if the crash is a new one
373                using (StreamWriter stackTraceLog = new StreamWriter(
374                    Path.Combine(dumpFolder, StackTraceFileName)))
375                {
376                    Exception currentException = exception;
377                    for (uint i = 1; currentException != null; ++i)
378                    {
379                        stream.WriteLine(string.Format("Exception {0}:", i));
380                        stream.WriteLine(string.Format(lineFormat, "Message", currentException.Message));
381                        stream.WriteLine(string.Format(lineFormat, "Exception Type",
382                            currentException.GetType().Name));
383                        stackTraceLog.WriteLine(string.Format("Exception {0}: {1}", i,
384                            currentException.GetType().Name));
385
386                        //Parse the stack trace
387                        string[] stackTrace = currentException.StackTrace.Split(new char[] { '\n' });
388                        for (uint j = 0; j < stackTrace.Length; ++j)
389                        {
390                            stream.WriteLine(string.Format(lineFormat,
391                                string.Format("Stack Trace [{0}]", j), stackTrace[j].Trim()));
392                            stackTraceLog.WriteLine(string.Format("{0}", stackTrace[j].Trim()));
393                        }
394
395                        uint k = 0;
396                        foreach (System.Collections.DictionaryEntry value in currentException.Data)
397                            stream.WriteLine(string.Format(lineFormat, string.Format("Data[{0}]", ++k),
398                                string.Format("{0} {1}", value.Key.ToString(), value.Value.ToString())));
399
400                        //End the exception and get the inner exception.
401                        stream.WriteLine();
402                        currentException = exception.InnerException;
403                    }
404                }
405            }
406        }
407
408        /// <summary>
409        /// Writes a screenshot to the given directory
410        /// </summary>
411        /// <param name="dumpFolder">The path to save the screenshot to.</param>
412        private void WriteScreenshot(string dumpFolder)
413        {
414            //Get the size of the screen
415            Rectangle rect = new Rectangle(int.MaxValue, int.MaxValue, int.MinValue, int.MinValue);
416            foreach (Screen screen in Screen.AllScreens)
417                rect = Rectangle.Union(rect, screen.Bounds);
418
419            //Copy a screen DC to the screenshot bitmap
420            Bitmap screenShot = new Bitmap(rect.Width, rect.Height);
421            Graphics bitmap = Graphics.FromImage(screenShot);
422            bitmap.CopyFromScreen(0, 0, 0, 0, rect.Size, CopyPixelOperation.SourceCopy);
423
424            //Save the bitmap to disk
425            screenShot.Save(Path.Combine(dumpFolder, ScreenshotFileName), ImageFormat.Png);
426        }
427
428        /// <summary>
429        /// The global BlackBox instance.
430        /// </summary>
431        private static BlackBox Instance;
432
433        /// <summary>
434        /// The path to all Eraser crash reports.
435        /// </summary>
436        private static readonly string CrashReportsPath = Path.Combine(Environment.GetFolderPath(
437            Environment.SpecialFolder.LocalApplicationData), @"Eraser 6\Crash Reports");
438
439        /// <summary>
440        /// The file name of the memory dump.
441        /// </summary>
442        ///
443        internal static readonly string MemoryDumpFileName = "Memory.dmp";
444
445        /// <summary>
446        /// The file name of the debug log.
447        /// </summary>
448        internal static readonly string DebugLogFileName = "Debug.log";
449
450        /// <summary>
451        /// The file name of the screenshot.
452        /// </summary>
453        internal static readonly string ScreenshotFileName = "Screenshot.png";
454
455        /// <summary>
456        /// The file name of the stack trace.
457        /// </summary>
458        internal static readonly string StackTraceFileName = "Stack Trace.log";
459    }
460
461    /// <summary>
462    /// Represents one BlackBox crash report.
463    /// </summary>
464    public class BlackBoxReport
465    {
466        /// <summary>
467        /// Constructor.
468        /// </summary>
469        /// <param name="path">Path to the folder containing the memory dump, screenshot and
470        /// debug log.</param>
471        internal BlackBoxReport(string path)
472        {
473            Path = path;
474
475            string[] stackTrace = null;
476            using (StreamReader reader = new StreamReader(
477                System.IO.Path.Combine(Path, BlackBox.StackTraceFileName)))
478            {
479                stackTrace = reader.ReadToEnd().Split(new char[] { '\n' });
480            }
481
482            //Parse the lines in the file.
483            StackTraceCache = new List<BlackBoxExceptionEntry>();
484            List<string> currentException = new List<string>();
485            string exceptionType = null;
486            foreach (string str in stackTrace)
487            {
488                if (str.StartsWith("Exception "))
489                {
490                    //Add the current exception to the list of exceptions.
491                    if (currentException.Count != 0)
492                    {
493                        StackTraceCache.Add(new BlackBoxExceptionEntry(exceptionType,
494                            new List<string>(currentException)));
495                        currentException.Clear();
496                    }
497
498                    //Set the exception type for the next exception.
499                    exceptionType = str.Substring(str.IndexOf(':') + 1).Trim();
500                }
501                else if (!string.IsNullOrEmpty(str.Trim()))
502                {
503                    currentException.Add(str.Trim());
504                }
505            }
506
507            if (currentException.Count != 0)
508                StackTraceCache.Add(new BlackBoxExceptionEntry(exceptionType, currentException));
509        }
510
511        /// <summary>
512        /// Deletes the report and its contents.
513        /// </summary>
514        public void Delete()
515        {
516            Directory.Delete(Path, true);
517        }
518
519        /// <summary>
520        /// The name of the report.
521        /// </summary>
522        public string Name
523        {
524            get
525            {
526                return System.IO.Path.GetFileName(Path);
527            }
528        }
529
530        /// <summary>
531        /// The path to the folder containing the report.
532        /// </summary>
533        public string Path
534        {
535            get;
536            private set;
537        }
538
539        /// <summary>
540        /// The files which comprise the error report.
541        /// </summary>
542        public ReadOnlyCollection<FileInfo> Files
543        {
544            get
545            {
546                List<FileInfo> result = new List<FileInfo>();
547                DirectoryInfo directory = new DirectoryInfo(Path);
548                foreach (FileInfo file in directory.GetFiles())
549                    if (!InternalFiles.Contains(file.Name))
550                        result.Add(file);
551
552                return result.AsReadOnly();
553            }
554        }
555
556        /// <summary>
557        /// Gets a read-only stream which reads the Debug log.
558        /// </summary>
559        public Stream DebugLog
560        {
561            get
562            {
563                return new FileStream(System.IO.Path.Combine(Path, BlackBox.DebugLogFileName),
564                    FileMode.Open, FileAccess.Read);
565            }
566        }
567
568        /// <summary>
569        /// Gets the stack trace for this crash report.
570        /// </summary>
571        public ReadOnlyCollection<BlackBoxExceptionEntry> StackTrace
572        {
573            get
574            {
575                return StackTraceCache.AsReadOnly();
576            }
577        }
578
579        /// <summary>
580        /// Gets or sets whether the given report has been uploaded to the server.
581        /// </summary>
582        public bool Submitted
583        {
584            get
585            {
586                byte[] buffer = new byte[1];
587                using (FileStream stream = new FileStream(System.IO.Path.Combine(Path, StatusFileName),
588                    FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read))
589                {
590                    stream.Read(buffer, 0, buffer.Length);
591                }
592
593                return buffer[0] == 1;
594            }
595
596            set
597            {
598                byte[] buffer = { Convert.ToByte(value) };
599                using (FileStream stream = new FileStream(System.IO.Path.Combine(Path, StatusFileName),
600                    FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read))
601                {
602                    stream.Write(buffer, 0, buffer.Length);
603                }
604            }
605        }
606
607        public override string ToString()
608        {
609            return Name;
610        }
611
612        /// <summary>
613        /// The backing variable for the <see cref="StackTrace"/> field.
614        /// </summary>
615        private List<BlackBoxExceptionEntry> StackTraceCache;
616
617        /// <summary>
618        /// The file name for the status file.
619        /// </summary>
620        private static readonly string StatusFileName = "Status.txt";
621
622        /// <summary>
623        /// The list of files internal to the report.
624        /// </summary>
625        private static readonly List<string> InternalFiles = new List<string>(
626            new string[] {
627                 BlackBox.StackTraceFileName,
628                 "Status.txt"
629            }
630        );
631    }
632
633    /// <summary>
634    /// Represents one exception which can be chained <see cref="InnerException"/>
635    /// to represent the exception handled by BlackBox
636    /// </summary>
637    public class BlackBoxExceptionEntry
638    {
639        /// <summary>
640        /// Constructor.
641        /// </summary>
642        /// <param name="exceptionType">The type of the exception.</param>
643        /// <param name="stackTrace">The stack trace for this exception.</param>
644        internal BlackBoxExceptionEntry(string exceptionType, List<string> stackTrace)
645        {
646            ExceptionType = exceptionType;
647            StackTraceCache = stackTrace;
648        }
649
650        /// <summary>
651        /// The type of the exception.
652        /// </summary>
653        public string ExceptionType
654        {
655            get;
656            private set;
657        }
658
659        /// <summary>
660        /// The stack trace for this exception.
661        /// </summary>
662        public ReadOnlyCollection<string> StackTrace
663        {
664            get
665            {
666                return StackTraceCache.AsReadOnly();
667            }
668        }
669
670        /// <summary>
671        /// The backing variable for the <see cref="StackTrace"/> property.
672        /// </summary>
673        private List<string> StackTraceCache;
674    }
675}
Note: See TracBrowser for help on using the repository browser.