Example #1
0
        private ThreadPoolItem GetThreadPoolItem(ClrObject item)
        {
            ClrType itemType = item.Type;

            if (itemType.Name == "System.Threading.Tasks.Task")
            {
                return(GetTask(item));
            }

            if (
                (string.CompareOrdinal(itemType.Name, "System.Threading.QueueUserWorkItemCallback") == 0) ||
                // new to .NET Core
                (string.CompareOrdinal(itemType.Name, "System.Threading.QueueUserWorkItemCallbackDefaultContext") == 0)
                )
            {
                return(GetQueueUserWorkItemCallback(item));
            }

            // create a raw information
            ThreadPoolItem tpi = new ThreadPoolItem()
            {
                Type       = ThreadRoot.Raw,
                Address    = item.Address,
                MethodName = itemType.Name
            };

            return(tpi);
        }
Example #2
0
        public void HeapCachedEnumerationMatches()
        {
            // Simply test that we can enumerate the heap.
            using (DataTarget dt = TestTargets.Types.LoadFullDump())
            {
                ClrRuntime runtime = dt.ClrVersions.Single().CreateRuntime();
                ClrHeap    heap    = runtime.Heap;

                List <ClrObject> expectedList = new List <ClrObject>(heap.EnumerateObjects());

                heap.CacheHeap(CancellationToken.None);
                Assert.True(heap.IsHeapCached);
                List <ClrObject> actualList = new List <ClrObject>(heap.EnumerateObjects());

                Assert.True(actualList.Count > 0);
                Assert.Equal(expectedList.Count, actualList.Count);

                for (int i = 0; i < actualList.Count; i++)
                {
                    ClrObject expected = expectedList[i];
                    ClrObject actual   = actualList[i];

                    Assert.True(expected == actual);
                    Assert.Equal(expected, actual);
                }
            }
        }
        public static IEnumerable <(ClrStaticField Field, ClrObject Object)> EnumerateAllStaticVariables(this ClrRuntime runtime)
        {
            if (runtime is null)
            {
                throw new ArgumentNullException(nameof(runtime));
            }

            foreach (ClrModule module in runtime.EnumerateModules())
            {
                foreach ((ulong mt, int _) in module.EnumerateTypeDefToMethodTableMap())
                {
                    ClrType?type = runtime.GetTypeByMethodTable(mt);

                    if (type is null)
                    {
                        continue;
                    }

                    foreach (ClrStaticField field in type.StaticFields)
                    {
                        if (field.IsObjectReference)
                        {
                            foreach (ClrAppDomain domain in runtime.AppDomains)
                            {
                                ClrObject obj = field.ReadObject(domain);
                                if (obj.IsValid && !obj.IsNull)
                                {
                                    yield return(field, obj);
                                }
                            }
                        }
                    }
                }
            }
        }
Example #4
0
 public bool TrySetMember(
     string memberName,
     Object value)
 {
     Operators.SetVariable(Context, null, memberName, ClrObject.WrapDynamic(value));
     return(true);
 }
Example #5
0
        private void AssertPathIsCorrect(ClrHeap heap, ClrObject[] path, ulong source, ulong target)
        {
            Assert.NotNull(path);
            Assert.True(path.Length > 0);

            ClrObject first = path.First();

            Assert.Equal(source, first.Address);

            for (int i = 0; i < path.Length - 1; i++)
            {
                ClrObject curr = path[i];
                Assert.Equal(curr.Type, heap.GetObjectType(curr.Address));

                List <ulong> refs = new List <ulong>();
                curr.Type.EnumerateRefsOfObject(curr.Address, (obj, offs) => refs.Add(obj));

                ulong next = path[i + 1].Address;
                Assert.Contains(next, refs);
            }

            ClrObject last = path.Last();

            Assert.Equal(last.Type, heap.GetObjectType(last.Address));
            Assert.Equal(target, last.Address);
        }
Example #6
0
        private void AssertPathIsCorrect(ClrHeap heap, ClrObject[] path, ulong source, ulong target)
        {
            Assert.NotNull(path);
            Assert.True(path.Length > 0);

            ClrObject first = path.First();

            Assert.Equal(source, first.Address);

            for (int i = 0; i < path.Length - 1; i++)
            {
                ClrObject curr = path[i];
                Assert.Equal(curr.Type, heap.GetObjectType(curr.Address));

                IEnumerable <ClrObject> refs = curr.EnumerateObjectReferences();

                ClrObject next = path[i + 1];
                Assert.Contains(next, refs);
            }

            ClrObject last = path.Last();

            Assert.Equal(last.Type, heap.GetObjectType(last.Address));
            Assert.Equal(target, last.Address);
        }
