コード例 #1
0
ファイル: ExceptionTests.cs プロジェクト: tomasr/clrmd
        private static void TestProperties(ClrRuntime runtime)
        {
            ClrThread thread = runtime.Threads.Where(t => !t.IsFinalizer).Single();
            ClrException ex = thread.CurrentException;
            Assert.IsNotNull(ex);

            Assert.AreEqual("IOE Message", ex.Message);
            Assert.AreEqual("System.InvalidOperationException", ex.Type.Name);
            Assert.IsNotNull(ex.Inner);
        }
コード例 #2
0
        public static void TestProperties(ClrRuntime runtime)
        {
            ClrThread thread = runtime.Threads.Where(t => !t.IsFinalizer).Single();
            ClrException ex = thread.CurrentException;
            Assert.IsNotNull(ex);

            ExceptionTestData testData = TestTargets.NestedExceptionData;
            Assert.AreEqual(testData.OuterExceptionMessage, ex.Message);
            Assert.AreEqual(testData.OuterExceptionType, ex.Type.Name);
            Assert.IsNotNull(ex.Inner);
        }
コード例 #3
0
        private void ShowCLRRuntimeInformation(DataTarget target)
        {
            rtxtCLRInfor.Clear();
            foreach (var clr in target.ClrVersions)
            {
                AppendText($"Version:\t{clr.Version.ToString()}");
                AppendText($"Module: \t{clr.ModuleInfo.ToString()}");
            }
            AppendText("");

            ClrRuntime runtime = target.ClrVersions.First().CreateRuntime();

            AppendText("App Domains:");
            AppendText("");

            var domains = new List <ClrAppDomain> {
                runtime.SystemDomain, runtime.SharedDomain
            };

            domains.AddRange(runtime.AppDomains.Select(x => x));

            foreach (var domain in domains)
            {
                AppendText($"  ID:                {domain.Id}");
                AppendText($"  Name:              {domain.Name}");
                AppendText($"  Address:           {domain.Address}");
                AppendText($"  ApplicationBase:   {domain.ApplicationBase}");
                AppendText($"  ConfigurationFile: {domain.ConfigurationFile}");
                AppendText("");

                AppendText("    Modules:" + Environment.NewLine);
                foreach (ClrModule module in domain.Modules)
                {
                    AppendText($"       Module:       { module.Name}");
                    AppendText($"       AssemblyName: { module.AssemblyName}");
                    AppendText("");
                }
            }
        }
コード例 #4
0
        private static void PrintHeapSegments(ClrRuntime runtime, StreamWriter sw)
        {
            sw.WriteLine("{0,12} {1,12} {2,12} {3,12} {4,4} {5}", "Start", "End", "CommittedEnd", "ReservedEnd", "Heap", "Type");
            foreach (ClrSegment segment in runtime.Heap.Segments)
            {
                string type;
                if (segment.IsEphemeral)
                {
                    type = "Ephemeral";
                }
                else if (segment.IsLarge)
                {
                    type = "Large";
                }
                else
                {
                    type = "Gen2";
                }

                sw.WriteLine($"{segment.Start,12:X} {segment.End,12:X} {segment.CommittedEnd,12:X} {segment.ReservedEnd,12:X} {segment.ProcessorAffinity,4} {type}");
            }
        }
コード例 #5
0
        public void DumpHeapStat()
        {
            using DataTarget dt      = TestTargets.Types.LoadFullDump();
            using ClrRuntime runtime = dt.ClrVersions.Single().CreateRuntime();
            ClrHeap heap    = runtime.Heap;
            var     results = heap.DumpHeapStat(0);
            var     all     = results.ToList();

            Assert.Equal(167, all.Count);
            Assert.Equal <(ulong, int, long)>((0x00007ff9fd29e768, 1, 24), GetRowData("System.Resources.FastResourceComparer"));
            Assert.Equal <(ulong, int, long)>((0x00007ff9fd295e70, 24, 36152), GetRowData("System.Object[]"));
            Assert.Equal <(ulong, int, long)>((0x00007ff9fd2959c0, 301, 22700), GetRowData("System.String"));

            (ulong methodTable, int instances, long totalSize) GetRowData(string typeName)
            {
                var objectArray = all.Where(a => a.type.Name.Equals(typeName)).Single();
                var size        = objectArray.size;
                var mt          = objectArray.type.MethodTable;

                return(mt, objectArray.objects.Count(), objectArray.size);
            }
        }
