Exemple #1
0
        public void Dump(DumpType dumpType, object dumpArgs)
        {
            Thread t = null;

            switch (dumpType)
            {
            case DumpType.UIGlobals:
                t = new Thread(new ParameterizedThreadStart(Dumper_UIGlobals));
                break;

            case DumpType.UIChildren:
                t = new Thread(new ParameterizedThreadStart(Dumper_UIChildren));
                break;

            default:
                return;
            }

            if (t != null)
            {
                t.IsBackground = true;
                t.Start(dumpArgs);
                t = null;
            }
        }
Exemple #2
0
        /// <summary>
        /// saving Wcf Configuration
        /// </summary>
        /// <param name="dumpType"></param>
        /// <param name="value"></param>
        /// <param name="wcfType"></param>
        public void updateConfigurationFile(DumpType dumpType, String value, WcfType?wcfType = null)
        {
            SetDumpConfig(dumpType);

            switch (dumpType)
            {
            case DumpType.File:
                configFile.UpdateAppSetting(AppKeyName.FilePath, value);
                break;

            case DumpType.Msmq:
                configFile.UpdateAppSetting(AppKeyName.MsmqPath, value);
                break;

            case DumpType.Wcf:
                configFile.UpdateAppSetting(AppKeyName.WcfType, wcfType.Value.ToString());
                configFile.UpdateUri(new Uri(value), wcfType.Value);
                break;

            default:
                break;
            }

            configFile.Save();
        }
Exemple #3
0
        public Task <ActionResult> GetDump(
            ProcessFilter?processFilter,
            [FromQuery] DumpType type         = DumpType.WithHeap,
            [FromQuery] string egressProvider = null)
        {
            return(InvokeForProcess(async processInfo =>
            {
                string dumpFileName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ?
                                      FormattableString.Invariant($"dump_{GetFileNameTimeStampUtcNow()}.dmp") :
                                      FormattableString.Invariant($"core_{GetFileNameTimeStampUtcNow()}");

                if (string.IsNullOrEmpty(egressProvider))
                {
                    Stream dumpStream = await _diagnosticServices.GetDump(processInfo, type, HttpContext.RequestAborted);

                    //Compression is done automatically by the response
                    //Chunking is done because the result has no content-length
                    return File(dumpStream, ContentTypes.ApplicationOctectStream, dumpFileName);
                }
                else
                {
                    KeyValueLogScope scope = new KeyValueLogScope();
                    scope.AddArtifactType(ArtifactType_Dump);
                    scope.AddEndpointInfo(processInfo.EndpointInfo);

                    return new EgressStreamResult(
                        token => _diagnosticServices.GetDump(processInfo, type, token),
                        egressProvider,
                        dumpFileName,
                        processInfo.EndpointInfo,
                        ContentTypes.ApplicationOctectStream,
                        scope);
                }
            }, processFilter, ArtifactType_Dump));
        }
Exemple #4
0
        public void SetDumpType(DumpIdentifier id, DumpType type)
        {
            DumpMetainfo dumpInfo = Get(id);

            dumpInfo.DumpType = type;
            storage.Store(dumpInfo);
        }
Exemple #5
0
        public static void WriteDump(string fileName, DumpType typeOfdumpType)
        {
            MiniDumpExceptionInformation info;

            info.ThreadId          = NativeMethods.GetCurrentThreadId();
            info.ClientPointers    = false;
            info.ExceptionPointers = Marshal.GetExceptionPointers();

            using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                uint   processId      = (uint)Process.GetCurrentProcess().Id;
                IntPtr processHandle  = NativeMethods.GetCurrentProcess();
                IntPtr processHandle2 = Process.GetCurrentProcess().Handle;
                // Feel free to specify different dump types
                //uint dumpType = (uint) (DumpType.MiniDumpNormal | DumpType.MiniDumpWithDataSegs);
                uint dumpType = (uint)typeOfdumpType;
                NativeMethods.MiniDumpWriteDump(processHandle2,
                                                processId,
                                                fs.SafeFileHandle.DangerousGetHandle(),
                                                dumpType,
                                                ref info,
                                                IntPtr.Zero,
                                                IntPtr.Zero);
            }
        }
        /// <summary>
        /// Trigger a core dump generation.
        /// </summary>
        /// <param name="dumpType">Type of the dump to be generated</param>
        /// <param name="dumpPath">Full path to the dump to be generated. By default it is /tmp/coredump.{pid}</param>
        /// <param name="logDumpGeneration">When set to true, display the dump generation debug log to the console.</param>
        /// <param name="token">The token to monitor for cancellation requests.</param>
        internal async Task WriteDumpAsync(DumpType dumpType, string dumpPath, bool logDumpGeneration, CancellationToken token)
        {
            IpcMessage request  = CreateWriteDumpMessage(dumpType, dumpPath, logDumpGeneration);
            IpcMessage response = await IpcClient.SendMessageAsync(_endpoint, request, token).ConfigureAwait(false);

            ValidateResponseMessage(response, nameof(WriteDumpAsync));
        }
        private void FillControls()
        {
            DumpType dtype = _editor.CurrentDumpLayer;

            switch (dtype)
            {
            case DumpType.File:
                FileSelected        = true;
                FolderPath          = _editor.FolderPath;
                MsmqPath            = String.Empty;
                SelectedBindingType = WcfBindingType[0];
                WcfUri = String.Empty;
                break;

            case DumpType.Msmq:
                MsmqSelected        = true;
                MsmqPath            = _editor.MsmqPath;
                FolderPath          = String.Empty;
                SelectedBindingType = WcfBindingType[0];
                WcfUri = String.Empty;
                break;

            case DumpType.Wcf:
                SelectedBindingType = _editor.WcfType;
                WcfSelected         = true;
                WcfUri     = _editor.GetWcfUri((WcfType)Enum.Parse(typeof(WcfType), SelectedBindingType)).ToString();
                MsmqPath   = String.Empty;
                FolderPath = String.Empty;
                break;

            default:
                break;
            }
        }