Example #7
0
        public object Read(ClrObject obj, string fldName)
        {
            ClrObject guidObject = obj.GetValueFld(fldName, false);

            // TOOD: Ensure this code works.
            return(ClrObjectValuesReader.ReadGuidValue(guidObject));
        }
Example #8
0
 public ClrmdRefCountHandle(ClrAppDomain parent, ulong address, ClrObject obj, uint refCount)
 {
     Address        = address;
     Object         = obj;
     AppDomain      = parent;
     ReferenceCount = refCount;
 }
Example #9
0
        public void FieldNameAndValueTests()
        {
            // TODO: test reading structs from instance/static fields
            using DataTarget dt      = TestTargets.Types.LoadFullDump();
            using ClrRuntime runtime = dt.ClrVersions.Single().CreateRuntime();
            ClrHeap heap = runtime.Heap;

            ClrAppDomain domain = runtime.AppDomains.Single();

            ClrType   fooType = runtime.GetModule("sharedlibrary.dll").GetTypeByName("Foo");
            ClrObject obj     = runtime.GetModule(ModuleName).GetTypeByName("Types").GetStaticFieldByName("s_foo").ReadObject(domain);

            if (dt.CacheOptions.CacheTypes)
            {
                Assert.Same(fooType, obj.Type);
                Assert.Same(fooType, heap.GetObjectType(obj.Address));
            }
            else
            {
                Assert.Equal(fooType, obj.Type);
                Assert.Equal(fooType, heap.GetObjectType(obj.Address));
            }

            TestFieldNameAndValue(fooType, obj, "i", 42);
            TestFieldNameAndValue(fooType, obj, "s", "string");
            TestFieldNameAndValue(fooType, obj, "b", true);
            TestFieldNameAndValue(fooType, obj, "f", 4.2f);
            TestFieldNameAndValue(fooType, obj, "d", 8.4);
        }
Example #10
0
        public void IntegerObjectClrType()
        {
            using DataTarget dt      = TestTargets.Types.LoadFullDump();
            using ClrRuntime runtime = dt.ClrVersions.Single().CreateRuntime();
            ClrHeap      heap   = runtime.Heap;
            ClrAppDomain domain = runtime.AppDomains.Single();

            ClrModule      module    = runtime.GetModule(ModuleName);
            ClrType        typesType = module.GetTypeByName("Types");
            ClrStaticField field     = typesType.GetStaticFieldByName("s_i");

            ClrObject obj = field.ReadObject(domain);

            Assert.False(obj.IsNull);

            ClrType type = obj.Type;

            Assert.NotNull(type);

            Assert.True(type.IsPrimitive);
            Assert.False(type.IsObjectReference);
            Assert.True(type.IsValueType);

            var fds = obj.Type.Fields;

            Assert.True(obj.IsBoxedValue);
            int value = obj.ReadBoxedValue <int>();

            Assert.Equal(42, value);

            Assert.Contains(obj.Address, heap.EnumerateObjects().Select(a => a.Address));
        }
Example #11
0
        public void EnumerateMethodTableTest()
        {
            using DataTarget dt      = TestTargets.AppDomains.LoadFullDump();
            using ClrRuntime runtime = dt.ClrVersions.Single().CreateRuntime();
            ClrHeap heap = runtime.Heap;

            ClrObject[] fooObjects = (from obj in heap.EnumerateObjects()
                                      where obj.Type.Name == "Foo"
                                      select obj).ToArray();

            // There are exactly two Foo objects in the process, one in each app domain.
            // They will have different method tables.
            Assert.Equal(2, fooObjects.Length);

            ClrType fooType  = heap.GetObjectType(fooObjects[0]);
            ClrType fooType2 = heap.GetObjectType(fooObjects[1]);

            Assert.NotSame(fooType, fooType2);

            ClrObject appDomainsFoo = fooObjects.Where(o => o.Type.Module.AppDomain.Name.Contains("AppDomains")).Single();
            ClrObject nestedFoo     = fooObjects.Where(o => o.Type.Module.AppDomain.Name.Contains("Second")).Single();

            Assert.NotSame(appDomainsFoo.Type, nestedFoo.Type);

            ulong nestedExceptionFooMethodTable = dt.DataReader.ReadPointer(nestedFoo.Address);
            ulong appDomainsFooMethodTable      = dt.DataReader.ReadPointer(appDomainsFoo.Address);

            // These are in different domains and should have different type handles:
            Assert.NotEqual(nestedExceptionFooMethodTable, appDomainsFooMethodTable);

            // The MethodTable returned by ClrType should always be the method table that lives in the "first"
            // AppDomain (in order of ClrAppDomain.Id).
            Assert.Equal(appDomainsFooMethodTable, fooType.MethodTable);
            Assert.Equal(nestedExceptionFooMethodTable, fooType2.MethodTable);
        }
