aboutsummaryrefslogtreecommitdiff
path: root/src/Ryujinx.HLE/HOS/Kernel/Process/HleProcessDebugger.cs
blob: 7578f1d2fd735c202c9b24695a4536d97f75b363 (plain) (blame)
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
using Ryujinx.HLE.HOS.Diagnostics.Demangler;
using Ryujinx.HLE.HOS.Kernel.Memory;
using Ryujinx.HLE.HOS.Kernel.Threading;
using Ryujinx.HLE.Loaders.Elf;
using Ryujinx.Memory;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Ryujinx.HLE.HOS.Kernel.Process
{
    class HleProcessDebugger
    {
        private const int Mod0 = 'M' << 0 | 'O' << 8 | 'D' << 16 | '0' << 24;

        private readonly KProcess _owner;

        private class Image
        {
            public ulong BaseAddress { get; }
            public ulong Size { get; }
            public ulong EndAddress => BaseAddress + Size;

            public ElfSymbol[] Symbols { get; }

            public Image(ulong baseAddress, ulong size, ElfSymbol[] symbols)
            {
                BaseAddress = baseAddress;
                Size = size;
                Symbols = symbols;
            }
        }

        private readonly List<Image> _images;

        private int _loaded;

        public HleProcessDebugger(KProcess owner)
        {
            _owner = owner;

            _images = new List<Image>();
        }

        public string GetGuestStackTrace(KThread thread)
        {
            EnsureLoaded();

            var context = thread.Context;

            StringBuilder trace = new();

            trace.AppendLine($"Process: {_owner.Name}, PID: {_owner.Pid}");

            void AppendTrace(ulong address)
            {
                if (AnalyzePointer(out PointerInfo info, address, thread))
                {
                    trace.AppendLine($"   0x{address:x16}\t{info.ImageDisplay}\t{info.SubDisplay}");
                }
                else
                {
                    trace.AppendLine($"   0x{address:x16}");
                }
            }

            if (context.IsAarch32)
            {
                ulong framePointer = context.GetX(11);

                while (framePointer != 0)
                {
                    if ((framePointer & 3) != 0 ||
                        !_owner.CpuMemory.IsMapped(framePointer) ||
                        !_owner.CpuMemory.IsMapped(framePointer + 4))
                    {
                        break;
                    }

                    AppendTrace(_owner.CpuMemory.Read<uint>(framePointer + 4));

                    framePointer = _owner.CpuMemory.Read<uint>(framePointer);
                }
            }
            else
            {
                ulong framePointer = context.GetX(29);

                while (framePointer != 0)
                {
                    if ((framePointer & 7) != 0 ||
                        !_owner.CpuMemory.IsMapped(framePointer) ||
                        !_owner.CpuMemory.IsMapped(framePointer + 8))
                    {
                        break;
                    }

                    AppendTrace(_owner.CpuMemory.Read<ulong>(framePointer + 8));

                    framePointer = _owner.CpuMemory.Read<ulong>(framePointer);
                }
            }

            return trace.ToString();
        }

        public string GetCpuRegisterPrintout(KThread thread)
        {
            EnsureLoaded();

            var context = thread.Context;

            StringBuilder sb = new();

            string GetReg(int x)
            {
                var v = x == 32 ? context.Pc : context.GetX(x);
                if (!AnalyzePointer(out PointerInfo info, v, thread))
                {
                    return $"0x{v:x16}";
                }
                else
                {
                    if (!string.IsNullOrEmpty(info.ImageName))
                    {
                        return $"0x{v:x16} ({info.ImageDisplay})\t=> {info.SubDisplay}";
                    }
                    else
                    {
                        return $"0x{v:x16} ({info.SpDisplay})";
                    }
                }
            }

            for (int i = 0; i <= 28; i++)
            {
                sb.AppendLine($"\tX[{i:d2}]:\t{GetReg(i)}");
            }
            sb.AppendLine($"\tFP:\t{GetReg(29)}");
            sb.AppendLine($"\tLR:\t{GetReg(30)}");
            sb.AppendLine($"\tSP:\t{GetReg(31)}");
            sb.AppendLine($"\tPC:\t{GetReg(32)}");

            return sb.ToString();
        }

        private static bool TryGetSubName(Image image, ulong address, out ElfSymbol symbol)
        {
            address -= image.BaseAddress;

            int left = 0;
            int right = image.Symbols.Length - 1;

            while (left <= right)
            {
                int size = right - left;

                int middle = left + (size >> 1);

                symbol = image.Symbols[middle];

                ulong endAddr = symbol.Value + symbol.Size;

                if (address >= symbol.Value && address < endAddr)
                {
                    return true;
                }

                if (address < symbol.Value)
                {
                    right = middle - 1;
                }
                else
                {
                    left = middle + 1;
                }
            }

            symbol = default;

            return false;
        }

        struct PointerInfo
        {
            public string ImageName;
            public string SubName;

            public ulong Offset;
            public ulong SubOffset;

            public readonly string ImageDisplay => $"{ImageName}:0x{Offset:x4}";
            public readonly string SubDisplay => SubOffset == 0 ? SubName : $"{SubName}:0x{SubOffset:x4}";
            public readonly string SpDisplay => SubOffset == 0 ? "SP" : $"SP:-0x{SubOffset:x4}";
        }

        private bool AnalyzePointer(out PointerInfo info, ulong address, KThread thread)
        {
            if (AnalyzePointerFromImages(out info, address))
            {
                return true;
            }

            if (AnalyzePointerFromStack(out info, address, thread))
            {
                return true;
            }

            return false;
        }

        private bool AnalyzePointerFromImages(out PointerInfo info, ulong address)
        {
            info = default;

            Image image = GetImage(address, out int imageIndex);

            if (image == null)
            {
                // Value isn't a pointer to a known image...
                return false;
            }

            info.Offset = address - image.BaseAddress;

            // Try to find what this pointer is referring to
            if (TryGetSubName(image, address, out ElfSymbol symbol))
            {
                info.SubName = symbol.Name;

                // Demangle string if possible
                if (info.SubName.StartsWith("_Z"))
                {
                    info.SubName = Demangler.Parse(info.SubName);
                }
                info.SubOffset = info.Offset - symbol.Value;
            }
            else
            {
                info.SubName = "";
            }

            info.ImageName = GetGuessedNsoNameFromIndex(imageIndex);

            return true;
        }

        private bool AnalyzePointerFromStack(out PointerInfo info, ulong address, KThread thread)
        {
            info = default;

            ulong sp = thread.Context.GetX(31);
            var memoryInfo = _owner.MemoryManager.QueryMemory(address);
            MemoryState memoryState = memoryInfo.State;

            if (!memoryState.HasFlag(MemoryState.Stack)) // Is this pointer within the stack?
            {
                return false;
            }

            info.SubOffset = address - sp;

            return true;
        }

        private Image GetImage(ulong address, out int index)
        {
            lock (_images)
            {
                for (index = _images.Count - 1; index >= 0; index--)
                {
                    if (address >= _images[index].BaseAddress && address < _images[index].EndAddress)
                    {
                        return _images[index];
                    }
                }
            }

            return null;
        }

        private string GetGuessedNsoNameFromIndex(int index)
        {
            if ((uint)index > 11)
            {
                return "???";
            }

            if (index == 0)
            {
                return "rtld";
            }
            else if (index == 1)
            {
                return "main";
            }
            else if (index == GetImagesCount() - 1)
            {
                return "sdk";
            }
            else
            {
                return "subsdk" + (index - 2);
            }
        }

        private int GetImagesCount()
        {
            lock (_images)
            {
                return _images.Count;
            }
        }

        private void EnsureLoaded()
        {
            if (Interlocked.CompareExchange(ref _loaded, 1, 0) == 0)
            {
                ScanMemoryForTextSegments();
            }
        }

        private void ScanMemoryForTextSegments()
        {
            ulong oldAddress = 0;
            ulong address = 0;

            while (address >= oldAddress)
            {
                KMemoryInfo info = _owner.MemoryManager.QueryMemory(address);

                if (info.State == MemoryState.Reserved)
                {
                    break;
                }

                if (info.State == MemoryState.CodeStatic && info.Permission == KMemoryPermission.ReadAndExecute)
                {
                    LoadMod0Symbols(_owner.CpuMemory, info.Address, info.Size);
                }

                oldAddress = address;

                address = info.Address + info.Size;
            }
        }

        private void LoadMod0Symbols(IVirtualMemoryManager memory, ulong textOffset, ulong textSize)
        {
            ulong mod0Offset = textOffset + memory.Read<uint>(textOffset + 4);

            if (mod0Offset < textOffset || !memory.IsMapped(mod0Offset) || (mod0Offset & 3) != 0)
            {
                return;
            }

            Dictionary<ElfDynamicTag, ulong> dynamic = new();

            int mod0Magic = memory.Read<int>(mod0Offset + 0x0);

            if (mod0Magic != Mod0)
            {
                return;
            }

            ulong dynamicOffset = memory.Read<uint>(mod0Offset + 0x4) + mod0Offset;
            ulong bssStartOffset = memory.Read<uint>(mod0Offset + 0x8) + mod0Offset;
            ulong bssEndOffset = memory.Read<uint>(mod0Offset + 0xc) + mod0Offset;
            ulong ehHdrStartOffset = memory.Read<uint>(mod0Offset + 0x10) + mod0Offset;
            ulong ehHdrEndOffset = memory.Read<uint>(mod0Offset + 0x14) + mod0Offset;
            ulong modObjOffset = memory.Read<uint>(mod0Offset + 0x18) + mod0Offset;

            bool isAArch32 = memory.Read<ulong>(dynamicOffset) > 0xFFFFFFFF || memory.Read<ulong>(dynamicOffset + 0x10) > 0xFFFFFFFF;

            while (true)
            {
                ulong tagVal;
                ulong value;

                if (isAArch32)
                {
                    tagVal = memory.Read<uint>(dynamicOffset + 0);
                    value = memory.Read<uint>(dynamicOffset + 4);

                    dynamicOffset += 0x8;
                }
                else
                {
                    tagVal = memory.Read<ulong>(dynamicOffset + 0);
                    value = memory.Read<ulong>(dynamicOffset + 8);

                    dynamicOffset += 0x10;
                }

                ElfDynamicTag tag = (ElfDynamicTag)tagVal;

                if (tag == ElfDynamicTag.DT_NULL)
                {
                    break;
                }

                dynamic[tag] = value;
            }

            if (!dynamic.TryGetValue(ElfDynamicTag.DT_STRTAB, out ulong strTab) ||
                !dynamic.TryGetValue(ElfDynamicTag.DT_SYMTAB, out ulong symTab) ||
                !dynamic.TryGetValue(ElfDynamicTag.DT_SYMENT, out ulong symEntSize))
            {
                return;
            }

            ulong strTblAddr = textOffset + strTab;
            ulong symTblAddr = textOffset + symTab;

            List<ElfSymbol> symbols = new();

            while (symTblAddr < strTblAddr)
            {
                ElfSymbol sym = isAArch32 ? GetSymbol32(memory, symTblAddr, strTblAddr) : GetSymbol64(memory, symTblAddr, strTblAddr);

                symbols.Add(sym);

                symTblAddr += symEntSize;
            }

            lock (_images)
            {
                _images.Add(new Image(textOffset, textSize, symbols.OrderBy(x => x.Value).ToArray()));
            }
        }

        private static ElfSymbol GetSymbol64(IVirtualMemoryManager memory, ulong address, ulong strTblAddr)
        {
            ElfSymbol64 sym = memory.Read<ElfSymbol64>(address);

            uint nameIndex = sym.NameOffset;

            StringBuilder nameBuilder = new();

            for (int chr; (chr = memory.Read<byte>(strTblAddr + nameIndex++)) != 0;)
            {
                nameBuilder.Append((char)chr);
            }

            return new ElfSymbol(nameBuilder.ToString(), sym.Info, sym.Other, sym.SectionIndex, sym.ValueAddress, sym.Size);
        }

        private static ElfSymbol GetSymbol32(IVirtualMemoryManager memory, ulong address, ulong strTblAddr)
        {
            ElfSymbol32 sym = memory.Read<ElfSymbol32>(address);

            uint nameIndex = sym.NameOffset;

            StringBuilder nameBuilder = new();

            for (int chr; (chr = memory.Read<byte>(strTblAddr + nameIndex++)) != 0;)
            {
                nameBuilder.Append((char)chr);
            }

            return new ElfSymbol(nameBuilder.ToString(), sym.Info, sym.Other, sym.SectionIndex, sym.ValueAddress, sym.Size);
        }
    }
}