Exemple #8
0
        internal DebugTarget(DebugClient client, int index)
        {
            Index = index;
            client.Control.GetDebuggeeType(out DebuggeeClass, out DebuggeeClassQualifier);
            switch (DebuggeeClass)
            {
            case DEBUG_CLASS.KERNEL:
                IsKernel = true;
                break;

            case DEBUG_CLASS.IMAGE_FILE:
                IsDump = true;
                break;
            }

            switch (DebuggeeClassQualifier)
            {
            case DEBUG_CLASS_QUALIFIER.KERNEL_LOCAL:
                IsLocalKernel = true;
                break;

            case DEBUG_CLASS_QUALIFIER.KERNEL_DUMP:
                DumpType = DumpType.Kernel;
                break;

            case DEBUG_CLASS_QUALIFIER.KERNEL_SMALL_DUMP:
                DumpType = DumpType.Small;
                break;

            case DEBUG_CLASS_QUALIFIER.KERNEL_FULL_DUMP:
                DumpType = DumpType.Full;
                IsDump   = true;
                break;
            }
        }
        /// <summary>
        /// Trigger a core dump generation.
        /// </summary>
        /// <param name="dumpType">Type of the dump to be generated</param>
        /// <param name="dumpPath">Full path to the dump to be generated. By default it is /tmp/coredump.{pid}</param>
        /// <param name="logDumpGeneration">When set to true, display the dump generation debug log to the console.</param>
        public void WriteDump(DumpType dumpType, string dumpPath, bool logDumpGeneration = false)
        {
            IpcMessage request  = CreateWriteDumpMessage(dumpType, dumpPath, logDumpGeneration);
            IpcMessage response = IpcClient.SendMessage(_endpoint, request);

            ValidateResponseMessage(response, nameof(WriteDump));
        }
 private void ArchiveDump(DumpType dumpType, string fileName)
 {
     if (_settings.ArchiveDumps)
     {
         var archiveDir = Path.Combine(AppContext.BaseDirectory, "dump-archive", dumpType.ToString().ToLower());
         if (!Directory.Exists(archiveDir))
         {
             Directory.CreateDirectory(archiveDir);
         }
         var info            = new FileInfo(fileName);
         var archiveFilename = $"{info.LastWriteTimeUtc.Year}-{info.LastWriteTimeUtc.Month:00}-{info.LastWriteTimeUtc.Day:00}-{dumpType.ToString().ToLower()}.xml.gz";
         var targetFileName  = Path.Combine(archiveDir, archiveFilename);
         _logger.Information("Archiving {@fileName} to {@archiveFileName}", fileName, targetFileName);
         if (File.Exists(fileName))
         {
             File.Copy(fileName, targetFileName);
         }
         else
         {
             _logger.Warning("File ({@fileName}) to archive not found.", fileName);
         }
     }
     else
     {
         _logger.Debug("{@dumpType} dump archiving skipped.", dumpType);
     }
 }
        /// <summary>
        /// Initiate a core dump in the target process runtime.
        /// </summary>
        /// <param name="processId">.NET Core process id</param>
        /// <param name="dumpName">Path and file name of core dump</param>
        /// <param name="dumpType">Type of dump</param>
        /// <param name="diagnostics">If true, log to console the dump generation diagnostics</param>
        /// <returns>DiagnosticsServerErrorCode</returns>
        public static int GenerateCoreDump(int processId, string dumpName, DumpType dumpType, bool diagnostics)
        {
            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                throw new PlatformNotSupportedException($"Unsupported operating system: {RuntimeInformation.OSDescription}");
            }

            if (string.IsNullOrEmpty(dumpName))
            {
                throw new ArgumentNullException($"{nameof(dumpName)} required");
            }


            var payload = SerializeCoreDump(dumpName, dumpType, diagnostics);
            var message = new IpcMessage(DiagnosticsServerCommandSet.Dump, (byte)DumpCommandId.GenerateCoreDump, payload);

            var response = IpcClient.SendMessage(processId, message);

            var hr = 0;

            switch ((DiagnosticsServerCommandId)response.Header.CommandId)
            {
            case DiagnosticsServerCommandId.Error:
            case DiagnosticsServerCommandId.OK:
                hr = BitConverter.ToInt32(response.Payload, 0);
                break;

            default:
                return(-1);
            }

            return(hr);
        }
Exemple #12
0
 public static void DumpLine(string line, int level, DumpType dumpType = DumpType.Strings)
 {
     if (!CanDump(dumpType) || !InitDump())
     {
         return;
     }
     if (!dumpAllLevels && !AllowedDumpLevels.Contains(level))
     {
         return;
     }
     if (dumpType == DumpType.Strings)
     {
         line = line.Replace("\n", "").Trim().Escape();
     }
     if (cachedDumps.Contains(line))
     {
         return;
     }
     cachedDumps.Add(line);
     lock (dumpStream)
     {
         dumpStream.WriteLine($"[{dumpType}][LEVEL {level}] {line}");
         dumpStream.Flush();
     }
 }