コード例 #6
0
        private Tuple <ulong, int, ulong, uint, uint>[] GetClrStackFrameLocals(Tuple <int, uint, int> input)
        {
            int              runtimeId      = input.Item1;
            uint             threadSystemId = input.Item2;
            int              stackFrameId   = input.Item3;
            ClrRuntime       clrRuntime     = runtimesCache[runtimeId];
            ClrThread        clrThread      = clrRuntime.Threads.First(t => t.OSThreadId == threadSystemId);
            ClrStackFrame    clrStackFrame  = clrThread.StackTrace[stackFrameId];
            IList <ClrValue> clrValues      = clrStackFrame.Locals;

            Tuple <ulong, int, ulong, uint, uint>[] variables = new Tuple <ulong, int, ulong, uint, uint> [clrValues.Count];
            ulong moduleBase    = clrStackFrame.Module.ImageBase;
            uint  metadataToken = clrStackFrame.Method.MetadataToken;
            uint  ilOffset      = FindIlOffset(clrStackFrame);

            for (int i = 0; i < variables.Length; i++)
            {
                GetClrValueAddressAndCodeTypeId(clrValues[i], out ulong address, out int codeTypeId);
                variables[i] = Tuple.Create(address, codeTypeId, moduleBase, metadataToken, ilOffset);
            }
            return(variables);
        }
コード例 #7
0
        public void GCRoots()
        {
            using (DataTarget dataTarget = TestTargets.GCRoot.LoadFullDump())
            {
                ClrRuntime runtime = dataTarget.ClrVersions.Single().CreateRuntime();
                GCRoot     gcroot  = new GCRoot(runtime.Heap);

                gcroot.ClearCache();
                Assert.False(gcroot.IsFullyCached);
                GCRootsImpl(gcroot);

                gcroot.BuildCache(CancellationToken.None);

                gcroot.AllowParallelSearch = false;
                Assert.True(gcroot.IsFullyCached);
                GCRootsImpl(gcroot);

                gcroot.AllowParallelSearch = true;
                Assert.True(gcroot.IsFullyCached);
                GCRootsImpl(gcroot);
            }
        }
コード例 #8
0
ファイル: Utils.cs プロジェクト: lhutyra/SELAConference2018
        public static ClrModule GetMscorlib(ClrRuntime clr)
        {
            foreach (ClrModule module in clr.Modules)
            {
                if (module.AssemblyName.Contains("mscorlib.dll"))
                {
                    return(module);
                }
            }

            // Uh oh, this shouldn't have happened.  Let's look more carefully (slowly).
            foreach (ClrModule module in clr.Modules)
            {
                if (module.AssemblyName.ToLower().Contains("mscorlib"))
                {
                    return(module);
                }
            }

            // Ok...not sure why we couldn't find it.
            return(null);
        }
コード例 #9
0
        static void Main(string[] args)
        {
            int pid = 1234;

            DataTarget dt = DataTarget.AttachToProcess(pid, 5000, AttachFlag.Passive);

            using (dt)
            {
                //pick first CLR version
                ClrInfo    runtimeInfo = dt.ClrVersions[0];
                ClrRuntime runtime     = runtimeInfo.CreateRuntime();

                ClrType type;

                //enumerate objects on managed heap
                foreach (ulong obj in runtime.Heap.EnumerateObjectAddresses())
                {
                    type = runtime.Heap.GetObjectType(obj);

                    if (type == null)
                    {
                        continue;
                    }

                    if (type.Name == "MyProject.MyClass")
                    {
                        Console.WriteLine("Address 0x{0:X}: {1}", obj, type.Name);
                        ClrInstanceField f   = type.GetFieldByName("Foo");
                        object           val = f.GetValue(obj);
                        if (val != null)
                        {
                            Console.WriteLine(val.ToString());
                        }
                    }
                }
            }

            Console.ReadKey();
        }
コード例 #10
0
ファイル: TypeTests.cs プロジェクト: urasandesu/clrmd
        public void VariableRootTest()
        {
            // Test to make sure that a specific static and local variable exist.

            using (DataTarget dt = TestTargets.Types.LoadFullDump())
            {
                ClrRuntime runtime = dt.ClrVersions.Single().CreateRuntime();
                ClrHeap    heap    = runtime.Heap;
                heap.StackwalkPolicy = ClrRootStackwalkPolicy.Exact;

                var fooRoots = from root in heap.EnumerateRoots()
                               where root.Type.Name == "Foo"
                               select root;

                ClrRoot staticRoot = fooRoots.Where(r => r.Kind == GCRootKind.StaticVar).Single();
                Assert.IsTrue(staticRoot.Name.Contains("s_foo"));

                var     arr          = fooRoots.Where(r => r.Kind == GCRootKind.LocalVar).ToArray();
                ClrRoot localVarRoot = fooRoots.Where(r => r.Kind == GCRootKind.LocalVar).Single();

                ClrThread     thread = runtime.GetMainThread();
                ClrStackFrame main   = thread.GetFrame("Main");
                ClrStackFrame inner  = thread.GetFrame("Inner");

                ulong low  = thread.StackBase;
                ulong high = thread.StackLimit;

                // Account for different platform stack direction.
                if (low > high)
                {
                    ulong tmp = low;
                    low  = high;
                    high = tmp;
                }


                Assert.IsTrue(low <= localVarRoot.Address && localVarRoot.Address <= high);
            }
        }
