summaryrefslogtreecommitdiff
path: root/src/tools/r2rdump/TextDumper.cs
blob: da45a71757a74c7503226d52c5c1daa05e9e69fa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection.PortableExecutable;
using System.Text;
using System.Xml;

namespace R2RDump
{
    class TextDumper : Dumper
    {
        public TextDumper(R2RReader r2r, TextWriter writer, Disassembler disassembler, DumpOptions options)
            : base(r2r, writer, disassembler, options)
        {
        }

        internal override void Begin()
        {
            if (!_options.Normalize)
            {
                _writer.WriteLine($"Filename: {_r2r.Filename}");
                _writer.WriteLine($"OS: {_r2r.OS}");
                _writer.WriteLine($"Machine: {_r2r.Machine}");
                _writer.WriteLine($"ImageBase: 0x{_r2r.ImageBase:X8}");
                SkipLine();
            }
        }

        internal override void End()
        {
            _writer.WriteLine("=============================================================");
            SkipLine();
        }

        internal override void WriteDivider(string title)
        {
            int len = 61 - title.Length - 2;
            _writer.WriteLine(new String('=', len / 2) + " " + title + " " + new String('=', (int)Math.Ceiling(len / 2.0)));
            SkipLine();
        }

        internal override void WriteSubDivider()
        {
            _writer.WriteLine("_______________________________________________");
            SkipLine();
        }

        internal override void SkipLine()
        {
            _writer.WriteLine();
        }

        /// <summary>
        /// Dumps the R2RHeader and all the sections in the header
        /// </summary>
        internal override void DumpHeader(bool dumpSections)
        {
            _writer.WriteLine(_r2r.R2RHeader.ToString());

            if (_options.Raw)
            {
                DumpBytes(_r2r.R2RHeader.RelativeVirtualAddress, (uint)_r2r.R2RHeader.Size);
            }
            SkipLine();
            if (dumpSections)
            {
                WriteDivider("R2R Sections");
                _writer.WriteLine($"{_r2r.R2RHeader.Sections.Count} sections");
                SkipLine();

                foreach (R2RSection section in NormalizedSections())
                {
                    DumpSection(section);
                }
            }
            SkipLine();
        }

        /// <summary>
        /// Dumps one R2RSection
        /// </summary>
        internal override void DumpSection(R2RSection section, XmlNode parentNode = null)
        {
            WriteSubDivider();
            _writer.WriteLine(section.ToString());

            if (_options.Raw)
            {
                DumpBytes(section.RelativeVirtualAddress, (uint)section.Size);
                SkipLine();
            }
            if (_options.SectionContents)
            {
                DumpSectionContents(section);
                SkipLine();
            }
        }

        internal override void DumpEntryPoints()
        {
            WriteDivider($@"R2R Entry Points");
            foreach (R2RMethod method in NormalizedMethods())
            {
                _writer.WriteLine(method.SignatureString);
            }
        }

        internal override void DumpAllMethods()
        {
            WriteDivider("R2R Methods");
            _writer.WriteLine($"{_r2r.R2RMethods.Count} methods");
            SkipLine();
            foreach (R2RMethod method in NormalizedMethods())
            {
                DumpMethod(method);
            }
        }

        /// <summary>
        /// Dumps one R2RMethod. 
        /// </summary>
        internal override void DumpMethod(R2RMethod method, XmlNode parentNode = null)
        {
            WriteSubDivider();
            method.WriteTo(_writer, _options);

            if (_options.GC && method.GcInfo != null)
            {
                _writer.WriteLine("GcInfo:");
                _writer.Write(method.GcInfo);

                if (_options.Raw)
                {
                    DumpBytes(method.GcInfo.Offset, (uint)method.GcInfo.Size, null, "", false);
                }
            }
            SkipLine();

            foreach (RuntimeFunction runtimeFunction in method.RuntimeFunctions)
            {
                DumpRuntimeFunction(runtimeFunction);
            }
        }

        /// <summary>
        /// Dumps one runtime function. 
        /// </summary>
        internal override void DumpRuntimeFunction(RuntimeFunction rtf, XmlNode parentNode = null)
        {
            _writer.WriteLine(rtf.Method.SignatureString);
            rtf.WriteTo(_writer, _options);

            if (_options.Disasm)
            {
                DumpDisasm(rtf, _r2r.GetOffset(rtf.StartAddress));
            }

            if (_options.Raw)
            {
                _writer.WriteLine("Raw Bytes:");
                DumpBytes(rtf.StartAddress, (uint)rtf.Size);
            }
            if (_options.Unwind)
            {
                _writer.WriteLine("UnwindInfo:");
                _writer.Write(rtf.UnwindInfo);
                if (_options.Raw)
                {
                    DumpBytes(rtf.UnwindRVA, (uint)rtf.UnwindInfo.Size);
                }
            }
            SkipLine();
        }