Exemple #13
0
 private void WriteToLog(DumpType type, ITraceable traceable)
 {
     try
     {
         XmlTextReader xmlTextReader = new XmlTextReader(traceStream.InnerStream);
         StringWriter  writer        = new StringWriter(new StringBuilder((int)(traceStream.InnerStream.Length * 1.51)));
         XmlTextWriter xmlTextWriter = new XmlTextWriter(writer);
         xmlTextWriter.Formatting  = Formatting.Indented;
         xmlTextWriter.IndentChar  = '\t';
         xmlTextWriter.Indentation = 1;
         xmlTextReader.MoveToContent();
         xmlTextWriter.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\"");
         while (!xmlTextReader.EOF)
         {
             if (xmlTextReader.NodeType != XmlNodeType.XmlDeclaration)
             {
                 xmlTextWriter.WriteNode(xmlTextReader, false);
             }
         }
         Trace.WriteLine(writer.ToString(), String.Format("{0} {1}", traceable.ComponentName, type));
     }
     catch (Exception e)
     {
         Trace.TraceError("Error in TraceExtension: {0}", e);
     }
 }
        /// <summary>
        /// Trigger a core dump generation.
        /// </summary>
        /// <param name="dumpType">Type of the dump to be generated</param>
        /// <param name="dumpPath">Full path to the dump to be generated. By default it is /tmp/coredump.{pid}</param>
        /// <param name="logDumpGeneration">When set to true, display the dump generation debug log to the console.</param>
        public void WriteDump(DumpType dumpType, string dumpPath, bool logDumpGeneration = false)
        {
            if (string.IsNullOrEmpty(dumpPath))
            {
                throw new ArgumentNullException($"{nameof(dumpPath)} required");
            }

            byte[]     payload  = SerializeCoreDump(dumpPath, dumpType, logDumpGeneration);
            IpcMessage message  = new IpcMessage(DiagnosticsServerCommandSet.Dump, (byte)DumpCommandId.GenerateCoreDump, payload);
            IpcMessage response = IpcClient.SendMessage(_endpoint, message);

            switch ((DiagnosticsServerResponseId)response.Header.CommandId)
            {
            case DiagnosticsServerResponseId.Error:
                uint hr = BitConverter.ToUInt32(response.Payload, 0);
                if (hr == (uint)DiagnosticsIpcError.UnknownCommand)
                {
                    throw new PlatformNotSupportedException($"Unsupported operating system: {RuntimeInformation.OSDescription}");
                }
                throw new ServerErrorException($"Writing dump failed (HRESULT: 0x{hr:X8})");

            case DiagnosticsServerResponseId.OK:
                return;

            default:
                throw new ServerErrorException($"Writing dump failed - server responded with unknown command");
            }
        }