コード例 #11
0
        internal static Runtime GetCurrentRuntime()
        {
            //do not change the order of conditions because it may cause incorrect determination of runtime
            if (IsMono)
            {
                return(MonoRuntime.Default);
            }
            if (IsFullFramework)
            {
                return(ClrRuntime.GetCurrentVersion());
            }
            if (IsNetCore)
            {
                return(CoreRuntime.GetCurrentVersion());
            }
            if (IsCoreRT)
            {
                return(CoreRtRuntime.GetCurrentVersion());
            }

            throw new NotSupportedException("Unknown .NET Runtime");
        }
コード例 #12
0
        private static void OnParallelStacks(ClrRuntime runtime, string args)
        {
            var ps = ParallelStack.Build(runtime);

            if (ps == null)
            {
                return;
            }

            // display parallel stacks
            Console.WriteLine();
            foreach (var stack in ps.Stacks)
            {
                Console.Write("________________________________________________");
                stack.WriteToConsole(useDml: true);
                Console.WriteLine();
                Console.WriteLine();
                Console.WriteLine();
            }

            Console.WriteLine($"==> {ps.ThreadIds.Count} threads with {ps.Stacks.Count} roots{Environment.NewLine}");
        }
コード例 #13
0
        public void AllocationContextLocation()
        {
            // Simply test that we can enumerate the heap.
            using DataTarget dt      = TestTargets.Types.LoadFullDump();
            using ClrRuntime runtime = dt.ClrVersions.Single().CreateRuntime();
            ClrHeap heap = runtime.Heap;

            // Ensure that we never find objects within allocation contexts.
            MemoryRange[] allocationContexts = heap.EnumerateAllocationContexts().ToArray();
            Assert.NotEmpty(allocationContexts);

            foreach (MemoryRange ac in allocationContexts)
            {
                Assert.True(ac.Length > 0);

                ClrSegment seg = heap.GetSegmentByAddress(ac.Start);
                Assert.NotNull(seg);
                Assert.Same(seg, heap.GetSegmentByAddress(ac.End - 1));

                Assert.True(seg.ObjectRange.Contains(ac));
            }
        }
コード例 #14
0
    static void Main(string[] args)
    {
        //ClrRuntime runtime = CreateRuntime(@"C:\Users\leculver\Desktop\work\projects\rmd_test_data\dumps\v4.0.30319.239_x86.cab",
        //                                   @"C:\Users\leculver\Desktop\work\projects\rmd_test_data\dacs");
        //PrintDict(runtime, "0262b058");

        List <string> typeNames = new List <string>();
        ClrRuntime    runtime   = CreateRuntime(@"D:\work\03_09_ml\ml.dmp", @"D:\work\03_09_ml");
        ClrHeap       heap      = runtime.GetHeap();

        foreach (var type in heap.EnumerateTypes())
        {
            typeNames.Add(type.Name);
        }

        typeNames.Sort(delegate(string a, string b) { return(-a.Length.CompareTo(b.Length)); });

        for (int i = 0; i < 10; ++i)
        {
            Console.WriteLine("{0} {1}", typeNames[i].Length, typeNames[i]);
        }
    }
コード例 #15
0
ファイル: ClrDriver.cs プロジェクト: servicetitan/clrspy
        public ClrDriver(ClrRuntime runtime)
        {
            (this.runtime, heap, domain) = (runtime, runtime.Heap, runtime.AppDomains[0]);

            typeObject          = heap.GetTypeByName("System.Object");
            typeDelegate        = heap.GetTypeByName("System.Delegate");
            fieldDelegateTarget = typeDelegate.GetFieldByName("_target");

            typeTask = heap.GetTypeByName("System.Threading.Tasks.Task");
            if (typeTask.BaseType.Name == "System.Threading.Tasks.Task")
            {
                typeTask = typeTask.BaseType;
            }
            fieldTaskAction             = typeTask.GetFieldByName("m_action");
            fieldTaskScheduler          = typeTask.GetFieldByName("m_taskScheduler");
            fieldTaskContinuationObject = typeTask.GetFieldByName("m_continuationObject");

            typeDelayPromise = heap.GetTypeByName("System.Threading.Tasks.Task+DelayPromise");
            typeQueueUserWorkItemCallback = heap.GetTypeByName("System.Threading.QueueUserWorkItemCallback");
            fieldCallback    = typeQueueUserWorkItemCallback.GetFieldByName("callback");
            typeWaitCallback = heap.GetTypeByName("System.Threading.WaitCallback");
        }