        /// <summary>
        /// Dumps disassembly and register liveness
        /// </summary>
        internal override void DumpDisasm(RuntimeFunction rtf, int imageOffset, XmlNode parentNode = null)
        {
            int rtfOffset = 0;
            int codeOffset = rtf.CodeOffset;
            while (rtfOffset < rtf.Size)
            {
                string instr;
                int instrSize = _disassembler.GetInstruction(rtf, imageOffset, rtfOffset, out instr);

                if (_r2r.Machine == Machine.Amd64 && ((Amd64.UnwindInfo)rtf.UnwindInfo).UnwindCodes.ContainsKey(codeOffset))
                {
                    List<Amd64.UnwindCode> codes = ((Amd64.UnwindInfo)rtf.UnwindInfo).UnwindCodes[codeOffset];
                    foreach (Amd64.UnwindCode code in codes)
                    {
                        _writer.Write($"                                {code.UnwindOp} {code.OpInfoStr}");
                        if (code.NextFrameOffset != -1)
                        {
                            _writer.WriteLine($"                                {code.NextFrameOffset}");
                        }
                        _writer.WriteLine();
                    }
                }

                if (rtf.Method.GcInfo != null && rtf.Method.GcInfo.Transitions.ContainsKey(codeOffset))
                {
                    foreach (BaseGcTransition transition in rtf.Method.GcInfo.Transitions[codeOffset])
                    {
                        _writer.WriteLine($"                                {transition.ToString()}");
                    }
                }

                /* According to https://msdn.microsoft.com/en-us/library/ck9asaa9.aspx and src/vm/gcinfodecoder.cpp
                 * UnwindCode and GcTransition CodeOffsets are encoded with a -1 adjustment (that is, it's the offset of the start of the next instruction)
                 */
                _writer.Write(instr);

                CoreDisTools.ClearOutputBuffer();
                rtfOffset += instrSize;
                codeOffset += instrSize;
            }
        }

        /// <summary>
        /// Prints a formatted string containing a block of bytes from the relative virtual address and size
        /// </summary>
        internal override void DumpBytes(int rva, uint size, XmlNode parentNode = null, string name = "Raw", bool convertToOffset = true)
        {
            int start = rva;
            if (convertToOffset)
                start = _r2r.GetOffset(rva);
            if (start > _r2r.Image.Length || start + size > _r2r.Image.Length)
            {
                throw new IndexOutOfRangeException();
            }

            _writer.Write("    ");
            if (rva % 16 != 0)
            {
                int floor = rva / 16 * 16;
                _writer.Write($"{floor:X8}:");
                _writer.Write(new String(' ', (rva - floor) * 3));
            }
            for (uint i = 0; i < size; i++)
            {
                if ((rva + i) % 16 == 0)
                {
                    _writer.Write($"{rva + i:X8}:");
                }
                _writer.Write($" {_r2r.Image[start + i]:X2}");
                if ((rva + i) % 16 == 15 && i != size - 1)
                {
                    SkipLine();
                    _writer.Write("    ");
                }
            }
            SkipLine();
        }