Exemple #15
0
        public async Task <int> Collect(CommandLineApplication cmd, int processId, string output, bool diag, DumpTypeOption type)
        {
            if (processId == 0)
            {
                return(cmd.ExitWithError("ProcessId is required."));
            }

            try
            {
                if (output == null)
                {
                    // Build timestamp based file path
                    string timestamp = $"{DateTime.Now:yyyyMMdd_HHmmss}";
                    output = Path.Combine(Directory.GetCurrentDirectory(), RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? $"dump_{processId}_{timestamp}.dmp" : $"core_{processId}_{timestamp}");
                }
                // Make sure the dump path is NOT relative. This path could be sent to the runtime
                // process on Linux which may have a different current directory.
                output = Path.GetFullPath(output);

                // Display the type of dump and dump path
                string dumpTypeMessage = type == DumpTypeOption.Mini ? "minidump" : "minidump with heap";
                cmd.Out.WriteLine($"Writing {dumpTypeMessage} to {output}");

                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    // Get the process
                    Process process = Process.GetProcessById(processId);

                    await Windows.CollectDumpAsync(process, output, type);
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    var      client   = new DiagnosticsClient(processId);
                    DumpType dumpType = type == DumpTypeOption.Heap ? DumpType.WithHeap : DumpType.Normal;

                    // Send the command to the runtime to initiate the core dump
                    client.WriteDump(dumpType, output, diag);
                }
                else
                {
                    throw new PlatformNotSupportedException($"Unsupported operating system: {RuntimeInformation.OSDescription}");
                }
            }
            catch (Exception ex) when
                (ex is FileNotFoundException ||
                ex is DirectoryNotFoundException ||
                ex is UnauthorizedAccessException ||
                ex is PlatformNotSupportedException ||
                ex is InvalidDataException ||
                ex is InvalidOperationException ||
                ex is NotSupportedException ||
                ex is DiagnosticsClientException)
            {
                return(cmd.ExitWithError($"{ex.Message}"));
            }

            cmd.Out.WriteLine($"Complete");
            return(0);
        }
 internal static extern int WerReportAddDump(
     ReportHandle reportHandle,
     IntPtr hProcess,
     IntPtr hThread,
     DumpType dumpType,
     IntPtr pExceptionParam,
     IntPtr dumpCustomOptions,
     DumpFlags dumpFlags);
 private static extern bool MiniDumpWriteDump(
     [In] IntPtr hProcess,
     uint ProcessId,
     SafeFileHandle hFile,
     DumpType DumpType,
     [In] IntPtr ExceptionParam,
     [In] IntPtr UserStreamParam,
     [In] IntPtr CallbackParam);
        private LogManager(string path = "./logs/latest.log", LogTypes _MinimumLogType = LogTypes.All, string _pattern_prefix = "[ %TYPE%: %DATE% ]: %MESSAGE%", DumpType dumpType = DumpType.NoDump, int dumpInterval = 10000)
        {
            _singleton     = this;
            Path           = Directory.CreateDirectory(Directory.GetParent(System.IO.Path.GetFullPath(path)).FullName).FullName;
            MinimumLogType = _MinimumLogType;
            Pattern        = _pattern_prefix;
            DumpType       = dumpType;
            DumpInterval   = dumpInterval;
            if (!string.IsNullOrWhiteSpace(Path))
            {
                if (DumpType == DumpType.Interval)
                {
                    MessageQueue = new List <string>();
                    Timer dumpLog = new Timer(dumpInterval)
                    {
                        AutoReset = true,
                        Enabled   = true,
                    };
                    dumpLog.Elapsed += (s, e) => DumpQueue();
                    dumpLog.Start();
                }

                AppDomain.CurrentDomain.ProcessExit += (s, e) => Close();
            }

            switch (MinimumLogType)
            {
            case LogTypes.All:
                IsFatalEnabled = true; IsWarnEnabled = true; IsInfoEnabled = true; IsDebugEnabled = true; IsErrorEnabled = true;
                break;

            case LogTypes.Debug:
                IsFatalEnabled = true; IsWarnEnabled = true; IsInfoEnabled = true; IsDebugEnabled = true; IsErrorEnabled = true;
                break;

            case LogTypes.Info:
                IsFatalEnabled = true; IsWarnEnabled = true; IsInfoEnabled = true; IsDebugEnabled = false; IsErrorEnabled = true;
                break;

            case LogTypes.Warn:
                IsFatalEnabled = true; IsWarnEnabled = true; IsInfoEnabled = false; IsDebugEnabled = false; IsErrorEnabled = true;
                break;

            case LogTypes.Error:
                IsFatalEnabled = true; IsWarnEnabled = false; IsInfoEnabled = false; IsDebugEnabled = false; IsErrorEnabled = true;
                break;

            case LogTypes.Fatal:
                IsFatalEnabled = true; IsWarnEnabled = false; IsInfoEnabled = false; IsDebugEnabled = false; IsErrorEnabled = false;
                break;

            default:
                IsFatalEnabled = true; IsWarnEnabled = true; IsInfoEnabled = true; IsDebugEnabled = true; IsErrorEnabled = true;
                MinimumLogType = LogTypes.All;
                break;
            }
        }
    /// <summary>
    /// Writes the memory dump to the file.
    /// </summary>
    /// <param name="fileName">The file name.</param>
    /// <param name="dumpType">The dump type.</param>
    public static void WriteDump(string fileName, DumpType dumpType)
    {
      using (FileStream fileStream = new FileStream(fileName, FileMode.Create))
      {
        Process currentProcess = Process.GetCurrentProcess();
        NativeMethods.ExceptionInformation exceptionInformation = new NativeMethods.ExceptionInformation { ThreadId = NativeMethods.GetCurrentThreadId(), ExceptionPointers = Marshal.GetExceptionPointers() };

        NativeMethods.MiniDumpWriteDump(currentProcess.Handle, currentProcess.Id, fileStream.SafeFileHandle, dumpType, ref exceptionInformation, IntPtr.Zero, IntPtr.Zero);
      }
    }
 public Dump(string path, DateTime timestamp, DumpType type, ProcessorArchitecture architecture, IReadOnlyList <NativeModule> modules, IReadOnlyList <NativeThread> threads, IReadOnlyList <NativeMemoryInfo> memoryInfos)
 {
     Path         = path;
     Timestamp    = timestamp;
     Type         = type;
     Architecture = architecture;
     Modules      = modules;
     Threads      = threads;
     MemoryInfos  = memoryInfos;
 }
        private async Task RetrieveDumpAsync(DumpType dumpType, IJobExecutionContext context)
        {
            var    fileName     = Path.Combine(AppContext.BaseDirectory, _dumpRetrievalService.GetDumpFileNameByDumpType(dumpType));
            string existingHash = "";

            if (File.Exists(fileName))
            {
                _logger.Debug("Calculating hash from local file: {@fileName}", fileName);
                using (var fileStream = new FileStream(fileName, FileMode.Open))
                {
                    existingHash = await CalculateHashFromStreamAsync(fileStream).ConfigureAwait(false);
                }
            }
            if (!_dumpRetrievalService.IsLocalDumpAvailableAndUpToDate(dumpType))
            {
                var stopWatch = Stopwatch.StartNew();

                using (Stream responseStream = await _dumpRetrievalService.DownloadDumpAsync(dumpType, CancellationToken.None).ConfigureAwait(false))
                {
                    stopWatch.Stop();
                    _logger.Debug("Download {@dumpType} dump as stream took {@elapsed} to complete.", dumpType, stopWatch.Elapsed);
                    if (existingHash != await CalculateHashFromStreamAsync(responseStream).ConfigureAwait(false))
                    {
                        ArchiveDump(dumpType, fileName);
                        using (var fileStream = new FileStream(fileName, FileMode.Create))
                        {
                            stopWatch.Restart();
                            responseStream.Seek(0, SeekOrigin.Begin);
                            await responseStream.CopyToAsync(fileStream).ConfigureAwait(false);

                            stopWatch.Stop();
                            _logger.Debug("Writing {@dumpType} dump to local cache took {@elapsed} to complete.", dumpType, stopWatch.Elapsed);
                        }
                        _isRetrying = false;
                        //Set only to true if there is no value, if it is true no need to change, if it is false keep it at false
                        if (!_successfullyUpdated.HasValue)
                        {
                            _successfullyUpdated = true;
                        }
                    }
                    else
                    {
                        _logger.Warning("Downloaded {@dumpType} dump stream does not differ from local {@dumpType} dump. {@dumpType} dump was not updated yet.", dumpType);
                        await RerunJobAsync(context).ConfigureAwait(false);

                        _successfullyUpdated = false;
                    }
                }
            }
            else
            {
                _successfullyUpdated = true;
            }
        }