コード例 #16
0
ファイル: Profiler.cs プロジェクト: VE-2016/VE-2016
        public static void Profile(ClrRuntime runtime)
        {
            {
                foreach (ClrThread thread in runtime.Threads)
                {
                    Console.WriteLine("Thread {0:x}:", thread.OSThreadId);

                    foreach (ClrStackFrame frame in thread.StackTrace)
                    {
                        if (frame.Kind == ClrStackFrameType.Runtime)
                        {
                            Console.WriteLine("{0,12:x} {1,12:x} {2}", frame.InstructionPointer, frame.StackPointer, frame.DisplayString);
                        }
                        else
                        {
                            FileAndLineNumber info = frame.GetSourceLocation();
                            Console.WriteLine("{0,12:x} {1,12:x} {2} [{3} @ {4}]", frame.InstructionPointer, frame.StackPointer, frame.DisplayString, info.File, info.Line);
                        }
                    }
                }
            }
        }
コード例 #17
0
        public IEnumerable <ClrObject> EnumerateObjectsFromSource([NotNull] ClrRuntime runtime)
        {
            Type classCarryingConfig;

            string[] fieldNames;

            if (this.IsOldSitecore(runtime))
            {
                classCarryingConfig = typeof(Configuration.Factory);

                fieldNames = new[] { "configuration" };
            }
            else
            {
                classCarryingConfig = typeof(Configuration.ConfigReader);
                fieldNames          = new[] { "config" };
            }

            var enumartor = new StaticFieldValuesEnumerator(classCarryingConfig.FullName, fieldNames);

            return(enumartor.EnumerateObjectsFromSource(runtime));
        }
コード例 #18
0
        private static void ShowConcurrentQueue(ClrRuntime runtime, ulong address, bool showItemType)
        {
            var     heap = runtime.Heap;
            ClrType t    = heap.GetObjectType(address);

            if (t == null)
            {
                Console.WriteLine("this is not a heap object");
                return;
            }

            try
            {
                // different implementations between .NET Core and .NET Framework
                var helper = new ClrMDHelper(runtime);
                var cq     = heap.GetProxy(address);
                int count  = 0;
                foreach (var item in ClrMDHelper.EnumerateConcurrentQueue(cq, helper.IsNetCore()))
                {
                    count++;
                    var itemAddress = (ulong)item;
                    var type        = heap.GetObjectType(itemAddress);
                    var typeName    = (type == null) ? "?" : type.Name;
                    if (showItemType)
                    {
                        Console.WriteLine($"{count,4} - <link cmd =\"!do {itemAddress:X}\">0x{itemAddress:X16}</link> | {typeName}");
                    }
                    else
                    {
                        Console.WriteLine($"{count,4} - <link cmd =\"!do {itemAddress:X}\">0x{itemAddress:X16}</link>");
                    }
                }
                //Console.WriteLine("---------------------------------------------" + Environment.NewLine + $"{count} items");
            }
            catch (NullReferenceException)
            {
                Console.WriteLine("this is not a ConcurrentQueue");
            }
        }
コード例 #19
0
        public static void OnDumpConcurrentQueue(ClrRuntime runtime, string args)
        {
            // parse the command argument
            if (string.IsNullOrEmpty(args))
            {
                Console.WriteLine("Missing address of a ConcurrentQueue");
                return;
            }

            var arguments = args.Split(' ');
            var address   = arguments[0];

            if (address.StartsWith("0x"))
            {
                // remove "0x" for parsing
                address = address.Substring(2).TrimStart('0');
            }

            // remove the leading 0000 that WinDBG often add in 64 bit
            address = address.TrimStart('0');

            if (!ulong.TryParse(address, System.Globalization.NumberStyles.HexNumber,
                                System.Globalization.CultureInfo.InvariantCulture, out var reference))
            {
                Console.WriteLine("numeric address value expected");
                return;
            }

            // check parameters
            // -t: show item type
            //
            var showItemType = false;

            if (arguments.Length > 1)
            {
                showItemType = arguments.Any(arg => arg == "-t");
            }
            ShowConcurrentQueue(runtime, reference, showItemType);
        }
コード例 #20
0
        public void EETypeTest()
        {
            using DataTarget dt = TestTargets.AppDomains.LoadFullDump();
            ClrRuntime runtime = dt.ClrVersions.Single().CreateRuntime();
            ClrHeap    heap    = runtime.Heap;

            HashSet <ulong> methodTables = (from obj in heap.EnumerateObjectAddresses()
                                            let type = heap.GetObjectType(obj)
                                                       where !type.IsFree
                                                       select heap.GetMethodTable(obj)).Unique();

            Assert.DoesNotContain(0ul, methodTables);

            foreach (ulong mt in methodTables)
            {
                ClrType type    = heap.GetTypeByMethodTable(mt);
                ulong   eeclass = heap.GetEEClassByMethodTable(mt);
                Assert.NotEqual(0ul, eeclass);

                Assert.NotEqual(0ul, heap.GetMethodTableByEEClass(eeclass));
            }
        }
