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

Revision 1426, 21.7 KB checked in by lowjoel, 5 years ago (diff)

-Removed the Idle event handler since that should be the GUI's job.
-Record the fully qualified type name of the exception in our logs.

  • 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        }
281
282        /// <summary>
283        /// Called when an unhandled exception is raised in the application.
284        /// </summary>
285        private void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
286        {
287            //Generate a unique identifier for this report.
288            string crashName = DateTime.Now.ToString("yyyyMMdd HHmmss.FFF");
289            string currentCrashReport = Path.Combine(CrashReportsPath, crashName);
290            Directory.CreateDirectory(currentCrashReport);
291
292            //Write a memory dump to the folder
293            Exception exception = (e.ExceptionObject as Exception);
294            WriteMemoryDump(currentCrashReport, exception);
295
296            //Then write a user-readable summary
297            WriteDebugLog(currentCrashReport, exception);
298
299            //Take a screenshot
300            WriteScreenshot(currentCrashReport);
301        }
302
303        /// <summary>
304        /// Dumps the contents of memory to a dumpfile.
305        /// </summary>
306        /// <param name="dumpFolder">Path to the folder to store the dump file.</param>
307        /// <param name="e">The exception which is being handled.</param>
308        private void WriteMemoryDump(string dumpFolder, Exception e)
309        {
310            //Open a file stream
311            using (FileStream stream = new FileStream(Path.Combine(dumpFolder, MemoryDumpFileName),
312                FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
313            {
314                //Store the exception information
315                NativeMethods.MiniDumpExceptionInfo exception =
316                    new NativeMethods.MiniDumpExceptionInfo();
317                exception.ClientPointers = false;
318                exception.ExceptionPointers = Marshal.GetExceptionPointers();
319                exception.ThreadId = (uint)AppDomain.GetCurrentThreadId();
320
321                NativeMethods.MiniDumpWriteDump(Process.GetCurrentProcess().Handle,
322                    (uint)Process.GetCurrentProcess().Id, stream.SafeFileHandle,
323                    NativeMethods.MiniDumpType.MiniDumpWithFullMemory,
324                    ref exception, IntPtr.Zero, IntPtr.Zero);
325            }
326        }
327
328        /// <summary>
329        /// Writes a debug log to the given directory.
330        /// </summary>
331        /// <param name="screenshotPath">The path to store the screenshot into.</param>
332        /// <param name="exception">The exception to log about.</param>
333        private void WriteDebugLog(string dumpFolder, Exception exception)
334        {
335            using (FileStream file = new FileStream(Path.Combine(dumpFolder, DebugLogFileName),
336                FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
337            using (StreamWriter stream = new StreamWriter(file))
338            {
339                //Application information
340                string separator = new string('-', 76);
341                string lineFormat = "{0,15}: {1}";
342                stream.WriteLine("Application Information");
343                stream.WriteLine(separator);
344                stream.WriteLine(string.Format(lineFormat, "Version",
345                    Assembly.GetEntryAssembly().GetName().Version));
346                StringBuilder commandLine = new StringBuilder();
347                foreach (string param in Environment.GetCommandLineArgs())
348                {
349                    commandLine.Append(param);
350                    commandLine.Append(' ');
351                }
352                stream.WriteLine(string.Format(lineFormat, "Command Line",
353                    commandLine.ToString().Trim()));
354
355                //Exception Information
356                stream.WriteLine();
357                stream.WriteLine("Exception Information (Outermost to innermost)");
358                stream.WriteLine(separator);
359
360                //Open a stream to the Stack Trace Log file. We want to separate the stack
361                //trace do we can check against the server to see if the crash is a new one
362                using (StreamWriter stackTraceLog = new StreamWriter(
363                    Path.Combine(dumpFolder, StackTraceFileName)))
364                {
365                    Exception currentException = exception;
366                    for (uint i = 1; currentException != null; ++i)
367                    {
368                        stream.WriteLine(string.Format("Exception {0}:", i));
369                        stream.WriteLine(string.Format(lineFormat, "Message", currentException.Message));
370                        stream.WriteLine(string.Format(lineFormat, "Exception Type",
371                            currentException.GetType().FullName));
372                        stackTraceLog.WriteLine(string.Format("Exception {0}: {1}", i,
373                            currentException.GetType().FullName));
374
375                        //Parse the stack trace
376                        string[] stackTrace = currentException.StackTrace.Split(new char[] { '\n' });
377                        for (uint j = 0; j < stackTrace.Length; ++j)
378                        {
379                            stream.WriteLine(string.Format(lineFormat,
380                                string.Format("Stack Trace [{0}]", j), stackTrace[j].Trim()));
381                            stackTraceLog.WriteLine(string.Format("{0}", stackTrace[j].Trim()));
382                        }
383
384                        uint k = 0;
385                        foreach (System.Collections.DictionaryEntry value in currentException.Data)
386                            stream.WriteLine(string.Format(lineFormat, string.Format("Data[{0}]", ++k),
387                                string.Format("{0} {1}", value.Key.ToString(), value.Value.ToString())));
388
389                        //End the exception and get the inner exception.
390                        stream.WriteLine();
391                        currentException = exception.InnerException;
392                    }
393                }
394            }
395        }
396
397        /// <summary>
398        /// Writes a screenshot to the given directory
399        /// </summary>
400        /// <param name="dumpFolder">The path to save the screenshot to.</param>
401        private void WriteScreenshot(string dumpFolder)
402        {
403            //Get the size of the screen
404            Rectangle rect = new Rectangle(int.MaxValue, int.MaxValue, int.MinValue, int.MinValue);
405            foreach (Screen screen in Screen.AllScreens)
406                rect = Rectangle.Union(rect, screen.Bounds);
407
408            //Copy a screen DC to the screenshot bitmap
409            Bitmap screenShot = new Bitmap(rect.Width, rect.Height);
410            Graphics bitmap = Graphics.FromImage(screenShot);
411            bitmap.CopyFromScreen(0, 0, 0, 0, rect.Size, CopyPixelOperation.SourceCopy);
412
413            //Save the bitmap to disk
414            screenShot.Save(Path.Combine(dumpFolder, ScreenshotFileName), ImageFormat.Png);
415        }
416
417        /// <summary>
418        /// The global BlackBox instance.
419        /// </summary>
420        private static BlackBox Instance;
421
422        /// <summary>
423        /// The path to all Eraser crash reports.
424        /// </summary>
425        private static readonly string CrashReportsPath = Path.Combine(Environment.GetFolderPath(
426            Environment.SpecialFolder.LocalApplicationData), @"Eraser 6\Crash Reports");
427
428        /// <summary>
429        /// The file name of the memory dump.
430        /// </summary>
431        ///
432        internal static readonly string MemoryDumpFileName = "Memory.dmp";
433
434        /// <summary>
435        /// The file name of the debug log.
436        /// </summary>
437        internal static readonly string DebugLogFileName = "Debug.log";
438
439        /// <summary>
440        /// The file name of the screenshot.
441        /// </summary>
442        internal static readonly string ScreenshotFileName = "Screenshot.png";
443
444        /// <summary>
445        /// The file name of the stack trace.
446        /// </summary>
447        internal static readonly string StackTraceFileName = "Stack Trace.log";
448    }
449
450    /// <summary>
451    /// Represents one BlackBox crash report.
452    /// </summary>
453    public class BlackBoxReport
454    {
455        /// <summary>
456        /// Constructor.
457        /// </summary>
458        /// <param name="path">Path to the folder containing the memory dump, screenshot and
459        /// debug log.</param>
460        internal BlackBoxReport(string path)
461        {
462            Path = path;
463
464            string[] stackTrace = null;
465            using (StreamReader reader = new StreamReader(
466                System.IO.Path.Combine(Path, BlackBox.StackTraceFileName)))
467            {
468                stackTrace = reader.ReadToEnd().Split(new char[] { '\n' });
469            }
470
471            //Parse the lines in the file.
472            StackTraceCache = new List<BlackBoxExceptionEntry>();
473            List<string> currentException = new List<string>();
474            string exceptionType = null;
475            foreach (string str in stackTrace)
476            {
477                if (str.StartsWith("Exception "))
478                {
479                    //Add the current exception to the list of exceptions.
480                    if (currentException.Count != 0)
481                    {
482                        StackTraceCache.Add(new BlackBoxExceptionEntry(exceptionType,
483                            new List<string>(currentException)));
484                        currentException.Clear();
485                    }
486
487                    //Set the exception type for the next exception.
488                    exceptionType = str.Substring(str.IndexOf(':') + 1).Trim();
489                }
490                else if (!string.IsNullOrEmpty(str.Trim()))
491                {
492                    currentException.Add(str.Trim());
493                }
494            }
495
496            if (currentException.Count != 0)
497                StackTraceCache.Add(new BlackBoxExceptionEntry(exceptionType, currentException));
498        }
499
500        /// <summary>
501        /// Deletes the report and its contents.
502        /// </summary>
503        public void Delete()
504        {
505            Directory.Delete(Path, true);
506        }
507
508        /// <summary>
509        /// The name of the report.
510        /// </summary>
511        public string Name
512        {
513            get
514            {
515                return System.IO.Path.GetFileName(Path);
516            }
517        }
518
519        /// <summary>
520        /// The path to the folder containing the report.
521        /// </summary>
522        public string Path
523        {
524            get;
525            private set;
526        }
527
528        /// <summary>
529        /// The files which comprise the error report.
530        /// </summary>
531        public ReadOnlyCollection<FileInfo> Files
532        {
533            get
534            {
535                List<FileInfo> result = new List<FileInfo>();
536                DirectoryInfo directory = new DirectoryInfo(Path);
537                foreach (FileInfo file in directory.GetFiles())
538                    if (!InternalFiles.Contains(file.Name))
539                        result.Add(file);
540
541                return result.AsReadOnly();
542            }
543        }
544
545        /// <summary>
546        /// Gets a read-only stream which reads the Debug log.
547        /// </summary>
548        public Stream DebugLog
549        {
550            get
551            {
552                return new FileStream(System.IO.Path.Combine(Path, BlackBox.DebugLogFileName),
553                    FileMode.Open, FileAccess.Read);
554            }
555        }
556
557        /// <summary>
558        /// Gets the stack trace for this crash report.
559        /// </summary>
560        public ReadOnlyCollection<BlackBoxExceptionEntry> StackTrace
561        {
562            get
563            {
564                return StackTraceCache.AsReadOnly();
565            }
566        }
567
568        /// <summary>
569        /// Gets or sets whether the given report has been uploaded to the server.
570        /// </summary>
571        public bool Submitted
572        {
573            get
574            {
575                byte[] buffer = new byte[1];
576                using (FileStream stream = new FileStream(System.IO.Path.Combine(Path, StatusFileName),
577                    FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read))
578                {
579                    stream.Read(buffer, 0, buffer.Length);
580                }
581
582                return buffer[0] == 1;
583            }
584
585            set
586            {
587                byte[] buffer = { Convert.ToByte(value) };
588                using (FileStream stream = new FileStream(System.IO.Path.Combine(Path, StatusFileName),
589                    FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read))
590                {
591                    stream.Write(buffer, 0, buffer.Length);
592                }
593            }
594        }
595
596        public override string ToString()
597        {
598            return Name;
599        }
600
601        /// <summary>
602        /// The backing variable for the <see cref="StackTrace"/> field.
603        /// </summary>
604        private List<BlackBoxExceptionEntry> StackTraceCache;
605
606        /// <summary>
607        /// The file name for the status file.
608        /// </summary>
609        private static readonly string StatusFileName = "Status.txt";
610
611        /// <summary>
612        /// The list of files internal to the report.
613        /// </summary>
614        private static readonly List<string> InternalFiles = new List<string>(
615            new string[] {
616                 BlackBox.StackTraceFileName,
617                 "Status.txt"
618            }
619        );
620    }
621
622    /// <summary>
623    /// Represents one exception which can be chained <see cref="InnerException"/>
624    /// to represent the exception handled by BlackBox
625    /// </summary>
626    public class BlackBoxExceptionEntry
627    {
628        /// <summary>
629        /// Constructor.
630        /// </summary>
631        /// <param name="exceptionType">The type of the exception.</param>
632        /// <param name="stackTrace">The stack trace for this exception.</param>
633        internal BlackBoxExceptionEntry(string exceptionType, List<string> stackTrace)
634        {
635            ExceptionType = exceptionType;
636            StackTraceCache = stackTrace;
637        }
638
639        /// <summary>
640        /// The type of the exception.
641        /// </summary>
642        public string ExceptionType
643        {
644            get;
645            private set;
646        }
647
648        /// <summary>
649        /// The stack trace for this exception.
650        /// </summary>
651        public ReadOnlyCollection<string> StackTrace
652        {
653            get
654            {
655                return StackTraceCache.AsReadOnly();
656            }
657        }
658
659        /// <summary>
660        /// The backing variable for the <see cref="StackTrace"/> property.
661        /// </summary>
662        private List<string> StackTraceCache;
663    }
664}
Note: See TracBrowser for help on using the repository browser.