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

Revision 1427, 21.8 KB checked in by lowjoel, 5 years ago (diff)

Don't enumerate the directories if the Crash Reports folder does not exist.

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