        internal override void DumpSectionContents(R2RSection section, XmlNode parentNode = null)
        {
            switch (section.Type)
            {
                case R2RSection.SectionType.READYTORUN_SECTION_AVAILABLE_TYPES:
                    if (!_options.Naked)
                    {
                        uint availableTypesSectionOffset = (uint)_r2r.GetOffset(section.RelativeVirtualAddress);
                        NativeParser availableTypesParser = new NativeParser(_r2r.Image, availableTypesSectionOffset);
                        NativeHashtable availableTypes = new NativeHashtable(_r2r.Image, availableTypesParser, (uint)(availableTypesSectionOffset + section.Size));
                        _writer.WriteLine(availableTypes.ToString());
                    }

                    foreach (string name in _r2r.AvailableTypes)
                    {
                        _writer.WriteLine(name);
                    }
                    break;
                case R2RSection.SectionType.READYTORUN_SECTION_METHODDEF_ENTRYPOINTS:
                    if (!_options.Naked)
                    {
                        NativeArray methodEntryPoints = new NativeArray(_r2r.Image, (uint)_r2r.GetOffset(section.RelativeVirtualAddress));
                        _writer.Write(methodEntryPoints.ToString());
                    }
                    break;
                case R2RSection.SectionType.READYTORUN_SECTION_INSTANCE_METHOD_ENTRYPOINTS:
                    if (!_options.Naked)
                    {
                        uint instanceSectionOffset = (uint)_r2r.GetOffset(section.RelativeVirtualAddress);
                        NativeParser instanceParser = new NativeParser(_r2r.Image, instanceSectionOffset);
                        NativeHashtable instMethodEntryPoints = new NativeHashtable(_r2r.Image, instanceParser, (uint)(instanceSectionOffset + section.Size));
                        _writer.Write(instMethodEntryPoints.ToString());
                        _writer.WriteLine();
                    }
                    foreach (InstanceMethod instanceMethod in _r2r.InstanceMethods)
                    {
                        _writer.WriteLine($@"0x{instanceMethod.Bucket:X2} -> {instanceMethod.Method.SignatureString}");
                    }
                    break;
                case R2RSection.SectionType.READYTORUN_SECTION_RUNTIME_FUNCTIONS:
                    int rtfOffset = _r2r.GetOffset(section.RelativeVirtualAddress);
                    int rtfEndOffset = rtfOffset + section.Size;
                    int rtfIndex = 0;
                    while (rtfOffset < rtfEndOffset)
                    {
                        int startRva = NativeReader.ReadInt32(_r2r.Image, ref rtfOffset);
                        int endRva = -1;
                        if (_r2r.Machine == Machine.Amd64)
                        {
                            endRva = NativeReader.ReadInt32(_r2r.Image, ref rtfOffset);
                        }
                        int unwindRva = NativeReader.ReadInt32(_r2r.Image, ref rtfOffset);
                        _writer.WriteLine($"Index: {rtfIndex}");
                        _writer.WriteLine($"\tStartRva: 0x{startRva:X8}");
                        if (endRva != -1)
                            _writer.WriteLine($"\tEndRva: 0x{endRva:X8}");
                        _writer.WriteLine($"\tUnwindRva: 0x{unwindRva:X8}");
                        rtfIndex++;
                    }
                    break;
                case R2RSection.SectionType.READYTORUN_SECTION_COMPILER_IDENTIFIER:
                    _writer.WriteLine(_r2r.CompilerIdentifier);
                    break;
                case R2RSection.SectionType.READYTORUN_SECTION_IMPORT_SECTIONS:
                    if (_options.Naked)
                    {
                        DumpNakedImportSections();
                    }
                    else
                    {
                        foreach (R2RImportSection importSection in _r2r.ImportSections)
                        {
                            _writer.Write(importSection.ToString());
                            if (_options.Raw && importSection.Entries.Count != 0)
                            {
                                if (importSection.SectionRVA != 0)
                                {
                                    _writer.WriteLine("Section Bytes:");
                                    DumpBytes(importSection.SectionRVA, (uint)importSection.SectionSize);
                                }
                                if (importSection.SignatureRVA != 0)
                                {
                                    _writer.WriteLine("Signature Bytes:");
                                    DumpBytes(importSection.SignatureRVA, (uint)importSection.Entries.Count * sizeof(int));
                                }
                                if (importSection.AuxiliaryDataRVA != 0 && importSection.AuxiliaryData != null)
                                {
                                    _writer.WriteLine("AuxiliaryData Bytes:");
                                    DumpBytes(importSection.AuxiliaryDataRVA, (uint)importSection.AuxiliaryData.Size);
                                }
                            }
                            foreach (R2RImportSection.ImportSectionEntry entry in importSection.Entries)
                            {
                                _writer.WriteLine(entry.ToString());
                            }
                            _writer.WriteLine();
                        }
                    }
                    break;
            }
        }

        private void DumpNakedImportSections()
        {
            List<string> importSignatures = new List<string>();
            foreach (R2RImportSection importSection in _r2r.ImportSections)
            {
                foreach (R2RImportSection.ImportSectionEntry entry in importSection.Entries)
                {
                    importSignatures.Add(entry.Signature);
                }
            }
            importSignatures.Sort();
            foreach (string sig in importSignatures)
            {
                _writer.WriteLine(sig);
            }
        }

        internal override XmlNode DumpQueryCount(string q, string title, int count)
        {
            _writer.WriteLine(count + " result(s) for \"" + q + "\"");
            SkipLine();
            return null;
        }
    }
}