Exemple #22
0
        public Task DumpTest(DiagnosticPortConnectionMode mode, DumpType type)
        {
#if !NET6_0_OR_GREATER
            // Capturing non-full dumps via diagnostic command works inconsistently
            // on Alpine for .NET 5 and lower (the dump command will return successfully, but)
            // the dump file will not exist). Only test other dump types on .NET 6+
            if (DistroInformation.IsAlpineLinux && type != DumpType.Full)
            {
                _outputHelper.WriteLine("Skipped on Alpine for .NET 5 and lower.");
                return(Task.CompletedTask);
            }
#endif

            return(ScenarioRunner.SingleTarget(
                       _outputHelper,
                       _httpClientFactory,
                       mode,
                       TestAppScenarios.AsyncWait.Name,
                       appValidate: async(runner, client) =>
            {
                int processId = await runner.ProcessIdTask;

                using ResponseStreamHolder holder = await client.CaptureDumpAsync(processId, type);
                Assert.NotNull(holder);

                // The dump operation may still be in progress but the process should still be discoverable.
                // If this check fails, then the dump operation is causing dotnet-monitor to not be able
                // to observe the process any more.
                ProcessInfo processInfo = await client.GetProcessAsync(processId);
                Assert.NotNull(processInfo);

                await DumpTestUtilities.ValidateDump(runner.Environment.ContainsKey(DumpTestUtilities.EnableElfDumpOnMacOS), holder.Stream);

                await runner.SendCommandAsync(TestAppScenarios.AsyncWait.Commands.Continue);
            },
                       configureApp: runner =>
            {
                // MachO not supported on .NET 5, only ELF: https://github.com/dotnet/runtime/blob/main/docs/design/coreclr/botr/xplat-minidump-generation.md#os-x
                if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) && DotNetHost.RuntimeVersion.Major == 5)
                {
                    runner.Environment.Add(DumpTestUtilities.EnableElfDumpOnMacOS, "1");
                }
            },
                       configureTool: runner =>
            {
                string dumpTempFolder = Path.Combine(runner.TempPath, "Dumps");

                // The dump temp folder should not exist in order to test that capturing dumps into the folder
                // will work since dotnet-monitor should ensure the folder is created before issuing the dump command.
                Assert.False(Directory.Exists(dumpTempFolder), "The dump temp folder should not exist.");

                runner.ConfigurationFromEnvironment.SetDumpTempFolder(dumpTempFolder);
            }));
        }
        public async Task <Stream> DumpAsync(IEndpointInfo endpointInfo, Models.DumpType mode, CancellationToken token)
        {
            if (endpointInfo == null)
            {
                throw new ArgumentNullException(nameof(endpointInfo));
            }

            string dumpTempFolder = _storageOptions.CurrentValue.DumpTempFolder;

            // Ensure folder exists before issue command.
            if (!Directory.Exists(dumpTempFolder))
            {
                Directory.CreateDirectory(dumpTempFolder);
            }

            string   dumpFilePath = Path.Combine(dumpTempFolder, FormattableString.Invariant($"{Guid.NewGuid()}_{endpointInfo.ProcessId}"));
            DumpType dumpType     = MapDumpType(mode);

            IDisposable operationRegistration = null;

            // Only track operation status for endpoints from a listening server because:
            // 1) Each process only ever has a single instance of an IEndpointInfo
            // 2) Only the listening server will query the dump service for the operation status of an endpoint.
            if (IsListenMode)
            {
                // This is a quick fix to prevent the polling algorithm in the ServerEndpointInfoSource
                // from removing IEndpointInfo instances when they don't respond in a timely manner to
                // a dump operation causing the runtime to temporarily be unresponsive. Long term, this
                // concept should be folded into RequestLimitTracker with registered endpoint information
                // and allowing to query the status of an endpoint for a given artifact.
                operationRegistration = _operationTrackerService.Register(endpointInfo);
            }

            try
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    // Get the process
                    Process process = Process.GetProcessById(endpointInfo.ProcessId);
                    await Dumper.CollectDumpAsync(process, dumpFilePath, dumpType);
                }
                else
                {
                    var client = new DiagnosticsClient(endpointInfo.Endpoint);
                    await client.WriteDumpAsync(dumpType, dumpFilePath, logDumpGeneration : false, token);
                }
            }
            finally
            {
                operationRegistration?.Dispose();
            }

            return(new AutoDeleteFileStream(dumpFilePath));
        }
Exemple #24
0
        /// <summary>
        /// Writes the memory dump to the file.
        /// </summary>
        /// <param name="fileName">The file name.</param>
        /// <param name="dumpType">The dump type.</param>
        public static void WriteDump(string fileName, DumpType dumpType)
        {
            using (FileStream fileStream = new FileStream(fileName, FileMode.Create))
            {
                Process currentProcess = Process.GetCurrentProcess();
                NativeMethods.ExceptionInformation exceptionInformation = new NativeMethods.ExceptionInformation {
                    ThreadId = NativeMethods.GetCurrentThreadId(), ExceptionPointers = Marshal.GetExceptionPointers()
                };

                NativeMethods.MiniDumpWriteDump(currentProcess.Handle, currentProcess.Id, fileStream.SafeFileHandle, dumpType, ref exceptionInformation, IntPtr.Zero, IntPtr.Zero);
            }
        }
 public static void WriteDumpForProcess(Process process, string fileName, DumpType dumpType)
 {
     using (FileStream fs = File.Create(fileName))
     {
         if (!MiniDumpWriteDump(Process.GetCurrentProcess().Handle,
                                (uint)process.Id, fs.SafeFileHandle, dumpType,
                                IntPtr.Zero, IntPtr.Zero, IntPtr.Zero))
         {
             throw new Win32Exception(Marshal.GetLastWin32Error(), "Error calling MiniDumpWriteDump.");
         }
     }
 }
Exemple #26
0
        public void Dump(int pid, DumpType dumpType, string fileName, string dumpComment = null)
        {
            _pid        = pid;
            _dumpType   = dumpType;
            dumpComment = dumpComment ?? ("DumpWriter: " + _dumpType.ToString());

            IntPtr hProcess = DumpNativeMethods.OpenProcess(
                ProcessAccessFlags.QueryInformation | ProcessAccessFlags.VirtualMemoryRead | ProcessAccessFlags.DuplicateHandle,
                false,
                (uint)_pid
                );

            if (hProcess == IntPtr.Zero)
            {
                throw new ArgumentException(String.Format("Unable to open process {0}, error {x:8}", _pid, Marshal.GetLastWin32Error()));
            }

            FileStream dumpFileStream = new FileStream(fileName, FileMode.Create);

            var exceptionParam  = new MINIDUMP_EXCEPTION_INFORMATION();
            var userStreamParam = PrepareUserStream(dumpComment);
            var callbackParam   = new MINIDUMP_CALLBACK_INFORMATION();

            if (_dumpType == DumpType.FullMemoryExcludingSafeRegions ||
                _dumpType == DumpType.MinimalWithFullCLRHeap)
            {
                callbackParam.CallbackRoutine = CallbackRoutine;
            }

            MINIDUMP_TYPE nativeDumpType =
                (_dumpType == DumpType.FullMemory || _dumpType == DumpType.FullMemoryExcludingSafeRegions) ?
                MINIDUMP_TYPE.MiniDumpWithFullMemory | MINIDUMP_TYPE.MiniDumpWithHandleData | MINIDUMP_TYPE.MiniDumpWithFullMemoryInfo :
                MINIDUMP_TYPE.MiniDumpWithHandleData | MINIDUMP_TYPE.MiniDumpWithFullMemoryInfo;
            bool success = DumpNativeMethods.MiniDumpWriteDump(
                hProcess,
                (uint)_pid,
                dumpFileStream.SafeFileHandle.DangerousGetHandle(),
                nativeDumpType,
                ref exceptionParam,
                ref userStreamParam,
                ref callbackParam
                );

            if (!success)
            {
                throw new ApplicationException(String.Format("Error writing dump, error {0:x8}", Marshal.GetLastWin32Error()));
            }

            userStreamParam.Delete();
            DumpNativeMethods.CloseHandle(hProcess);
            dumpFileStream.Close();
        }
