示例#1
0
    public static void PrintDict(ClrRuntime runtime, string args)
    {
        bool  failed = false;
        ulong obj    = 0;

        try
        {
            obj    = Convert.ToUInt64(args, 16);
            failed = obj == 0;
        }
        catch (ArgumentException)
        {
            failed = true;
        }

        if (failed)
        {
            Console.WriteLine("Usage: !PrintDict <dictionary>");
            return;
        }

        ClrHeap heap = runtime.GetHeap();
        ClrType type = heap.GetObjectType(obj);

        if (type == null)
        {
            Console.WriteLine("Invalid object {0:X}", obj);
            return;
        }

        if (!type.Name.StartsWith("System.Collections.Generic.Dictionary"))
        {
            Console.WriteLine("Error: Expected object {0:X} to be a dictionary, instead it's of type '{1}'.");
            return;
        }

        // Get the entries field.
        ulong entries = type.GetFieldValue(obj, "entries");

        if (entries == 0)
        {
            return;
        }

        ClrType          entryArray     = heap.GetObjectType(entries);
        ClrType          arrayComponent = entryArray.ComponentType;
        ClrInstanceField hashCodeField  = arrayComponent.GetFieldByName("hashCode");
        ClrInstanceField keyField       = arrayComponent.GetFieldByName("key");
        ClrInstanceField valueField     = arrayComponent.GetFieldByName("value");

        Console.WriteLine("{0,8} {1,16} : {2}", "hash", "key", "value");
        int len = entryArray.GetArrayLength(entries);

        for (int i = 0; i < len; ++i)
        {
            ulong arrayElementAddr = entryArray.GetArrayElementAddress(entries, i);

            int    hashCode = (int)hashCodeField.GetValue(arrayElementAddr, true);
            object key      = keyField.GetValue(arrayElementAddr, true);
            object value    = valueField.GetValue(arrayElementAddr, true);

            key   = Format(heap, key);
            value = Format(heap, value);

            bool skip = key is ulong && (ulong)key == 0 && value is ulong && (ulong)value == 0;

            if (!skip)
            {
                Console.WriteLine("{0,8:X} {1,16} : {2}", hashCode, key, value);
            }
        }
    }