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

Revision 1390, 17.0 KB checked in by lowjoel, 5 years ago (diff)

Added the BlackBoxReport? class that encapsulates a crash report.

  • 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, "Memory.dmp"),
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, "Debug.log"),
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                Exception currentException = exception;
372                for (uint i = 1; currentException != null; ++i)
373                {
374                    stream.WriteLine(string.Format("Exception {0}:", i));
375                    stream.WriteLine(string.Format(lineFormat, "Message", currentException.Message));
376                    stream.WriteLine(string.Format(lineFormat, "Exception Type",
377                        currentException.GetType().Name));
378
379                    //Parse the stack trace
380                    string[] stackTrace = currentException.StackTrace.Split(new char[] { '\n' });
381                    for (uint j = 0; j < stackTrace.Length; ++j)
382                        stream.WriteLine(string.Format(lineFormat,
383                            string.Format("Stack Trace [{0}]", j), stackTrace[j].Trim()));
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        /// <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, "Screenshot.png"), 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 readonly string CrashReportsPath = Path.Combine(Environment.GetFolderPath(
426            Environment.SpecialFolder.LocalApplicationData), @"Eraser 6\Crash Reports");
427    }
428
429    /// <summary>
430    /// Represents one BlackBox crash report.
431    /// </summary>
432    public class BlackBoxReport
433    {
434        /// <summary>
435        /// Constructor.
436        /// </summary>
437        /// <param name="path">Path to the folder containing the memory dump, screenshot and
438        /// debug log.</param>
439        internal BlackBoxReport(string path)
440        {
441            Path = path;
442        }
443
444        /// <summary>
445        /// The name of the report.
446        /// </summary>
447        public string Name
448        {
449            get
450            {
451                return System.IO.Path.GetFileName(Path);
452            }
453        }
454
455        /// <summary>
456        /// The files which comprise the error report.
457        /// </summary>
458        public ICollection<FileInfo> Files
459        {
460            get
461            {
462                List<FileInfo> result = new List<FileInfo>();
463                DirectoryInfo directory = new DirectoryInfo(Path);
464                result.AddRange(directory.GetFiles());
465                return result.AsReadOnly();
466            }
467        }
468
469        public override string ToString()
470        {
471            return Name;
472        }
473
474        /// <summary>
475        /// The path to the folder containing the report.
476        /// </summary>
477        private string Path;
478    }
479}
Note: See TracBrowser for help on using the repository browser.