Exemple #27
0
 public MiniDumper(string dumpFolder, int pid, string processName,
                   TextWriter logger, DumpType dumpType, bool writeAsync, string filter)
 {
     this.dumpFolder  = dumpFolder;
     this.pid         = pid;
     this.processName = processName;
     this.logger      = logger;
     this.dumpType    = dumpType;
     this.writeAsync  = writeAsync;
     this.rgxFilter   = new Regex((filter ?? "*").Replace("*", ".*").Replace('?', '.'),
                                  RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase);
     this.target = DataTarget.AttachToProcess(pid, 1000, AttachFlag.Passive);
 }
Exemple #28
0
 public MiniDumper(string dumpFolder, int pid, string processName,
     TextWriter logger, DumpType dumpType, bool writeAsync, string filter)
 {
     this.dumpFolder = dumpFolder;
     this.pid = pid;
     this.processName = processName;
     this.logger = logger;
     this.dumpType = dumpType;
     this.writeAsync = writeAsync;
     this.rgxFilter = new Regex((filter ?? "*").Replace("*", ".*").Replace('?', '.'),
         RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase);
     this.target = DataTarget.AttachToProcess(pid, 1000, AttachFlag.Passive);
 }
        private static byte[] SerializeCoreDump(string dumpName, DumpType dumpType, bool diagnostics)
        {
            using (var stream = new MemoryStream())
                using (var writer = new BinaryWriter(stream))
                {
                    writer.WriteString(dumpName);
                    writer.Write((uint)dumpType);
                    writer.Write((uint)(diagnostics ? 1 : 0));

                    writer.Flush();
                    return(stream.ToArray());
                }
        }
        public void Add_A_Type_Only_Once()
        {
            // arrange
            var sut  = new DumpModule(new DumpModuleKey(0, ""));
            var type = new DumpType();

            // act
            sut.AddType(type);
            sut.AddType(type);

            // assert
            sut.Types.Should().HaveCount(1);
        }
 public UnhandledExceptions( FeatureFlags featureFlags , DumpType dumpType )
 {
     _featureFlags = featureFlags;
     _dumpType = dumpType;
     if ( ( _featureFlags & FeatureFlags.Logging ) == FeatureFlags.Logging )
     {
         throw new ArgumentException("Logging feature is enabled with no log provided", "featureFlags");
     }
     if ( ( _featureFlags & FeatureFlags.Dump ) == FeatureFlags.Dump && _dumpType == DumpType.None )
     {
         throw new ArgumentException("Dump feature is enabled with DumpType.None provided", "dumpType");
     }
 }
 public UnhandledExceptions( FeatureFlags featureFlags , DumpType dumpType , ILog log )
 {
     _featureFlags = featureFlags;
     _dumpType = dumpType;
     _log = log;
     if ( ( _featureFlags & FeatureFlags.Logging ) == FeatureFlags.Logging && _log == null )
     {
         throw new ArgumentNullException("log", "Logging feature is enabled with null log provided");
     }
     if ( ( _featureFlags & FeatureFlags.Dump ) == FeatureFlags.Dump && _dumpType == DumpType.None )
     {
         throw new ArgumentException("Dump feature is enabled with DumpType.None provided", "dumpType");
     }
 }
Exemple #33
0
        /// <summary>
        /// Trigger a core dump generation.
        /// </summary>
        /// <param name="dumpType">Type of the dump to be generated</param>
        /// <param name="dumpPath">Full path to the dump to be generated. By default it is /tmp/coredump.{pid}</param>
        /// <param name="flags">logging and crash report flags. On runtimes less than 6.0, only LoggingEnabled is supported.</param>
        /// <param name="token">The token to monitor for cancellation requests.</param>
        public async Task WriteDumpAsync(DumpType dumpType, string dumpPath, WriteDumpFlags flags, CancellationToken token)
        {
            IpcMessage request  = CreateWriteDumpMessage2(dumpType, dumpPath, flags);
            IpcMessage response = await IpcClient.SendMessageAsync(_endpoint, request, token).ConfigureAwait(false);

            if (!ValidateResponseMessage(response, nameof(WriteDumpAsync), ValidateResponseOptions.UnknownCommandReturnsFalse))
            {
                if ((flags & ~WriteDumpFlags.LoggingEnabled) != 0)
                {
                    throw new ArgumentException($"Only {nameof(WriteDumpFlags.LoggingEnabled)} flag is supported by this runtime version", nameof(flags));
                }
                await WriteDumpAsync(dumpType, dumpPath, logDumpGeneration : (flags & WriteDumpFlags.LoggingEnabled) != 0, token);
            }
        }