コード例 #21
0
ファイル: PdbTests.cs プロジェクト: zforks/KeeThief
        public void PdbSourceLineTest()
        {
            using (DataTarget dt = TestTargets.NestedException.LoadFullDump())
            {
                ClrRuntime runtime = dt.ClrVersions.Single().CreateRuntime();
                ClrThread  thread  = runtime.GetMainThread();

                HashSet <int> sourceLines = new HashSet <int>();
                using (PdbReader reader = new PdbReader(TestTargets.NestedException.Pdb))
                {
                    Assert.IsTrue(TestTargets.NestedException.Source.Equals(reader.Sources.Single().Name, StringComparison.OrdinalIgnoreCase));

                    var functions = from frame in thread.StackTrace
                                    where frame.Kind != ClrStackFrameType.Runtime
                                    select reader.GetFunctionFromToken(frame.Method.MetadataToken);

                    foreach (PdbFunction function in functions)
                    {
                        PdbSequencePointCollection sourceFile = function.SequencePoints.Single();

                        foreach (int line in sourceFile.Lines.Select(l => l.LineBegin))
                        {
                            sourceLines.Add(line);
                        }
                    }
                }


                int curr = 0;
                foreach (var line in File.ReadLines(TestTargets.NestedException.Source))
                {
                    curr++;
                    if (line.Contains("/* seq */"))
                    {
                        Assert.IsTrue(sourceLines.Contains(curr));
                    }
                }
            }
        }
コード例 #22
0
        public static ClrAppDomain[] GetDomains(ClrRuntime Runtime)
        {
            ClrAppDomain system = Runtime.SystemDomain;
            ClrAppDomain shared = Runtime.SharedDomain;

            /*
             * ulong systemDomain = 0;
             * ulong sharedDomain = 0;
             * GetSystemAndSharedAddress(Runtime, out systemDomain, out sharedDomain);
             *
             * ClrAppDomain system = RunMethod(Runtime, "InitDomain", systemDomain) as ClrAppDomain ;
             * ClrAppDomain shared = RunMethod(Runtime, "InitDomain", sharedDomain) as ClrAppDomain;
             */
            List <ClrAppDomain> domains = new List <ClrAppDomain>();

            domains.Add((ClrAppDomain)system);


            domains.Add((ClrAppDomain)shared);
            domains.AddRange(Runtime.AppDomains);
            return(domains.ToArray());
        }
コード例 #23
0
        private IList <BlockingObject> GetAllLocks(ClrRuntime runtime)
        {
            List <BlockingObject> locks = new List <BlockingObject>();

            _logger?.LogTrace("Starting lock walk");
            foreach (var thread in runtime.Threads)
            {
                var blocking = thread.BlockingObjects;
                if (blocking != null)
                {
                    foreach (var lck in blocking)
                    {
                        if (lck.Taken)
                        {
                            locks.Add(lck);
                        }
                    }
                }
            }

            return(locks);
        }
コード例 #24
0
        public virtual HashSet <ulong> GetAliveObjects([NotNull] ClrRuntime runtime)
        {
            var pinnedRoots = this.ExtractRootsFromRuntime(runtime);

            var heap = runtime.GetHeap();
            var uniqueObjectsToStay = HashSetHelper.GetHashSet <ulong>(10 * 1000 * 1000);

            foreach (var pinnedRoot in pinnedRoots)
            {
                var type = heap.GetObjectType(pinnedRoot);
                if (type == null)
                {
                    continue;
                }

                this.EnumerateObjectReferences(pinnedRoot, uniqueObjectsToStay, heap);
            }

            uniqueObjectsToStay.TrimExcess();

            return(uniqueObjectsToStay);
        }
コード例 #25
0
        private bool TryReadMethodPtr(ClrObject obj, [CanBeNull] out ClrMethod methodDescriptor)
        {
            methodDescriptor = null;
            ClrRuntime rn = obj.Type.Heap.Runtime;

            try
            {
                var _methodPtr = (ulong)(long)obj.GetSimpleFld <object>("_methodPtr");
                if (_methodPtr == 0)
                {
                    return(false);
                }
                byte[] commandOpCode = ReadBytes(_methodPtr, rn, 1);

                return((commandOpCode[0] == 0xE9) && TryProcessNearJump(_methodPtr, rn, out methodDescriptor) &&
                       (methodDescriptor != null));
            }
            catch (Exception)
            {
                return(false);
            }
        }