Example #12
0
        private static void ChainStateMachinesBasedOnJointableTasks(DebuggerContext context, List <AsyncStateMachine> allStateMachines)
        {
            foreach (AsyncStateMachine?stateMachine in allStateMachines)
            {
                if (stateMachine.Previous is null)
                {
                    try
                    {
                        ClrObject joinableTask = stateMachine.StateMachine.TryGetObjectField("<>4__this");
                        ClrObject wrappedTask  = joinableTask.TryGetObjectField("wrappedTask");
                        if (!wrappedTask.IsNull)
                        {
                            AsyncStateMachine?previousStateMachine = allStateMachines
                                                                     .FirstOrDefault(s => s.Task.Address == wrappedTask.Address);
                            if (previousStateMachine is object && stateMachine != previousStateMachine)
                            {
                                stateMachine.Previous     = previousStateMachine;
                                previousStateMachine.Next = stateMachine;
                                previousStateMachine.DependentCount++;
                            }
                        }
                    }
#pragma warning disable CA1031 // Do not catch general exception types
                    catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
                    {
                        context.Output.WriteLine($"Fail to fix continuation of state {stateMachine.StateMachine.Address:x} Error: {ex.Message}");
                    }
                }
            }
        }
Example #13
0
        private static void ChainStateMachinesBasedOnTaskContinuations(DebuggerContext context, Dictionary <ulong, AsyncStateMachine> knownStateMachines)
        {
            foreach (AsyncStateMachine?stateMachine in knownStateMachines.Values)
            {
                ClrObject taskObject = stateMachine.Task;
                try
                {
                    while (!taskObject.IsNull)
                    {
                        // 3 cases in order to get the _target:
                        // 1. m_continuationObject.m_action._target
                        // 2. m_continuationObject._target
                        // 3. m_continuationObject.m_task.m_stateObject._target
                        ClrObject continuationObject = taskObject.TryGetObjectField("m_continuationObject");
                        if (continuationObject.IsNull)
                        {
                            break;
                        }

                        ChainStateMachineBasedOnTaskContinuations(knownStateMachines, stateMachine, continuationObject);

                        taskObject = continuationObject;
                    }
                }
#pragma warning disable CA1031 // Do not catch general exception types
                catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
                {
                    context.Output.WriteLine($"Fail to fix continuation of state {stateMachine.StateMachine.Address:x} Error: {ex.Message}");
                }
            }
        }
 public DataSetVisual(ClrObject dataset)
 {
     m_tables = (from table in (ClrObject)dataset.Dynamic.tableCollection._list._items
                 where !table.IsNull()
                 orderby(string) table["tableName"]
                 select table).ToList();
 }
Example #15
0
        /// <summary>
        /// Invokes the subscribed recursions.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="clrObject">The color object.</param>
        protected virtual void InvokeSubscribedRecursions(IClrObjMappingModel value, ClrObject clrObject)
        {
            if (RecursionCheckerDisabler.IsActive || !this.recursionCallBacks.ContainsKey(clrObject.Address))
            {
                return;
            }

            if (value != null)
            {
                Delegate[] invocationList = this.recursionCallBacks[clrObject.Address].GetInvocationList();
                foreach (Delegate @delegate in invocationList)
                {
                    try
                    {
                        @delegate.DynamicInvoke(value);
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError("{0} error during {1} setting for {2} object", ex.ToString(), value.GetType().Name,
                                         clrObject.Address.ToString("x8"));
                    }
                }
            }

            this.recursionCallBacks.Remove(clrObject.Address);
        }