Exemple #34
0
        /// <summary>
        /// Trigger a core dump generation.
        /// </summary>
        /// <param name="dumpType">Type of the dump to be generated</param>
        /// <param name="dumpPath">Full path to the dump to be generated. By default it is /tmp/coredump.{pid}</param>
        /// <param name="flags">logging and crash report flags. On runtimes less than 6.0, only LoggingEnabled is supported.</param>
        public void WriteDump(DumpType dumpType, string dumpPath, WriteDumpFlags flags)
        {
            IpcMessage request  = CreateWriteDumpMessage2(dumpType, dumpPath, flags);
            IpcMessage response = IpcClient.SendMessage(_endpoint, request);

            if (!ValidateResponseMessage(response, nameof(WriteDump), ValidateResponseOptions.UnknownCommandReturnsFalse))
            {
                if ((flags & ~WriteDumpFlags.LoggingEnabled) != 0)
                {
                    throw new ArgumentException($"Only {nameof(WriteDumpFlags.LoggingEnabled)} flag is supported by this runtime version", nameof(flags));
                }
                WriteDump(dumpType, dumpPath, logDumpGeneration: (flags & WriteDumpFlags.LoggingEnabled) != 0);
            }
        }
    /// <summary>
    /// Initializes a new instance of the <see cref="MemoryDumpOnException"/> class.
    /// </summary>
    /// <param name="fileName">The file name.</param>
    /// <param name="dumpType">The dump type.</param>
    /// <param name="exceptionsToTrack">The exceptions to track.</param>
    public MemoryDumpOnException(string fileName, DumpType dumpType, IEnumerable<Type> exceptionsToTrack)
    {
      if (fileName == null)
      {
        throw new ArgumentNullException("fileName");
      }

      if (exceptionsToTrack == null)
      {
        throw new ArgumentNullException("exceptionsToTrack");
      }

      this.fileName = fileName;
      this.dumpType = dumpType;
      this.exceptionsToTrack = exceptionsToTrack;
    }
Exemple #36
0
        public void Dump(int pid, DumpType dumpType, string fileName, string dumpComment = null)
        {
            _pid = pid;
            _dumpType = dumpType;
            dumpComment = dumpComment ?? ("DumpWriter: " + _dumpType.ToString());

            IntPtr hProcess = DumpNativeMethods.OpenProcess(
                ProcessAccessFlags.QueryInformation | ProcessAccessFlags.VirtualMemoryRead | ProcessAccessFlags.DuplicateHandle,
                false,
                (uint)_pid
                );
            if (hProcess == IntPtr.Zero)
                throw new ArgumentException(String.Format("Unable to open process {0}, error {x:8}", _pid, Marshal.GetLastWin32Error()));

            FileStream dumpFileStream = new FileStream(fileName, FileMode.Create);

            var exceptionParam = new MINIDUMP_EXCEPTION_INFORMATION();
            var userStreamParam = PrepareUserStream(dumpComment);
            var callbackParam = new MINIDUMP_CALLBACK_INFORMATION();
            if (_dumpType == DumpType.FullMemoryExcludingSafeRegions ||
                _dumpType == DumpType.MinimalWithFullCLRHeap)
            {
                callbackParam.CallbackRoutine = CallbackRoutine;
            }

            MINIDUMP_TYPE nativeDumpType =
                (_dumpType == DumpType.FullMemory || _dumpType == DumpType.FullMemoryExcludingSafeRegions) ?
                MINIDUMP_TYPE.MiniDumpWithFullMemory | MINIDUMP_TYPE.MiniDumpWithHandleData | MINIDUMP_TYPE.MiniDumpWithFullMemoryInfo :
                MINIDUMP_TYPE.MiniDumpWithHandleData | MINIDUMP_TYPE.MiniDumpWithFullMemoryInfo;
            bool success = DumpNativeMethods.MiniDumpWriteDump(
                hProcess,
                (uint)_pid,
                dumpFileStream.SafeFileHandle.DangerousGetHandle(),
                nativeDumpType,
                ref exceptionParam,
                ref userStreamParam,
                ref callbackParam
                );
            if (!success)
                throw new ApplicationException(String.Format("Error writing dump, error {0:x8}", Marshal.GetLastWin32Error()));

            userStreamParam.Delete();
            DumpNativeMethods.CloseHandle(hProcess);
            dumpFileStream.Close();
        }
Exemple #37
0
        public int Dump(Stream asnStream, TextWriter dumpWriter, DumpType dumpType, byte maxLevel)
        {
            long offset = asnStream.Position;

            BerDecoderResult pr = BerDecoderResult.Finished;
            TlvObject tlv;
            D900CdrElement record;
            int cnt = 0;

            for (; ; )//(int n = 11; n > 0; n--)
            {
                pr = DecodeTlv(asnStream, out tlv, ref offset, 0, maxLevel);

                if (pr != BerDecoderResult.Finished)
                    break;

                switch (dumpType)
                {
                    case DumpType.TLV_TXT:
                        tlv.DumpToTxt(dumpWriter, String.Format("{0,8} > {1}", tlv.Offset, ++cnt));
                        dumpWriter.WriteLine();
                        break;
                    case DumpType.TLV_XML:
                        tlv.DumpToXml(dumpWriter, 0);
                        break;
                    case DumpType.ELEMENT_TXT:
                        record = _tlvParser.ParseTlvObject(tlv);
                        record.DumpToTxt(dumpWriter, String.Format("{0,8} > {1}", record.Offset, ++cnt));
                        dumpWriter.WriteLine();
                        break;
                    case DumpType.ELEMENT_XML:
                        record = _tlvParser.ParseTlvObject(tlv);
                        record.DumpToXml(dumpWriter, 0);
                        break;
                }
            }

            dumpWriter.Flush();

            return (int)(pr);
        }
        public static void WriteDump(string fileName, DumpType typeOfdumpType)
        {
            MiniDumpExceptionInformation info;
            info.ThreadId = NativeMethods.GetCurrentThreadId();
            info.ClientPointers = false;
            info.ExceptionPointers = Marshal.GetExceptionPointers();

            using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                var processId = (uint) Process.GetCurrentProcess().Id;
                var processHandle = NativeMethods.GetCurrentProcess();
                var processHandle2 = Process.GetCurrentProcess().Handle;
                // Feel free to specify different dump types
                //uint dumpType = (uint) (DumpType.MiniDumpNormal | DumpType.MiniDumpWithDataSegs);
                var dumpType = (uint) typeOfdumpType;
                NativeMethods.MiniDumpWriteDump(processHandle2,
                                                processId,
                                                fs.SafeFileHandle.DangerousGetHandle(),
                                                dumpType,
                                                ref info,
                                                IntPtr.Zero,
                                                IntPtr.Zero);
            }
        }