コード例 #26
0
ファイル: GCRootTests.cs プロジェクト: wp442638266/clrmd
        public void ObjectSetAddRemove()
        {
            using DataTarget dataTarget = TestTargets.Types.LoadFullDump();
            using ClrRuntime runtime    = dataTarget.ClrVersions.Single().CreateRuntime();
            ClrHeap heap = runtime.Heap;

            ObjectSet hash = new ObjectSet(heap);

            foreach (ulong obj in heap.EnumerateObjects())
            {
                Assert.False(hash.Contains(obj));
                hash.Add(obj);
                Assert.True(hash.Contains(obj));
            }

            foreach (ulong obj in heap.EnumerateObjects())
            {
                Assert.True(hash.Contains(obj));
                hash.Remove(obj);
                Assert.False(hash.Contains(obj));
            }
        }
コード例 #27
0
        public static ulong[] GetDomainsAddr(ClrRuntime runtime, ulong Address)
        {
            List <ulong> domains = new List <ulong>();

            if (Address == 0)
            {
                return(domains.ToArray());
            }

            foreach (var domain in AdHoc.GetDomains(runtime))
            {
                foreach (var module in domain.Modules)
                {
                    if (module.ImageBase == Address)
                    {
                        domains.Add(module.AssemblyId);
                    }
                }
            }

            return(domains.ToArray());
        }
コード例 #28
0
        public static ulong GetDomainFromMT(ClrRuntime Runtime, ulong MethodTable)
        {
            if (MethodTable == 0)
            {
                return(0);
            }
            object module = RunMethod(Runtime, "GetModuleForMT", MethodTable);

            if (module == null)
            {
                return(0);
            }

            object moduleData = RunMethod(Runtime, "GetModuleData", module);

            if (moduleData == null)
            {
                return(0);
            }
            object assembly = GetMember(moduleData, "Assembly");

            if (assembly == null)
            {
                return(0);
            }
            object assemblyData = RunMethod(Runtime, "GetAssemblyData", 0UL, assembly);

            if (assemblyData == null)
            {
                return(0);
            }
            object domain = GetMember(assemblyData, "ParentDomain");

            if (domain == null)
            {
                return(0);
            }
            return((ulong)domain);
        }
コード例 #29
0
ファイル: TypeTests.cs プロジェクト: WillVan/clrmd
        public void ComponentTypeEventuallyFilledTest()
        {
            // https://github.com/microsoft/clrmd/issues/108
            // Ensure that a previously created type with a erronous null ComponentType eventually
            // gets its ComponentType set.

            using DataTarget dt      = TestTargets.Types.LoadFullDump();
            using ClrRuntime runtime = dt.ClrVersions.Single().CreateRuntime();

            ClrType        fooType = runtime.GetModule(ModuleName).GetTypeByName("Types");
            ClrStaticField list    = fooType.GetStaticFieldByName("s_list");

            Assert.NotNull(list);

            ClrInstanceField itemsField    = list.Type.GetFieldByName("_items");
            ClrElementType   elementType   = itemsField.ElementType;
            ClrType          componentType = itemsField.Type.ComponentType;

            // If this assert fails, remove the test.  This value is null because currently CLR's
            // debugging layer doesn't tell us the component type of an array.  If we eventually
            // fix that issue, we would return a non-null m_array.Type.ComponentType, causing
            // this test to fail but the underlying issue would be fixed.
            Assert.Null(componentType);

            ClrObject itemsObj = list.ReadObject().GetObjectField("_items");

            // Ensure we are looking at the same ClrType
            if (dt.CacheOptions.CacheTypes)
            {
                Assert.Same(itemsField.Type, itemsObj.Type);
            }
            else
            {
                Assert.Equal(itemsField.Type, itemsObj.Type);
            }

            // Assert that we eventually filled in ComponentType after we got a real object for the type
            Assert.NotNull(itemsObj.Type.ComponentType);
        }
コード例 #30
0
        public void NoMethodCachingTest()
        {
            using DataTarget dt              = TestTargets.Types.LoadFullDump();
            dt.CacheOptions.CacheMethods     = false;
            dt.CacheOptions.CacheMethodNames = StringCaching.None;

            using ClrRuntime runtime = dt.ClrVersions.Single().CreateRuntime();


            ClrModule module = runtime.GetModule("sharedlibrary.dll");
            ClrType   type   = module.GetTypeByName("Foo");
            ClrMethod method = type.GetMethod("Bar");

            Assert.NotEqual(0ul, method.MethodDesc);  // Sanity test

            ClrMethod method2 = type.GetMethod("Bar");

            Assert.Equal(method, method2);
            Assert.NotSame(method, method2);


            string signature1 = method.Signature;
            string signature2 = method2.Signature;

            Assert.NotNull(signature1);
            Assert.Equal(signature1, signature2);

            Assert.Equal(signature1, method.Signature);
            Assert.NotSame(signature1, method.Signature);
            Assert.NotSame(method2.Signature, method.Signature);

            // Ensure that we can swap this at runtime and that we get interned strings
            dt.CacheOptions.CacheMethodNames = StringCaching.Intern;

            Assert.NotNull(method.Signature);
            Assert.Same(method2.Signature, method.Signature);
            Assert.Same(method.Signature, string.Intern(method.Signature));
        }