Example #16
0
        public static EventHandler RunSilverlightApplication(System.Windows.Controls.Canvas c, string source)
        {
            ApplicationContext app_context = ApplicationContext.Default;

            // try to preload configuration (to prevent exceptions during InitApplication)
            Configuration.Load(app_context);
            ApplicationConfiguration app_config = Configuration.Application;


            string url       = HtmlPage.Document.DocumentUri.AbsoluteUri;
            int    lastSlash = url.Replace('\\', '/').LastIndexOf('/');

            app_config.Compiler.SourceRoot = new FullPath(url.Substring(0, lastSlash), false);

            int    sourcelastSlash = source.Replace('\\', '/').LastIndexOf('/');
            string sourceRelPath   = source.Substring(lastSlash + 1);



            // Silverlight language features
            app_config.Compiler.LanguageFeatures = LanguageFeatures.PhpClr;

            // ..
            ScriptContext context = InitApplication(app_context);

            Debug.Fail("Update versions below!");
            ConfigurationContext.AddLibrary("mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e", null, "");
            ConfigurationContext.AddLibrary("System, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e", null, "");
            ConfigurationContext.AddLibrary("System.Windows, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e", null, "");
            ConfigurationContext.AddLibrary("System.Net, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e", null, "");
            //ConfigurationContext.AddLibrary("System.SilverLight, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", null, "");
            //ConfigurationContext.AddLibrary("agclr, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", null, "");

            ConfigurationContext.AddLibrary("PhpNetClassLibrary, Version=3.0.0.0, Culture=neutral, PublicKeyToken=4af37afe3cde05fb", null, "");

            //
            Configuration.Application.Compiler.Debug = true;

            // ..
            Dictionary <string, object> vars = new Dictionary <string, object>();

            currentContext.AutoGlobals.Canvas.Value = ClrObject.Wrap(c);
            currentContext.AutoGlobals.Addr.Value   = ClrObject.Wrap(app_config.Compiler.SourceRoot.ToString());

            //Operators.SetVariableRef(currentContext, vars, "_CANVAS", Operators.GetItemRef("_CANVAS", ref currentContext.AutoGlobals.Globals.value));
            //Operators.SetVariable(currentContext, vars, "_CANVAS", ClrObject.Wrap(c));


            context.DynamicInclude(source, sourceRelPath, vars, null, null, InclusionTypes.RunSilverlight);

            return(new EventHandler(delegate(object sender, EventArgs e)
            {
                if (context.ResolveFunction("OnLoad", null, true) != null)
                {
                    PhpCallback load = new PhpCallback("OnLoad");
                    load.Invoke(sender, e);
                }
            }));
        }
Example #17
0
 public ClrStackRoot(ulong address, ClrObject obj, ClrStackFrame stackFrame, bool interior, bool pinned)
 {
     Address    = address;
     Object     = obj;
     StackFrame = stackFrame;
     IsInterior = interior;
     IsPinned   = pinned;
 }
Example #18
0
        public IEnumerable<ClrObject> GetReferenceBy(ClrObject o)
        {
            ParentList parents;
            if (!m_referenceMap.TryGetValue(o.Address, out parents))
                return new ClrObject[0];

            return parents.Start.Enumerate();
        }
Example #19
0
 public IDListMappingModel GetModel(ClrObject obj)
 {
     return(new IDListMappingModel
     {
         Obj = obj,
         Collection = Read(obj)
     });
 }
 public Pair(ClrObject clrObj, object runtimeObject)
 {
     this.ClrObj        = clrObj;
     this.RuntimeObject = runtimeObject;
     this.FieldInfo     = GetFields(runtimeObject.GetType());
     Errors             = new List <string>();
     Warnings           = new List <string>();
 }
        /// <summary>
        /// Gets the <see cref="ClrThread"/> by managed ThreadID specified in <paramref name="threadObj"/>.
        /// </summary>
        /// <param name="threadObj">The thread object.</param>
        /// <returns></returns>
        public static ClrThread GetByAddress([ClrObjAndTypeNotEmpty] ClrObject threadObj)
        {
            ClrAssert.ObjectNotNullTypeNotEmpty(threadObj);
            var tp = threadObj.Type;
            var id = threadObj.GetInt32Fld("m_ManagedThreadId");

            return(tp.Heap.Runtime.Threads.FirstOrDefault(t => t.ManagedThreadId == id));
        }
        private TreeNode GetNode(ClrObject o1)
        {
            var      o  = new ObjData(o1);
            TreeNode tn = new TreeNode(o1.Type.ToString(), new TreeNode[] { new TreeNode("Loading...") });

            tn.Tag = o;
            return(tn);
        }