Exemple #39
0
        public void Dump(DumpType dumpType, object dumpArgs)
        {
            Thread t = null;

            switch (dumpType)
            {
                case DumpType.UIGlobals:
                    t = new Thread(new ParameterizedThreadStart(Dumper_UIGlobals));
                    break;

                case DumpType.UIChildren:
                    t = new Thread(new ParameterizedThreadStart(Dumper_UIChildren));
                    break;

                default:
                    return;
            }

            if (t != null)
            {
                t.IsBackground = true;
                t.Start(dumpArgs);
                t = null;
            }
        }
 internal static extern int WerReportAddDump(
     ReportHandle reportHandle,
     IntPtr hProcess,
     IntPtr hThread,
     DumpType dumpType,
     IntPtr pExceptionParam,
     IntPtr dumpCustomOptions,
     DumpFlags dumpFlags);
 internal static extern bool MiniDumpWriteDump(IntPtr processHandle, int processId, SafeHandle fileHandle, DumpType dumpType, ref ExceptionInformation exception, IntPtr userStream, IntPtr callback);
Exemple #42
0
        public void Dump(int pid, DumpType dumpType, IntPtr exceptionParam,
            string fileName, bool writeAsync = false, string dumpComment = null)
        {
            _pid = pid;
            _dumpType = dumpType;
            _spillSegmentsAsynchronously = writeAsync;
            dumpComment = dumpComment ?? ("DumpWriter: " + _dumpType.ToString());

            IntPtr hProcess = DumpNativeMethods.OpenProcess(
                ProcessAccessFlags.QueryInformation | ProcessAccessFlags.VirtualMemoryRead | ProcessAccessFlags.DuplicateHandle,
                false,
                (uint)_pid
                );
            if (hProcess == IntPtr.Zero)
                throw new ArgumentException(String.Format("Unable to open process {0}, error {x:8}", _pid, Marshal.GetLastWin32Error()));

            _dumpFileStream = new FileStream(fileName, FileMode.Create);

            var userStreamParam = PrepareUserStream(dumpComment);
            var callbackParam = new MINIDUMP_CALLBACK_INFORMATION();
            _needMemoryCallbacks = (
                _dumpType == DumpType.FullMemoryExcludingSafeRegions ||
                _dumpType == DumpType.MinimalWithFullCLRHeap
                );
            if (_needMemoryCallbacks || _spillSegmentsAsynchronously)
            {
                callbackParam.CallbackRoutine = CallbackRoutine;
            }

            MINIDUMP_TYPE nativeDumpType =
                (_dumpType == DumpType.FullMemory || _dumpType == DumpType.FullMemoryExcludingSafeRegions) ?
                MINIDUMP_TYPE.MiniDumpWithFullMemory | MINIDUMP_TYPE.MiniDumpWithHandleData | MINIDUMP_TYPE.MiniDumpWithFullMemoryInfo :
                MINIDUMP_TYPE.MiniDumpWithHandleData | MINIDUMP_TYPE.MiniDumpWithFullMemoryInfo;
            Stopwatch sw = Stopwatch.StartNew();
            bool success = DumpNativeMethods.MiniDumpWriteDump(
                hProcess,
                (uint)_pid,
                _dumpFileStream.SafeFileHandle.DangerousGetHandle(),
                nativeDumpType,
                exceptionParam,
                ref userStreamParam,
                ref callbackParam);
            if (!success)
                throw new ApplicationException(string.Format("Error writing dump, error: {0}", Marshal.GetExceptionForHR(
                    Marshal.GetHRForLastWin32Error())));

            _logger.WriteLine("Process was suspended for {0:N2}ms", sw.Elapsed.TotalMilliseconds);

            if (_spillSegmentsAsynchronously)
            {
                // We are asynchronously spilling dump segments to disk, need to wait
                // for this process to complete before returning to the caller.
                _segmentSpillingTask.Wait();
                _logger.WriteLine(
                    "Total dump writing time including async flush was {0:N2}ms",
                    sw.Elapsed.TotalMilliseconds);
            }

            userStreamParam.Delete();
            DumpNativeMethods.CloseHandle(hProcess);
            _dumpFileStream.Close();
        }
Exemple #43
0
		public void Setup(DumpFormat format, DumpType type)
		{
			this.format = format;
			this.type = type;

			switch(format)
			{
				case DumpFormat.Text:
					file = Path.Combine(directory, string.Format("TagIndexDump.{0:yyyy}{0:MM}{0:dd}_{0:HH}{0:mm}({0:ss}).{1}", DateTime.Now, "txt"));
					provider = new TextProvider(file, type);
					break;

				case DumpFormat.Xml:
					file = Path.Combine(directory, string.Format("TagIndexDump.{0:yyyy}{0:MM}{0:dd}_{0:HH}{0:mm}({0:ss}).{1}", DateTime.Now, "xml"));
					provider = new XmlProvider(file);
					break;
			}
		}
Exemple #44
0
 public int Dump(Stream asnStream, DumpType dumpType)
 {
     return this.Dump(asnStream, System.Console.Out, dumpType, byte.MaxValue);
 }
Exemple #45
0
			public TextProvider(string file, DumpType type)
			{
				writer = new StreamWriter(file, false, Encoding.ASCII);
				this.type = type;
			}