コード例 #31
0
ファイル: ModuleTests.cs プロジェクト: wilvk/dotnet-sos
        public void TestTypeMapRoundTrip()
        {
            using DataTarget dt      = TestTargets.Types.LoadFullDump();
            using ClrRuntime runtime = dt.ClrVersions.Single().CreateRuntime();

            int badTypes = 0;

            foreach (ClrModule module in runtime.EnumerateModules())
            {
                foreach ((ulong mt, int token) in module.EnumerateTypeDefToMethodTableMap())
                {
                    Assert.NotEqual(0, token);
                    Assert.True((token & 0x02000000) == 0x02000000);

                    ClrType type = runtime.GetTypeByMethodTable(mt);
                    if (type == null)
                    {
                        // We really want to Assert.NotNull(type), but it turns out that one type
                        // (System.Runtime.Remoting.Proxies.__TransparentProxy) cannot be constructed because
                        // GetMethodTableData returns null for it.  This is an issue with the dac so we'll
                        // simply count types that are null and assert there's only one

                        badTypes++;

                        continue;
                    }

                    Assert.NotNull(type);

                    ClrType typeFromToken = module.ResolveToken(token);
                    Assert.NotNull(typeFromToken);

                    Assert.Same(type, typeFromToken);
                }
            }

            Assert.True(badTypes <= 1);
        }
コード例 #32
0
ファイル: Program.cs プロジェクト: stjeong/RefOwner
        private static void DumpHeapRefHierachy(ClrRuntime runtime, string typeNameOrAddress, bool detailed, int depth)
        {
            HashSet <ulong> instances = GetObjectListByName(runtime, typeNameOrAddress);

            Console.WriteLine(typeNameOrAddress + ", # of instances: " + instances.Count);

            Dictionary <string, HeapObjectCounter> owners    = GetObjectOwners(runtime, instances);
            List <ObjectHistogramItem>             histogram = new List <ObjectHistogramItem>();

            foreach (var owner in owners)
            {
                ObjectHistogramItem item = new ObjectHistogramItem {
                    Key = owner.Key, Counter = owner.Value
                };
                histogram.Add(item);
            }

            histogram.Sort();

            int count = 0;

            foreach (var item in histogram)
            {
                Console.WriteLine($"{item.Counter.Total} {item.Key}({item.Counter.OwnerCount})");

                if (detailed == true)
                {
                    foreach (var instance in item.Counter)
                    {
                        Console.WriteLine($"\t[{instance.Key:x}, {instance.Value}]");
                    }
                }

                count += item.Counter.Total;
            }

            Console.WriteLine("Total: " + count);
        }