Example #23
0
        public static bool HasSameNameAutoProperty(this ClrObject clrObject, [NotNull] FieldInfo autoPropFldInfo)
        {
            Assert.ArgumentNotNull(autoPropFldInfo, "fieldInfo");

            var expected = MemoryDiagnostics.StringUtil.ProduceAutoPropertyName(autoPropFldInfo.Name);

            return(clrObject.HasSameNameField(expected));
        }
Example #24
0
        public void IsNull_WhenHasAddress_ReturnsFalse([Frozen] ulong objectAddress, ClrObject clrObject)
        {
            // Act
            var isNull = clrObject.IsNull;

            // Assert
            isNull.Should().BeFalse();
        }
Example #25
0
        public static IEnumerable <ClrGraphNode> CreateForChildren(ClrObject startObject)
        {
            var instance  = new ClrGraph();
            var firstNode = new ClrGraphNode(instance, startObject);

            instance.StartObject = firstNode;
            return(firstNode.Children);
        }
        public static TimeSpan Read(ClrObject obj)
        {
            ClrInstanceField dateDataField = obj.Type.GetFieldByName("_ticks");
            var rawDateTimeData            = (long)dateDataField.GetValue(obj.Address, true);
            var ts = new TimeSpan(rawDateTimeData);

            return(ts);
        }
 public override object GetValue(ClrObject o)
 {
     return(new ListVisual()
     {
         Count = o.Dynamic._size,
         Items = o.Dynamic._items.Take(o.Dynamic._size),
     });
 }
Example #28
0
        public static ClrGraphNode CreateForSelf(ClrObject startObject)
        {
            var instance  = new ClrGraph();
            var firstNode = new ClrGraphNode(instance, startObject);

            instance.StartObject = firstNode;
            return(firstNode);
        }
Example #29
0
        /// <summary>
        /// This only works starting from .NET 5
        /// https://github.com/dotnet/runtime/issues/11157
        /// TODO: compute the field from the property name
        /// </summary>
        /// <param name="allocatorObject"></param>
        /// <returns></returns>
        public string GetAllocatorName(ClrObject allocatorObject)
        {
            // allocatorObject is AssemblyLoadContext or a derived class
            // this means it has a property called "Name"
            var value = allocatorObject.ReadObjectField("_name");

            return(value.GetStringValue());
        }
Example #30
0
        /// <summary>
        /// AssemblyLoadContextAddress
        /// PR: https://github.com/microsoft/clrmd/pull/776
        /// Discussion: https://github.com/dotnet/runtime/issues/11157
        /// </summary>
        /// <param name="clrObject"></param>
        /// <returns></returns>
        private ClrObject GetAllocatorObject(ClrObject clrObject)
        {
            var assemblyLoadContextAddress = clrObject.Type.AssemblyLoadContextAddress;
            //if (assemblyLoadContextAddress != 0) Debugger.Break();
            var alc = _clrRuntime.Heap.GetObject(assemblyLoadContextAddress);

            return(alc);
        }
Example #31
0
 private static void ShowObject(ClrHeap heap, ClrObject clrObject, string indent)
 {
     Console.WriteLine($"{indent} {clrObject.Type.Name} ({clrObject.HexAddress}) - gen{heap.GetGeneration(clrObject.Address)}");
     foreach (var reference in clrObject.EnumerateObjectReferences())
     {
         ShowObject(heap, reference, "  ");
     }
 }
Example #32
0
        public static PhpResource ConnectShared(
            ClrObject clrConnection,
            string connectionString)
        {
            bool success;
            PhpMyDbConnection connection = (PhpMyDbConnection)manager.OpenConnection(connectionString, false, MySqlConfiguration.Global.MaxConnections, out success);

            if (!success) {
                if (connection != null) {
                    UpdateConnectErrorInfo(connection);
                    connection = null;
                }
                return null;
            }

            // Set the shared connection
            connection.SetSharedConnection(clrConnection.RealObject as IDbConnection);
            return connection;
        }
Example #33
0
 public IEnumerable<ClrObject> GetReferenceBy(ClrObject o)
 {
     return m_referenceMap.GetReferenceBy(o);
 }
Example #34
0
 public Node(ClrObject o, Node next)
 {
     Value = o;
     Next = next;
 }