Exemplo n.º 1
0
        public void LoadFromDump(string dumpPath)
        {
            Debug.Assert(_documentStore != null);

            if (_target != null)
            {
                Dispose();
            }
            _databaseName ??= dumpPath;

            var getDatabaseRecordResult = _documentStore.Maintenance.Server.Send(new GetDatabaseRecordOperation(_databaseName));

            if (getDatabaseRecordResult == null)//no such database
            {
                _documentStore.Maintenance.Server.Send(new CreateDatabaseOperation(new DatabaseRecord(_databaseName)));
            }
            //ensure indexes exist
            _documentStore.ExecuteIndex(new GcRootIndex(), _databaseName);
            _documentStore.ExecuteIndex(new HeapStatIndex(), _databaseName);
            _documentStore.ExecuteIndex(new HeapStatByGenerationIndex(), _databaseName);
            _documentStore.ExecuteIndex(new DuplicateStringsIndex(), _databaseName);


            _target = DataTarget.LoadDump(dumpPath);

            if (_target.ClrVersions.Length == 0)
            {
                throw new InvalidOperationException("Haven't found relevant CLR versions for the dump, cannot continue with the import");
            }

            _runtime = _target.CreateRuntime();
        }
Exemplo n.º 2
0
        public CLRReporter(int pid)
            : this()
        {
            // TODO: Get timeout from config
            var timeout = 5000U;

            _dataTarget = DataTarget.AttachToProcess(pid, timeout);
            _runtime    = _dataTarget.CreateRuntime(_mscordacwks);
        }
        public void OpenClrRuntime()
        {
            if (CurrentDataTarget == null)
            {
                OpenDump();
            }

            if (CurrentDataTarget == null)
            {
                //throw new ArgumentNullException("_dataTarget");
                return;
            }

            try
            {
                var info = CurrentDataTarget.ClrVersions.Single();
            }
            catch (NullReferenceException ex)
            {
                // set error header
                MessageBox.Show(ex.Message, "Cannot opern CLR window", MessageBoxButton.OK, MessageBoxImage.Error);

                var viewModel2 = new DataTargetViewModel(CurrentDataTarget);
                ActivateItem(viewModel2);
                return;
            }
            catch (InvalidOperationException ex)
            {
                MessageBox.Show("Cannot find CLR in this process", "Cannot open CLR window", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            var clrVersion = CurrentDataTarget.ClrVersions.FirstOrDefault();

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

            try
            {
                if (CurrentClrRuntime == null)
                {
                    CurrentClrRuntime = CurrentDataTarget.CreateRuntime(clrVersion.TryGetDacLocation() ?? clrVersion.TryDownloadDac());
                }
            }
            catch (SystemException ex)
            {
                MessageBox.Show("Cannot open CLR runtime, due the: " + ex.Message);
                return;
            }

            var viewModel = new ClrRuntimeViewModel(CurrentClrRuntime);

            ActivateItem(viewModel);
        }
Exemplo n.º 4
0
        private void CreateRuntime()
        {
            ClrInfo clrInfo     = _target.ClrVersions[_clrVersionIndex];
            string  dacLocation = clrInfo.TryDownloadDac();

            _context.WriteInfo("Using Data Access DLL at: " + dacLocation);
            _context.DacLocation = dacLocation;
            _context.ClrVersion  = clrInfo;
            _context.Runtime     = _target.CreateRuntime(dacLocation);
            _context.Heap        = _context.Runtime.GetHeap();
            _target.DefaultSymbolNotification = new SymbolNotification(_context);
        }
        private ClrRuntime SetupClrRuntime(DataTarget dataTarget)
        {
            var version = dataTarget.ClrVersions.Single();

            logger?.WriteLine($"\nCLR Version: {version.Version} ({version.Flavor}), Dac: {version.DacInfo}");
            var dacFileName = version.TryDownloadDac();

            logger?.WriteLine($"DacFile: {Path.GetFileName(dacFileName)}");
            logger?.WriteLine($"DacPath: {Path.GetDirectoryName(dacFileName)}");
            ClrRuntime runtime = dataTarget.CreateRuntime(dacFileName);

            return(runtime);
        }
Exemplo n.º 6
0
        private void StartRuntime(string Target)
        {
            DataTarget dataTarget = DataTarget.LoadCrashDump(Target);
            ClrInfo    latest     = null;

            foreach (var version in dataTarget.ClrVersions)
            {
                WriteLine("Version: {0}.{1}.{2}.{3} from {4}", version.Version.Major, version.Version.Minor, version.Version.Patch, version.Version.Revision, version.DacInfo.FileName);
                latest = version;
            }
            m_runtime = dataTarget.CreateRuntime(latest.TryDownloadDac());
            ulong strMT, arrMT, freeMT = 0;

            AdHoc.GetCommonMT(m_runtime, out strMT, out arrMT, out freeMT);

            WriteLine("Free MT: {0:x16}, String MT: {1:x16}, Array MT: {2:x16}", freeMT, strMT, arrMT);

            WriteLine("== App Domains ===");
            int i = 0;

            DumpDomains();
            //foreach (var appDomain in AdHoc.GetDomains(m_runtime))
            //{
            //    i++;
            //    if (i == 1)
            //    {
            //        WriteLine("{0:x16} System", appDomain.Address);
            //        WriteLine("  Modules: {0}", appDomain.Modules.Count);
            //        continue;
            //    }
            //    if (i == 2)
            //    {
            //        WriteLine("{0:x16} Shared", appDomain.Address);
            //        WriteLine("  Modules: {0}", appDomain.Modules.Count);
            //        continue;
            //    }



            //    WriteLine("{0:x16} {1}", appDomain.Address, appDomain.Name);
            //    WriteLine("  {0}{1}", appDomain.ApplicationBase, appDomain.ConfigurationFile);
            //    WriteLine("  Modules: {0}", appDomain.Modules.Count);

            //}

            WriteLine("==================");
            WriteLine("Heap(s): {0}  GC Server Mode: {1}", m_runtime.HeapCount, m_runtime.ServerGC);
            m_heap   = m_runtime.GetHeap();
            heapObjs = m_heap.EnumerateObjects().GetEnumerator();
            count    = 0;
        }
Exemplo n.º 7
0
        public void CreateRuntimeTest()
        {
            Assert.IsTrue(File.Exists(sample));

            DataTarget target = DataTarget.LoadCrashDump(sample, CrashDumpReader.ClrMD);

            target.SymbolLocator.SymbolPath = SYMBOL_PATH;
            Assert.IsNotNull(target);
            string     dac     = null;
            ClrRuntime runtime = target.CreateRuntime(ref dac);

            Assert.IsNotNull(dac);
            System.Diagnostics.Debug.WriteLine(dac);
        }
Exemplo n.º 8
0
        private static ClrRuntime CreateRuntimeHack(this DataTarget target, string dacLocation, int major, int minor)
        {
            string dacFileNoExt = Path.GetFileNameWithoutExtension(dacLocation);

            if (dacFileNoExt.Contains("mscordacwks") && major == 4 && minor >= 5)
            {
                Type   dacLibraryType = typeof(DataTarget).Assembly.GetType("Microsoft.Diagnostics.Runtime.DacLibrary");
                object dacLibrary     = Activator.CreateInstance(dacLibraryType, target, dacLocation);
                Type   v45RuntimeType = typeof(DataTarget).Assembly.GetType("Microsoft.Diagnostics.Runtime.Desktop.V45Runtime");
                object runtime        = Activator.CreateInstance(v45RuntimeType, target, dacLibrary);
                return((ClrRuntime)runtime);
            }
            else
            {
                return(target.CreateRuntime(dacLocation));
            }
        }
Exemplo n.º 9
0
 public void Initialize()
 {
     if (context == null)
     {
         context = new DumpContext();
         string dump = Environment.CurrentDirectory + @"\..\..\..\SuperDump\dumps\dotnetworld2\dotnetworld2.dmp";
         Assert.IsTrue(File.Exists(dump));
         string     dac    = null;
         DataTarget target = DataTarget.LoadCrashDump(dump, CrashDumpReader.ClrMD);
         target.SymbolLocator.SymbolPath = SYMBOL_PATH;
         context.Target        = target;
         context.Runtime       = target.CreateRuntime(ref dac);
         context.Heap          = context.Runtime.Heap;
         context.DumpFile      = dump;
         context.DumpDirectory = Path.GetDirectoryName(context.DumpFile);
         context.Printer       = new ConsolePrinter();
         context.SymbolLocator = target.SymbolLocator;
         context.SymbolPath    = target.SymbolLocator.SymbolPath;
     }
 }
Exemplo n.º 10
0
        private static ClrRuntime CreateRuntime(string dump, string dac)
        {
            // Create the data target.  This tells us the versions of CLR loaded in the target process.
            DataTarget dataTarget = DataTarget.LoadCrashDump(dump);

            // Now check bitness of our program/target:
            bool isTarget64Bit = dataTarget.PointerSize == 8;

            if (Environment.Is64BitProcess != isTarget64Bit)
            {
                throw new Exception(string.Format("Architecture mismatch:  Process is {0} but target is {1}", Environment.Is64BitProcess ? "64 bit" : "32 bit", isTarget64Bit ? "64 bit" : "32 bit"));
            }

            // Note I just take the first version of CLR in the process.  You can loop over every loaded
            // CLR to handle the SxS case where both v2 and v4 are loaded in the process.
            var version = dataTarget.ClrVersions[0];

            // Next, let's try to make sure we have the right Dac to load.  CLRVersionInfo will actually
            // have the full path to the right dac if you are debugging the a version of CLR you have installed.
            // If they gave us a path (and not the actual filename of the dac), we'll try to handle that case too:
            if (dac != null && Directory.Exists(dac))
            {
                dac = Path.Combine(dac, version.DacInfo.FileName);
            }
            else if (dac == null || !File.Exists(dac))
            {
                dac = version.TryGetDacLocation();
            }

            // Finally, check to see if the dac exists.  If not, throw an exception.
            if (dac == null || !File.Exists(dac))
            {
                throw new FileNotFoundException("Could not find the specified dac.", dac);
            }

            // Now that we have the DataTarget, the version of CLR, and the right dac, we create and return a
            // ClrRuntime instance.
            return(dataTarget.CreateRuntime(dac));
        }
Exemplo n.º 11
0
        private static void SetupCLRRuntime()
        {
            // for .NET specific
            try {
                string dac = null;
                context.DacLocation = dac;
                context.Runtime     = target.CreateRuntime(ref dac);
                context.WriteInfo("created runtime with version " + context.Runtime.ClrInfo.Version);
                context.Heap = context.Runtime.GetHeap();
            } catch (FileNotFoundException ex) {
                context.WriteError("The right dac file could not be found.");
                context.WriteLine(ex.Message);
                context.WriteLine(ex.StackTrace);

                context.Runtime = null;
                //context.Dispose();
                //throw ex;
            } catch (Exception ex) {
                context.WriteError("Exception creating CLR Runtime");
                context.WriteError(ex.Message);
                context.WriteLine(ex.StackTrace);
            }
        }
        static void Main(string[] args)
        {
            var dumpFullPath = "d:\\MysteryApp3.dmp";

            if (File.Exists(dumpFullPath) == false)
            {
                throw new FileNotFoundException($"Dump not found", dumpFullPath);
            }

            _target = DataTarget.LoadDump(dumpFullPath);

            if (_target.ClrVersions.Length == 0)
            {
                throw new InvalidOperationException("Haven't found relevant CLR versions for the dump, cannot continue with the import");
            }

            _runtime = _target.CreateRuntime();

            var allStrings = _runtime.Heap.EnumerateObjects()
                             .Where(x => x.Type.Name == "System.String")
                             .ToList();

            //TODO: write code to investigate the dumps
        }
        public bool Attach(Process process, string dacFile = null, uint attachTimeout = DefaultAttachTimeout)
        {
            if (process == null)
            {
                throw new ArgumentNullException("process");
            }
            _process = process;

            if (_dataTarget != null)
            {
                _output.Error(String.Format("Already attached to process PID={0} Name={1}",
                                            _process.Id, _process.ProcessName));
                return(false);
            }

            _output.Info(String.Format("Attaching to process PID={0}",
                                       process.Id));

            try
            {
                _dataTarget = DataTarget.AttachToProcess(process.Id, attachTimeout);

                //make sure we dont kill the process on exit
            }

            catch (Exception exception)
            {
                //TODO: Be more specific, dont catch all exceptions
                _output.Error("Could not attach to the process.");
                throw;
            }

            if (_dataTarget == null)
            {
                //TODO: Be more specific, what exactly does it mean?
                _output.Error("Could not attach to the process.");
                _process = null;
                return(false);
            }
            _dataTarget.DebuggerInterface.SetProcessOptions(DEBUG_PROCESS.DETACH_ON_EXIT);

            if (_dataTarget.ClrVersions.Count == 0)
            {
                var msg = String.Format(
                    "Process PID={0} Name={1} does not seem to have CLR loaded. Is it an unmanaged process?",
                    _process.Id, _process.ProcessName);
                _output.Error(msg);

                Detach();
                return(false);
            }
            if (_dataTarget.ClrVersions.Count > 1)
            {
                //TODO: multiple CLRs found present user with choice?
                var msg = String.Format("Multiple CLR versions loaded. Proceeding with first version.");
                _output.Warning(msg);
            }
            _clrInfo = _dataTarget.ClrVersions[0];

            _output.Info(String.Format("Using CLR Version={0} DACFileName={1}",
                                       _clrInfo.Version, _clrInfo.DacInfo.FileName));

            string dacLocation;

            if (String.IsNullOrWhiteSpace(dacFile))
            {
                dacLocation = _clrInfo.TryGetDacLocation();
            }
            else
            {
                dacLocation = dacFile;
                _output.Info(String.Format("Using DacFile={0}", dacFile));
            }
            if (String.IsNullOrWhiteSpace(dacLocation))
            {
                //TODO: Check filepath, display meaningful message
                _output.Error("Could not automatically locate Data Access Component (mscordacwks.dll). This may mean that bitness or CLR versions do not match. " +
                              "You may specify file location manually eg. ClrDiag.Attach(PID, @\"C:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319\\mscordacwks.dll\"");
                Detach();
                return(false);
            }

            ClrRuntime runtime = _dataTarget.CreateRuntime(dacLocation);

            if (runtime == null)
            {
                //TODO: add more meaningful information
                _output.Error("Unable to get CLR information.");
                Detach();
            }
            _output.Success(String.Format("Succesfully attached to process PID={0} Name={1}",
                                          _process.Id, _process.ProcessName));
            Clr = runtime;
            return(true);
        }
Exemplo n.º 14
0
        // Sample based on https://github.com/Microsoft/dotnetsamples/blob/master/Microsoft.Diagnostics.Runtime/CLRMD/docs/MachineCode.md
        // All the common code was copied from the MemStats project "dotnetsamples-master\Microsoft.Diagnostics.Runtime\CLRMD\MemStats\Program.cs"
        static void Main(string[] args)
        {
            string dump, dac;

            if (!TryParseArgs(args, out dump, out dac))
            {
                Usage();
                Environment.Exit(1);
            }

            try
            {
                // Create a ClrRuntime instance from the dump and dac location.  The ClrRuntime
                // object represents a version of CLR loaded in the process.  It contains data
                // such as the managed threads in the process, the AppDomains in the process,
                // the managed heap, and so on.
                //ClrRuntime runtime = CreateRuntime(dump, dac);

                // 1. Get the ClrType object for the type the method is on
                // 2. Get the ClrMethod object for the method
                // 3. Get the offset of the native code
                // 4. Compute the end address by mapping the IL instruction to addresses
                // 5. Disassemble the native code contained in that range (not provided by CLRMD)

                using (DataTarget dt = DataTarget.LoadCrashDump(dump))
                {
                    // Boilerplate.
                    //ClrRuntime runtime = dt.CreateRuntime(dt.ClrVersions.Single().TryDownloadDac());
                    var version = dt.ClrVersions.Single();
                    //{v4.0.30319.18444}
                    //version.Version = new VersionInfo { Major = 4, Minor = 0, Patch = 30319, Revision = 18444 };
                    Console.WriteLine("CLR Version: {0} ({1}), Dac: {2}", version.Version, version.Flavor, version.DacInfo);
                    var dacFileName = version.TryDownloadDac();
                    Console.WriteLine("DacFile: " + Path.GetFileName(dacFileName));
                    Console.WriteLine("DacPath: " + Path.GetDirectoryName(dacFileName));
                    ClrRuntime runtime = dt.CreateRuntime(dacFileName);
                    ClrHeap    heap    = runtime.GetHeap();

                    PrintDiagnosticInfo(dt, runtime, heap);
                    Console.WriteLine();

                    // Note heap.GetTypeByName doesn't always get you the type, even if it exists, due to
                    // limitations in the dac private apis that ClrMD is written on.  If you have the ClrType
                    // already via other means (heap walking, stack walking, etc), then that's better than
                    // using GetTypeByName:
                    var     classNameWithNamespace = "JITterOptimisations.Program";
                    ClrType @class = heap.GetTypeByName(classNameWithNamespace);

                    // Get the method you are looking for.
                    var       signature = "JITterOptimisations.Program.Log(System.ConsoleColor, System.String)";
                    ClrMethod @method   = @class.Methods.Single(m => m.GetFullSignature() == signature);

                    // This is the first instruction of the JIT'ed (or NGEN'ed) machine code.
                    ulong startAddress = @method.NativeCode;

                    // Unfortunately there's not a great way to get the size of the code, or the end address.
                    // This is partly due to the fact that we don't *have* to put all the JIT'ed code into one
                    // contiguous chunk, though I think an implementation detail is that we actually do.
                    // You are supposed to do code flow analysis like "uf" in windbg to find the size, but
                    // in practice you can use the IL to native mapping:
                    ulong endAddress = @method.ILOffsetMap.Select(entry => entry.EndAddress).Max();

                    var lines =
                        File.ReadAllLines(
                            @"C:\Users\warma11\Documents\Visual Studio 2013\Projects\JITterOptimisations\JITterOptimisations\Program.cs");

                    PrintILToNativeOffsetAlternative(method, lines);

                    // This doesn't seem to work as expected, using alternative method (above)
                    //PrintILToNativeOffsets(method, startAddress, lines);

                    // So the assembly code for the function is is in the range [startAddress, endAddress] inclusive.
                    var count = (int)endAddress + runtime.PointerSize - (int)startAddress;
                    Console.WriteLine("\nCode startAddress 0x{0:X} -> endAddress 0x{1:X} (inclusive), will read {2} bytes", startAddress, endAddress, count);

                    var bytes = new byte[count];
                    int bytesRead;
                    runtime.ReadMemory(startAddress, bytes, count, out bytesRead);
                    if (count != bytesRead)
                    {
                        Console.WriteLine("Expected to read {0} bytes, but only read {1}\n", count, bytesRead);
                    }
                    else
                    {
                        Console.WriteLine("Read read {0} bytes, as expected\n", bytesRead);
                    }
                    var fileName = string.Format("result-{0}bit.bin", runtime.PointerSize == 8 ? 64 : 32);
                    if (File.Exists(fileName))
                    {
                        File.Delete(fileName);
                    }
                    File.WriteAllBytes(fileName, bytes);

                    var filename =
                        @"C:\Users\warma11\Downloads\__GitHub__\dotnetsamples\Microsoft.Diagnostics.Runtime\CLRMD\MachineCode\nasm-2.11.05-win32\ndisasm.exe";
                    var currentFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                    var arguments     = "-b32 " + Path.Combine(currentFolder, fileName); // +" -o " + startAddress;
                    var disassembly   = Disassembler.GetDisassembly(filename, arguments, timeoutMsecs: 250);

                    var assemblyData = Disassembler.ProcessDisassembly(disassembly);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unhandled exception:");
                Console.WriteLine(ex);
            }
        }
Exemplo n.º 15
0
 public void CreateRuntimeFromDac(string dacLocation, out IMDRuntime ppRuntime)
 {
     ppRuntime = new MDRuntime(m_target.CreateRuntime(dacLocation));
 }
Exemplo n.º 16
0
 public CLRReporter(string dumpFile)
     : this()
 {
     _dataTarget = DataTarget.LoadCrashDump(dumpFile, CrashDumpReader.ClrMD);
     _runtime    = _dataTarget.CreateRuntime(_mscordacwks);
 }
Exemplo n.º 17
0
 private void CreateRuntime(string dacLocation)
 {
     _runtime = _target.CreateRuntime(dacLocation);
     _heap    = _runtime.GetHeap();
 }
Exemplo n.º 18
0
 private ClrMDSession(DataTarget target, string dacFile)
     : this(target, target.CreateRuntime(dacFile))
 {
 }
Exemplo n.º 19
0
        private static void ShowStackTrace(int processId, uint attachTimeout, string outputPath)
        {
            if (processId == -1)
            {
                throw new InvalidOperationException("Uinitialized process id parameter");
            }

            var threadInfoList = new List <ThreadInfo>();

            using (DataTarget dataTarget = DataTarget.AttachToProcess(processId, attachTimeout))
            {
                var dacLocation  = dataTarget.ClrVersions[0].TryGetDacLocation();
                var runtime      = dataTarget.CreateRuntime(dacLocation);
                var control      = (IDebugControl)dataTarget.DebuggerInterface;
                var sysObjs      = (IDebugSystemObjects)dataTarget.DebuggerInterface;
                var nativeFrames = new DEBUG_STACK_FRAME[100];
                var sybSymbols   = (IDebugSymbols)dataTarget.DebuggerInterface;

                var sb = new StringBuilder(1024 * 1024);

                foreach (ClrThread thread in runtime.Threads)
                {
                    var threadInfo = new ThreadInfo
                    {
                        OSThreadId = thread.OSThreadId
                    };

                    if (thread.StackTrace.Count > 0)
                    {
                        foreach (ClrStackFrame frame in thread.StackTrace)
                        {
                            if (frame.DisplayString.Equals("GCFrame") || frame.DisplayString.Equals("DebuggerU2MCatchHandlerFrame"))
                            {
                                continue;
                            }

                            threadInfo.StackTrace.Add(frame.DisplayString);
                        }
                    }
                    else
                    {
                        threadInfo.IsNative = true;

                        sysObjs.SetCurrentThreadId(threadInfo.OSThreadId);

                        uint frameCount;
                        control.GetStackTrace(0, 0, 0, nativeFrames, 100, out frameCount);

                        for (int i = 0; i < frameCount; i++)
                        {
                            uint  nameSize;
                            ulong dis;

                            sb.Clear();
                            sybSymbols.GetNameByOffset(nativeFrames[i].InstructionOffset, sb, sb.Capacity, out nameSize, out dis);

                            threadInfo.StackTrace.Add(sb.ToString());
                        }
                    }

                    threadInfoList.Add(threadInfo);
                }
            }

            var mergedStackTraces = new List <StackInfo>();

            foreach (var threadInfo in threadInfoList)
            {
                bool merged = false;

                foreach (var mergedStack in mergedStackTraces)
                {
                    if (threadInfo.IsNative != mergedStack.NativeThreads)
                    {
                        continue;
                    }

                    if (threadInfo.StackTrace.SequenceEqual(mergedStack.StackTrace, StringComparer.InvariantCultureIgnoreCase) == false)
                    {
                        continue;
                    }

                    if (mergedStack.ThreadIds.Contains(threadInfo.OSThreadId) == false)
                    {
                        mergedStack.ThreadIds.Add(threadInfo.OSThreadId);
                    }

                    merged = true;
                    break;
                }

                if (merged)
                {
                    continue;
                }

                mergedStackTraces.Add(new StackInfo()
                {
                    ThreadIds = new List <uint>()
                    {
                        threadInfo.OSThreadId
                    },
                    StackTrace    = threadInfo.StackTrace,
                    NativeThreads = threadInfo.IsNative
                });
            }

            var jsonSerializer = new JsonSerializer
            {
                Formatting = Formatting.Indented
            };

            if (outputPath != null)
            {
                using (var output = File.Create(outputPath))
                    using (var streamWriter = new StreamWriter(output))
                    {
                        jsonSerializer.Serialize(streamWriter, mergedStackTraces);
                    }
            }
            else
            {
                jsonSerializer.Serialize(Console.Out, mergedStackTraces);
            }
        }