コード例 #33
0
ファイル: ProjectNode.cs プロジェクト: VirtualReality/Libs
		/// <summary>
		/// Parses the specified node.
		/// </summary>
		/// <param name="node">The node.</param>
		public override void Parse(XmlNode node)
		{
			m_Name = Helper.AttributeValue(node, "name", m_Name);
			m_Path = Helper.AttributeValue(node, "path", m_Path);
			m_FilterGroups = Helper.AttributeValue(node, "filterGroups", m_FilterGroups);
            m_Version = Helper.AttributeValue(node, "version", m_Version);
            m_AppIcon = Helper.AttributeValue(node, "icon", m_AppIcon);
            m_ApplicationManifest = Helper.AttributeValue(node, "appmanifest", m_ApplicationManifest);
            m_ConfigFile = Helper.AttributeValue(node, "configFile", m_ConfigFile);
			m_DesignerFolder = Helper.AttributeValue(node, "designerFolder", m_DesignerFolder);
			m_AssemblyName = Helper.AttributeValue(node, "assemblyName", m_AssemblyName);
			m_Language = Helper.AttributeValue(node, "language", m_Language);
			m_Type = (ProjectType)Helper.EnumAttributeValue(node, "type", typeof(ProjectType), m_Type);
			m_Runtime = (ClrRuntime)Helper.EnumAttributeValue(node, "runtime", typeof(ClrRuntime), m_Runtime);
            if(m_useFramework)
                m_Framework = (FrameworkVersion)Helper.EnumAttributeValue(node, "frameworkVersion", typeof(FrameworkVersion), m_Framework);
			
            m_StartupObject = Helper.AttributeValue(node, "startupObject", m_StartupObject);
			m_RootNamespace = Helper.AttributeValue(node, "rootNamespace", m_RootNamespace);
			
            int hash = m_Name.GetHashCode();
 			Guid guidByHash = new Guid(hash, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
			string guid = Helper.AttributeValue(node, "guid", guidByHash.ToString());
			m_Guid = new Guid(guid);

            m_GenerateAssemblyInfoFile = Helper.ParseBoolean(node, "generateAssemblyInfoFile", false);
		    m_DebugStartParameters = Helper.AttributeValue(node, "debugStartParameters", string.Empty);
            
			if(string.IsNullOrEmpty(m_AssemblyName))
			{
				m_AssemblyName = m_Name;
			}

			if(string.IsNullOrEmpty(m_RootNamespace))
			{
				m_RootNamespace = m_Name;
			}

			m_FullPath = m_Path;
			try
			{
				m_FullPath = Helper.ResolvePath(m_FullPath);
			}
			catch
			{
				throw new WarningException("Could not resolve Solution path: {0}", m_Path);
			}

			Kernel.Instance.CurrentWorkingDirectory.Push();
			try
			{
				Helper.SetCurrentDir(m_FullPath);

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

				foreach(XmlNode child in node.ChildNodes)
				{
					IDataNode dataNode = Kernel.Instance.ParseNode(child, this);
					if(dataNode is ConfigurationNode)
					{
						HandleConfiguration((ConfigurationNode)dataNode);
					}
					else if(dataNode is ReferencePathNode)
					{
                        m_ReferencePaths.Add((ReferencePathNode)dataNode);
					}
					else if(dataNode is ReferenceNode)
					{
                        m_References.Add((ReferenceNode)dataNode);
					}
					else if(dataNode is AuthorNode)
					{
                        m_Authors.Add((AuthorNode)dataNode);
					}
					else if(dataNode is FilesNode)
					{
						m_Files = (FilesNode)dataNode;
					}
				}
			}
			finally
			{
				Kernel.Instance.CurrentWorkingDirectory.Pop();
			}
		}
コード例 #34
0
 public NativeAppDomain(ClrRuntime runtime, IList<ClrModule> modules)
 {
     _runtime = runtime;
     _modules = modules;
 }
コード例 #35
0
        /// <summary>
        /// Parses the specified node.
        /// </summary>
        /// <param name="node">The node.</param>
        public override void Parse(XmlNode node)
        {
            m_Name = Helper.AttributeValue(node, "name", m_Name);
            m_Path = Helper.AttributeValue(node, "path", m_Path);
            m_FilterGroups = Helper.AttributeValue(node, "filterGroups", m_FilterGroups);
            m_AppIcon = Helper.AttributeValue(node, "icon", m_AppIcon);
            m_DesignerFolder = Helper.AttributeValue(node, "designerFolder", m_DesignerFolder);
            m_AssemblyName = Helper.AttributeValue(node, "assemblyName", m_AssemblyName);
            m_Language = Helper.AttributeValue(node, "language", m_Language);
            m_Type = (ProjectType)Helper.EnumAttributeValue(node, "type", typeof(ProjectType), m_Type);
            m_Runtime = (ClrRuntime)Helper.EnumAttributeValue(node, "runtime", typeof(ClrRuntime), m_Runtime);
            m_StartupObject = Helper.AttributeValue(node, "startupObject", m_StartupObject);
            m_RootNamespace = Helper.AttributeValue(node, "rootNamespace", m_RootNamespace);

            int hash = m_Name.GetHashCode();

            m_Guid = new Guid( hash, 0, 0, 0, 0, 0, 0,0,0,0,0 );

            m_GenerateAssemblyInfoFile = Helper.ParseBoolean(node, "generateAssemblyInfoFile", false);

            if(m_AssemblyName == null || m_AssemblyName.Length < 1)
            {
                m_AssemblyName = m_Name;
            }

            if(m_RootNamespace == null || m_RootNamespace.Length < 1)
            {
                m_RootNamespace = m_Name;
            }

            m_FullPath = m_Path;
            try
            {
                m_FullPath = Helper.ResolvePath(m_FullPath);
            }
            catch
            {
                throw new WarningException("Could not resolve Solution path: {0}", m_Path);
            }

            Kernel.Instance.CurrentWorkingDirectory.Push();
            try
            {
                Helper.SetCurrentDir(m_FullPath);

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

                foreach(XmlNode child in node.ChildNodes)
                {
                    IDataNode dataNode = Kernel.Instance.ParseNode(child, this);
                    if(dataNode is ConfigurationNode)
                    {
                        HandleConfiguration((ConfigurationNode)dataNode);
                    }
                    else if(dataNode is ReferencePathNode)
                    {
                        m_ReferencePaths.Add(dataNode);
                    }
                    else if(dataNode is ReferenceNode)
                    {
                        m_References.Add(dataNode);
                    }
                    else if(dataNode is FilesNode)
                    {
                        m_Files = (FilesNode)dataNode;
                    }
                }
            }
            finally
            {
                Kernel.Instance.CurrentWorkingDirectory.Pop();
            }
        }