예제 #1
0
        public static bool WriteDump(int pid, int threadWithExceptionId, string filename,  DumpOptions options, bool hasException)
        {
            using (FileStream dumpFile = File.OpenWrite(filename))
            {
                SafeHandle fileHandle = dumpFile.SafeFileHandle;
                //Process currentProcess = Process.GetCurrentProcess();
                Process currentProcess = Process.GetProcessById(pid);
                IntPtr currentProcessHandle = currentProcess.Handle;
                uint currentProcessId = (uint)currentProcess.Id;

                MiniDumpExceptionInformation exp;
                exp.ThreadId = threadWithExceptionId;//GetCurrentThreadId();
                exp.ClientPointers = false;
                exp.ExceptionPointers = IntPtr.Zero;

                if (hasException)
                {
                    exp.ExceptionPointers = System.Runtime.InteropServices.Marshal.GetExceptionPointers();
                }

                bool bRet = false;
                if (exp.ExceptionPointers == IntPtr.Zero)
                {
                    bRet = MiniDumpWriteDump(currentProcessHandle, currentProcessId, fileHandle, (uint)options, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
                }
                else
                {
                    bRet = MiniDumpWriteDump(currentProcessHandle, currentProcessId, fileHandle, (uint)options, ref exp, IntPtr.Zero, IntPtr.Zero);
                }

                return bRet;
            }
        }
예제 #2
0
    public static string Dump <T>(ref T value, DumpOptions options, InspectorOptions options2)
    {
        switch (options)
        {
        case DumpOptions.Info:
            //

            var addrTable = new ConsoleTable("Addresses", "");

            var addr = Mem.AddressOf(ref value);
            addrTable.AddRow("Address", addr);

            if (Mem.TryGetAddressOfHeap(value, out var heap))
            {
                addrTable.AddRow("Address (heap)", heap);
            }

            addrTable.Write(ConsoleTableFormat.Minimal);

            //

            var infoTable = new ConsoleTable("Sizes", "");

            infoTable.AddRow("Intrinsic", Mem.SizeOf <T>());
            infoTable.AddRow("Auto", Mem.SizeOf(value, SizeOfOptions.Auto));

            infoTable.Write(ConsoleTableFormat.Minimal);

            //

            var propTable = new ConsoleTable("Runtime info", "");

            propTable.AddRow("Pinnable", RuntimeProperties.IsPinnable(value));
            propTable.AddRow("Blittable", RuntimeProperties.IsBlittable(value));
            propTable.AddRow("Boxed", RuntimeProperties.IsBoxed(value));
            propTable.AddRow("Nil", RuntimeProperties.IsDefault(value));
            propTable.AddRow("Uninitialized", RuntimeProperties.IsNullMemory(value));


            propTable.AddRow("In GC heap", GCHeap.IsHeapPointer(Mem.AddressOfData(ref value)));

            return(propTable.ToMinimalString());

        case DumpOptions.Sizes:
            var layoutTable = new ConsoleTable("Size Type", "Value");

            var options1 = Enum.GetValues <SizeOfOptions>().ToList();

            options1.Remove(SizeOfOptions.Heap);


            foreach (var option in options1)
            {
                var sizeOf = Mem.SizeOf(value, option);

                if (sizeOf == Native.INVALID)
                {
                    continue;
                }

                layoutTable.AddRow(Enum.GetName(option), sizeOf);
            }

            var mt = value.GetMetaType();

            if (!mt.RuntimeType.IsValueType)
            {
                layoutTable.AddRow(nameof(SizeOfOptions.Heap), Mem.SizeOf(value, SizeOfOptions.Heap));
            }

            return(layoutTable.ToString());

        case DumpOptions.Layout:
            var layoutTable1 = new ConsoleTable();

            var flags = EnumHelper.GetSetFlags(options2);

            if (options2 == InspectorOptions.All)
            {
                flags.Remove(InspectorOptions.All);
            }

            layoutTable1.AddColumn(flags.Select(Enum.GetName));


            // Rewrite options

            options2 = default;

            foreach (var flag in flags)
            {
                options2 |= flag;
            }

            var mt1    = value.GetMetaType();
            var fields = mt1.Fields.Where(x => !x.IsStatic);

            int s = Mem.SizeOf(value, SizeOfOptions.Auto);
            var p = Mem.AddressOf(ref value);


            foreach (var metaField in fields)
            {
                var rowValues = new List <object>();


                if (options2.HasFlag(InspectorOptions.Offset))
                {
                    rowValues.Add($"{metaField.Offset:X}");
                }

                if (options2.HasFlag(InspectorOptions.Size))
                {
                    rowValues.Add(metaField.Size);
                }

                if (options2.HasFlag(InspectorOptions.Type))
                {
                    rowValues.Add(metaField.FieldType.Name);
                }

                if (options2.HasFlag(InspectorOptions.Name))
                {
                    rowValues.Add(metaField.Name);
                }

                if (options2.HasFlag(InspectorOptions.Address))
                {
                    var addr1 = Mem.AddressOfData(ref value) + metaField.Offset;
                    rowValues.Add(addr1.ToString());
                }

                if (options2.HasFlag(InspectorOptions.Value))
                {
                    object fieldVal;

                    if (!mt1.RuntimeType.IsConstructedGenericType)
                    {
                        fieldVal = metaField.Info.GetValue(value);
                    }
                    else
                    {
                        fieldVal = "?";
                    }

                    rowValues.Add($"{fieldVal}");
                }

                layoutTable1.AddRow(rowValues.ToArray());
            }


            if (value is string str)
            {
                for (int i = 1; i < str.Length; i++)
                {
                    char c          = str[i];
                    var  rowValues  = new List <object>();
                    int  offsetBase = (i * sizeof(char));

                    if (options2.HasFlag(InspectorOptions.Offset))
                    {
                        rowValues.Add($"{offsetBase + RuntimeProperties.StringOverhead - sizeof(char):X}");
                    }

                    if (options2.HasFlag(InspectorOptions.Size))
                    {
                        rowValues.Add(sizeof(char));
                    }

                    if (options2.HasFlag(InspectorOptions.Type))
                    {
                        rowValues.Add(nameof(Char));
                    }

                    if (options2.HasFlag(InspectorOptions.Name))
                    {
                        rowValues.Add($"Char #{i + 1}");
                    }

                    if (options2.HasFlag(InspectorOptions.Address))
                    {
                        if (Mem.TryGetAddressOfHeap(value, OffsetOptions.StringData, out var addr2))
                        {
                            addr2 += offsetBase;
                            rowValues.Add(addr2.ToString());
                        }
                    }

                    if (options2.HasFlag(InspectorOptions.Value))
                    {
                        rowValues.Add($"{c}");
                    }

                    layoutTable1.AddRow(rowValues.ToArray());
                }
            }


            return(layoutTable1.ToString());

        default:
            throw new ArgumentOutOfRangeException(nameof(options));
        }
    }
예제 #3
0
        public static TextBuilder AppendDump(this TextBuilder textBuilder, MemberInfo?member, DumpOptions options = default)
        {
            if (member is null)
            {
                if (options.Verbose)
                {
                    return(textBuilder.Append("(MemberInfo)null"));
                }
                return(textBuilder);
            }

            if (member is FieldInfo fieldInfo)
            {
                return(AppendDump(textBuilder, fieldInfo, options));
            }

            // Fallback
            return(textBuilder.Append(member));
        }
예제 #4
0
        public static TextBuilder AppendDump(this TextBuilder textBuilder, PropertyInfo?property, DumpOptions options = default)
        {
            if (property is null)
            {
                if (options.Verbose)
                {
                    return(textBuilder.Append("(PropertyInfo)null"));
                }
                return(textBuilder);
            }

            if (options.Verbose)
            {
                var fieldAttributes = Attribute.GetCustomAttributes(property, true);
                if (fieldAttributes.Length > 0)
                {
                    textBuilder.AppendDelimit(Environment.NewLine,
                                              fieldAttributes,
                                              (tb, attr) => tb.Append('[').Append(attr).Append(']'))
                    .AppendLine();
                }

                var visibility = property.GetVisibility();
                if (visibility.HasFlag <Visibility>(Visibility.Private))
                {
                    textBuilder.Write("private ");
                }
                if (visibility.HasFlag <Visibility>(Visibility.Protected))
                {
                    textBuilder.Write("protected ");
                }
                if (visibility.HasFlag <Visibility>(Visibility.Internal))
                {
                    textBuilder.Write("internal ");
                }
                if (visibility.HasFlag <Visibility>(Visibility.Public))
                {
                    textBuilder.Write("public ");
                }
                if (property.IsStatic())
                {
                    textBuilder.Write("static ");
                }
            }

            textBuilder.AppendDump(property.PropertyType, options)
            .Append(' ')
            .Append(property.Name);

            var indexParams = property.GetIndexParameters();

            if (indexParams.Length > 0)
            {
                textBuilder.Append('[')
                .AppendDelimit(", ", indexParams, (tb, pi) => tb.AppendDump(pi, options))
                .Append(']');
            }

            // Getter + Setter
            textBuilder.Append(" { ");
            var getter = property.GetGetter();

            if (getter != null)
            {
                if (options.Verbose)
                {
                }
                else
                {
                    textBuilder.Append("get; ");
                }
            }
            var setter = property.GetSetter();

            if (setter != null)
            {
                if (options.Verbose)
                {
                }
                else
                {
                    textBuilder.Append("set; ");
                }
            }
            return(textBuilder.Append(" }"));
        }
예제 #5
0
파일: Vba.cs 프로젝트: debug-sharp/desharp
 public string DumpWithOptions(object obj, DumpOptions options)
 {
     return(Debug.Dump(obj, options));
 }
예제 #6
0
 public ObjectDumperConsole(DumpOptions dumpOptions) : base(dumpOptions)
 {
 }
예제 #7
0
        public static TextBuilder AppendDump(this TextBuilder builder, TimeSpan timeSpan, DumpOptions options = default)
        {
            string?format = options.Format;

            if (format.IsNullOrWhiteSpace())
            {
                if (options.Verbose)
                {
                    format = "G";
                }
                else
                {
                    format = "g";
                }
            }
            if (timeSpan.TryFormat(builder.Available,
                                   out int charsWritten,
                                   format,
                                   options.FormatProvider))
            {
                builder.Length += charsWritten;
                return(builder);
            }

            return(builder.Append(timeSpan.ToString(format, options.FormatProvider)));
        }
 public JEmptyArrayDumper(BaseJsonDumper parent, JArray instance, int depth, DumpOptions options)
     : base(parent, instance, depth, options)
 {
 }
예제 #9
0
 public static TextBuilder AppendDump(this TextBuilder textBuilder, object?obj, DumpOptions options = default)
 {
     return(obj switch
     {
         // Big ol' switch statement
         null when options.Verbose => textBuilder.Append("null"),
         null => textBuilder,
         Type type => AppendDump(textBuilder, type, options),
         Array array => AppendDump(textBuilder, array, options),
         string str => textBuilder.Append(str),
         IEnumerable enumerable => AppendDump(textBuilder, enumerable, options),
         TimeSpan timeSpan => textBuilder.AppendDump(timeSpan, options),
         DateTime dateTime => textBuilder.AppendDump(dateTime, options),
         Guid guid => textBuilder.AppendDump(guid, options),
         _ => textBuilder.Append(obj)
     });
예제 #10
0
        public static TextBuilder AppendDump(this TextBuilder builder, DateTime dateTime, DumpOptions options = default)
        {
            string?format = options.Format;

            if (format.IsNullOrWhiteSpace())
            {
                if (options.Verbose)
                {
                    format = "O";
                }
                else
                {
                    format = "yyyy-MM-dd HH:mm:ss";
                }
            }
            if (dateTime.TryFormat(builder.Available,
                                   out int charsWritten,
                                   format,
                                   options.FormatProvider))
            {
                builder.Length += charsWritten;
                return(builder);
            }

            return(builder.Append(dateTime.ToString(format, options.FormatProvider)));
        }
예제 #11
0
        public static void DumpIt(Vtero vtero, ConfigOptions co, DumpOptions dmpo)
        {
            var Version = vtero.Version;

            Mem.InitMem(co.FileName, vtero.MRD);

            // Extract Address Spaces verifies the linkages between
            // process<->CR3<->EPTP(if there is one)
            // and that they are functional

            var vetted = vtero.ExtrtactAddressSpaces(null, null, Version);

            // leaving this in as an example maybe? ;)

            //WriteLine("enter a group ID: ");
            //input = ReadLine();
            //int Grp = int.Parse(input);
            //WriteLine("enter a process ID: ");
            //input = ReadLine();
            //long procID = long.Parse(input, NumberStyles.HexNumber);
            //var proc = (from procz in vtero.ASGroups[Grp]
            //            where procz.CR3Value == procID
            //            select procz).First();
            //int i = 1;
            //DetectedProc dp = proc;
            //while(dp == null)
            //    dp = vtero.GetKernelRangeFromGroup(i++);


            // Scan for kernel
            // NT kernel may be in 0xFFFFF80000000 to 0xFFFFF8800000 range
            long         KernVAStart  = 0xF80000000000;
            long         KernVAEnd    = KernVAStart + (0x8000000000 - 0x1000);
            string       input        = string.Empty;
            var          Detections   = new Dictionary <long, Extract>();
            DetectedProc LikelyKernel = null;
            bool         Decoded      = false;

            // were doing this in nested loops to brute force our way past any errors
            // but only need the first set of detections per group

            foreach (var grpz in vtero.ASGroups)
            {
                foreach (var vm in vtero.VMCSs.Values)
                {
                    WriteColor(ConsoleColor.White, $"Group ID: {grpz.Key}");
                    foreach (var p in grpz.Value)
                    {
                        WriteLine($"Proc: {p.CR3Value:X}");
                        Detections = Detections.Concat(
                            vtero.ModuleScan(p, KernVAStart, KernVAEnd).Where(x => !Detections.ContainsKey(x.Key)))
                                     .ToDictionary(x => x.Key, x => x.Value);

                        if (Detections.Count() > 0)
                        {
                            LikelyKernel = p;

                            if (vm.EPTP == 0)
                            {
                                p.vmcs = null;
                            }
                            else
                            {
                                p.vmcs = vm;
                            }

                            // scan for kernel
                            foreach (var detected in Detections)
                            {
                                WriteColor(ConsoleColor.Green, $"Attempting to parse detected PE module loaded @ {detected.Key:X}");
                                WriteColor(ConsoleColor.Cyan, detected.Value.ToString());

                                if (detected.Value.ToString().Contains("POOLCODE"))
                                {
                                    WriteColor(ConsoleColor.White, "Likely Kernel analyzing for CV data");
                                    var cv_data = vtero.ExtractCVDebug(LikelyKernel, detected.Value, detected.Key);

                                    if (cv_data != null)
                                    {
                                        var sympath = Environment.GetEnvironmentVariable("_NT_SYMBOL_PATH");
                                        if (string.IsNullOrWhiteSpace(sympath))
                                        {
                                            sympath = "SRV*http://msdl.microsoft.com/download/symbols";
                                        }

                                        if (vtero.TryLoadSymbols(LikelyKernel, detected.Value, cv_data, detected.Key, sympath))
                                        {
                                            Decoded = vtero.GetKernelDebuggerData(LikelyKernel, detected.Value, cv_data, sympath);
                                        }
                                    }
                                }
                            }
                        }
                        if (Decoded)
                        {
                            break;
                        }
                    }
                    if (Decoded)
                    {
                        break;
                    }
                }
                if (Decoded)
                {
                    break;
                }
            }
            ForegroundColor = ConsoleColor.Green;
            WriteLine($"{Environment.NewLine}Final analysis completed, address spaces extracted. {QuickOptions.Timer.Elapsed} {QuickOptions.FormatRate(vtero.FileSize * 3, QuickOptions.Timer.Elapsed)}");

            // do a test dump
            // extract & dump could be done at the same time

            if (!dmpo.ListOnly)
            {
                vtero.DumpASToFile();
            }

            //if (Vtero.VerboseOutput)
            //vtero.DumpFailList();

            return;
        }
 public JEmptyObjectDumper(BaseJsonDumper parent, JObject instance, int depth, DumpOptions options)
     : base(parent, instance, depth, options)
 {
 }
예제 #13
0
파일: Vba.cs 프로젝트: debug-sharp/desharp
 public string DumpAndDie(object obj, DumpOptions options)
 {
     return(Debug.DumpAndDie(obj, options));
 }
예제 #14
0
 public static bool WriteDump(int pid, SafeHandle fileHandle, DumpOptions dumpType)
 {
     return(WriteDump(pid, 0, fileHandle, dumpType, false));
 }
예제 #15
0
 protected BaseJsonDumper(BaseJsonDumper parent, int depth, DumpOptions options)
 {
     Parent  = parent;
     Depth   = depth;
     Options = options;
 }
예제 #16
0
        public static bool WriteDump(int pid, int threadWithExceptionId, SafeHandle fileHandle, DumpOptions options, bool hasException)
        {
            IntPtr processHandle;
            uint   processId = (uint)pid;

            try {
                Process currentProcess = Process.GetProcessById(pid);
                processHandle = currentProcess.Handle;
            }
            catch (Exception)
            {
                return(false);
            }

            MiniDumpExceptionInformation exp;

            exp.ThreadId          = threadWithExceptionId;
            exp.ClientPointers    = false;
            exp.ExceptionPointers = IntPtr.Zero;

            if (hasException)
            {
                exp.ExceptionPointers = System.Runtime.InteropServices.Marshal.GetExceptionPointers();
            }

            bool bRet = false;

            if (exp.ExceptionPointers == IntPtr.Zero)
            {
                bRet = MiniDumpWriteDump(processHandle, processId, fileHandle, (uint)options, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
            }
            else
            {
                bRet = MiniDumpWriteDump(processHandle, processId, fileHandle, (uint)options, ref exp, IntPtr.Zero, IntPtr.Zero);
            }

            return(bRet);
        }
예제 #17
0
        internal static BaseJsonDumper GetWrapperFor(BaseJsonDumper parent, JToken instance, int depth, DumpOptions options)
        {
            switch (instance)
            {
            case JObject jObject when jObject.Count == 0:
                return(new JEmptyObjectDumper(parent, jObject, depth, options));

            case JObject jObject:
                return(new JObjectDumper(parent, jObject, depth, options));

            case JArray jArray when jArray.Count == 0:
                return(new JEmptyArrayDumper(parent, jArray, depth, options));

            case JArray jArray:
                return(new JArrayDumper(parent, jArray, depth, options));

            case JValue jValue:
                return(new JTokenDumper(parent, jValue, depth, options));

            default:
                return(new JTokenDumper(parent, instance, depth, options));
            }
        }
예제 #18
0
 public ObjectDumperCSharp(DumpOptions dumpOptions) : base(dumpOptions)
 {
 }
예제 #19
0
 public JTokenDumper(BaseJsonDumper parent, JToken instance, int depth, DumpOptions options)
     : base(parent, instance, depth, options)
 {
 }
        public void ShouldDumpExceptionAfterThrow()
        {
            // Arrange
            Exception ex;

            try
            {
                throw new KeyNotFoundException("message text");
            }
            catch (Exception e)
            {
                ex = e;
            }
            var options = new DumpOptions
            {
                IgnoreDefaultValues = true,
                ExcludeProperties   =
                {
                    "CustomAttributes",
                    "Module",
                    "StackTrace",
                    "MetadataToken"
                }
            };

            // Act
            var dump = ObjectDumperConsole.Dump(ex, options);

            // Assert
            this.testOutputHelper.WriteLine(dump);
            dump.Should().NotBeNull();

#if NETCORE
            dump.Should().Be(
                "{KeyNotFoundException}\r\n" +
                "  TargetSite: {RuntimeMethodInfo}\r\n" +
                "    Name: \"ShouldDumpExceptionAfterThrow\"\r\n" +
                "    DeclaringType: ObjectDumperConsoleTests\r\n" +
                "    ReflectedType: ObjectDumperConsoleTests\r\n" +
                "    MemberType: MemberTypes.Method\r\n" +
                "    IsSecurityCritical: true\r\n" +
                "    MethodHandle: {RuntimeMethodHandle}\r\n" +
                "      Value: {IntPtr}\r\n" +
                "\r\n" +
                "    Attributes: PrivateScope | Public | HideBySig\r\n" +
                "    CallingConvention: Standard | HasThis\r\n" +
                "    ReturnType: void\r\n" +
                "    ReturnTypeCustomAttributes: {RuntimeParameterInfo}\r\n" +
                "      ParameterType: void\r\n" +
                "      HasDefaultValue: true\r\n" +
                "      Member: null --> Circular reference detected\r\n" +
                "      Position: -1\r\n" +
                "    ReturnParameter: null --> Circular reference detected\r\n" +
                "    IsHideBySig: true\r\n" +
                "    IsPublic: true\r\n" +
                "  Message: \"message text\"\r\n" +
                "  Data: ...\r\n" +
                "  Source: \"ObjectDumper.Tests\"\r\n" +
                "  HResult: -2146232969");
#endif
        }
예제 #21
0
        public static TextBuilder AppendDump(this TextBuilder textBuilder, FieldInfo?field, DumpOptions options = default)
        {
            if (field is null)
            {
                if (options.Verbose)
                {
                    return(textBuilder.Append("(FieldInfo)null"));
                }
                return(textBuilder);
            }

            if (options.Verbose)
            {
                var fieldAttributes = Attribute.GetCustomAttributes(field, true);
                if (fieldAttributes.Length > 0)
                {
                    textBuilder.AppendDelimit(Environment.NewLine,
                                              fieldAttributes,
                                              (tb, attr) => tb.Append('[').Append(attr).Append(']'))
                    .AppendLine();
                }

                var visibility = field.GetVisibility();
                if (visibility.HasFlag <Visibility>(Visibility.Private))
                {
                    textBuilder.Write("private ");
                }
                if (visibility.HasFlag <Visibility>(Visibility.Protected))
                {
                    textBuilder.Write("protected ");
                }
                if (visibility.HasFlag <Visibility>(Visibility.Internal))
                {
                    textBuilder.Write("internal ");
                }
                if (visibility.HasFlag <Visibility>(Visibility.Public))
                {
                    textBuilder.Write("public ");
                }
                if (field.IsStatic)
                {
                    textBuilder.Write("static ");
                }
            }

            return(textBuilder.AppendDump(field.FieldType, options)
                   .Append(' ')
                   .Append(field.Name));
        }
예제 #22
0
 public static bool WriteDump(int pid, string filename, DumpOptions dumpType)
 {
     return WriteDump(pid, 0, filename, dumpType, false);
 }
예제 #23
0
파일: Vba.cs 프로젝트: debug-sharp/desharp
 public string Dump(Exception exception, DumpOptions options)
 {
     return(Debug.Dump(exception, options));
 }