-
Notifications
You must be signed in to change notification settings - Fork 27
/
ElfCoreDump.cs
1312 lines (1118 loc) · 43.6 KB
/
ElfCoreDump.cs
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using SharpDebug.Engine;
using SharpDebug.Engine.Utility;
using ELFSharp.ELF;
using ELFSharp.ELF.Segments;
using SharpUtilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace SharpDebug.DwarfSymbolProvider
{
/// <summary>
/// Simple ELF core dump reader.
/// </summary>
public class ElfCoreDump : IDisposable
{
/// <summary>
/// The elf reader.
/// </summary>
private ELF<ulong> elf;
/// <summary>
/// The instance
/// </summary>
private IInstance instance;
/// <summary>
/// The ELF note files loaded in the dump
/// </summary>
private elf_note_file[] files = new elf_note_file[0];
/// <summary>
/// AUX vector.
/// </summary>
private List<AuxvEntry> auxVector = new List<AuxvEntry>();
/// <summary>
/// Memory reader for ELF core dump files.
/// </summary>
/// <seealso cref="SharpDebug.Engine.Utility.DumpFileMemoryReader" />
private class CoreDumpReader : DumpFileMemoryReader
{
/// <summary>
/// Initializes a new instance of the <see cref="CoreDumpReader" /> class.
/// </summary>
/// <param name="dumpFilePath">The dump file path.</param>
/// <param name="segments">The segments.</param>
public CoreDumpReader(string dumpFilePath, IEnumerable<Segment<ulong>> segments)
: base(dumpFilePath)
{
Segment<ulong>[] segmentsArray = segments.OrderBy(s => s.Address).ToArray();
MemoryLocation[] ranges = new MemoryLocation[segmentsArray.Length];
for (int i = 0; i < ranges.Length; i++)
{
ranges[i] = new MemoryLocation()
{
MemoryStart = segmentsArray[i].Address,
MemoryEnd = segmentsArray[i].Address + (ulong)segmentsArray[i].FileSize,
FilePosition = (ulong)segmentsArray[i].Offset,
};
}
Initialize(ranges);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ElfCoreDump"/> class.
/// </summary>
/// <param name="coreDumpPath">The core dump path.</param>
public ElfCoreDump(string coreDumpPath)
{
elf = ELFReader.Load<ulong>(coreDumpPath);
if (elf.Type != FileType.Core)
{
throw new Exception($"Expected core dump, but got: {elf.Type}");
}
switch (elf.Machine)
{
case Machine.Intel386:
instance = new Intel386Instance(elf);
break;
case Machine.AMD64:
instance = new AMD64Instance(elf);
break;
default:
throw new Exception($"Unsupported machine type: {elf.Machine}");
}
Path = coreDumpPath;
foreach (var segment in elf.Segments)
{
if (segment.Type == SegmentType.Note)
{
using (DwarfMemoryReader reader = new DwarfMemoryReader(ReadSegment(segment)))
{
int noteStructSize = Marshal.SizeOf<elf_32note>();
while (reader.Position + noteStructSize < reader.Data.Length)
{
// Read note
elf_32note note = reader.ReadStructure<elf_32note>();
int nameEnd = reader.Position + (int)note.NameSize;
// Check if note is available to be read
if (nameEnd + note.n_descsz > reader.Data.Length)
{
break;
}
// Read name and content
string name = reader.ReadString();
reader.Position = nameEnd;
byte[] content = reader.ReadBlock(note.n_descsz);
instance.ProcessNote(name, content, note.n_type);
if (note.n_type == elf_note_type.File)
{
using (DwarfMemoryReader data = new DwarfMemoryReader(content))
{
files = elf_note_file.Parse(data, Is64bit);
}
}
else if (note.n_type == elf_note_type.Auxv)
{
using (DwarfMemoryReader data = new DwarfMemoryReader(content))
{
uint addressSize = elf.Class == Class.Bit32 ? 4U : 8U;
while (!data.IsEnd)
{
AuxvEntry entry = new AuxvEntry
{
Type = (AuxvEntryType)data.ReadUlong(addressSize),
Value = data.ReadUlong(addressSize)
};
if (entry.Type == AuxvEntryType.Null)
{
break;
}
if (entry.Type == AuxvEntryType.Ignore)
{
continue;
}
auxVector.Add(entry);
}
}
}
}
}
}
}
DumpFileMemoryReader = new CoreDumpReader(coreDumpPath, elf.Segments.Where(s => s.Type == SegmentType.Load));
}
/// <summary>
/// Gets the ELF core dump path.
/// </summary>
public string Path { get; private set; }
/// <summary>
/// Gets the dumped process identifier.
/// </summary>
public uint ProcessId
{
get
{
return instance.ProcessId;
}
}
/// <summary>
/// Gets a value indicating whether this <see cref="ElfCoreDump"/> is is 64bit dump.
/// </summary>
/// <value>
/// <c>true</c> if is 64bit; otherwise, <c>false</c>.
/// </value>
public bool Is64bit
{
get
{
return elf.Class == Class.Bit64;
}
}
/// <summary>
/// Gets the dump file memory reader.
/// </summary>
internal DumpFileMemoryReader DumpFileMemoryReader { get; private set; }
/// <summary>
/// Gets the array of thread ids available in the dump.
/// </summary>
public int[] GetThreadIds()
{
return instance.GetThreadIds();
}
/// <summary>
/// Gets the thread stack trace.
/// </summary>
/// <param name="threadIndex">Index of the thread.</param>
/// <param name="process">Process being debugged.</param>
/// <param name="symbolProvider">The symbol provider.</param>
/// <returns>Array of tuples of instruction offset, stack offset and frame offset.</returns>
public Tuple<ulong, ulong, ulong>[] GetThreadStackTrace(int threadIndex, Process process, DwarfSymbolProvider symbolProvider)
{
return instance.GetThreadStackTrace(threadIndex, DumpFileMemoryReader, process, symbolProvider);
}
/// <summary>
/// Gets base address of all loaded modules.
/// </summary>
/// <returns>Array of base addresses.</returns>
public ulong[] GetModulesBaseAddresses()
{
// Return list of files where offset is start of the file
return files.Where(f => f.file_ofs == 0).Select(f => f.start).ToArray();
}
/// <summary>
/// Gets the module load offset.
/// </summary>
/// <param name="baseAddress">The module base address.</param>
public ulong GetModuleLoadOffset(ulong baseAddress)
{
// Check if we are looking for load offset of main module
if (baseAddress == files[0].start)
{
// Find file with symbols for main module
string mainModulePath = files[0].name;
if (!string.IsNullOrEmpty(mainModulePath))
{
mainModulePath = ElfCoreDumpDebuggingEngine.GetModuleMappedImage(this, mainModulePath);
}
// Find offset for main module
ulong offset = 0;
if (!string.IsNullOrEmpty(mainModulePath) && File.Exists(mainModulePath))
{
var elf = ELFReader.Load<ulong>(mainModulePath);
foreach (AuxvEntry entry in auxVector)
{
if (entry.Type == AuxvEntryType.Entry)
{
offset = entry.Value - elf.EntryPoint;
break;
}
}
}
return offset;
}
return 0;
}
/// <summary>
/// Gets the size of the module.
/// </summary>
/// <param name="baseAddress">The module base address.</param>
public ulong GetModuleSize(ulong baseAddress)
{
string name = files.First(f => f.start == baseAddress).name;
string imagePath = ElfCoreDumpDebuggingEngine.GetModuleMappedImage(this, name);
if (!string.IsNullOrEmpty(imagePath) && File.Exists(imagePath))
{
// Return file size
return (ulong)(new FileInfo(imagePath).Length);
}
ulong endAddress = 0;
foreach (elf_note_file file in files)
{
if (file.name == name)
{
endAddress = Math.Max(endAddress, file.end);
}
}
return endAddress - baseAddress;
}
/// <summary>
/// Gets the module original path.
/// </summary>
/// <param name="baseAddress">The module base address.</param>
public string GetModuleOriginalPath(ulong baseAddress)
{
return files.First(f => f.start == baseAddress).name;
}
/// <summary>
/// Gets the architecture type.
/// </summary>
public ArchitectureType GetProcessArchitectureType()
{
return instance.GetProcessArchitectureType();
}
/// <summary>
/// Reads the segment from the dump.
/// </summary>
/// <param name="segment">The segment.</param>
private byte[] ReadSegment(Segment<ulong> segment)
{
try
{
return segment.GetFileContents();
}
catch
{
using (FileStream stream = new FileStream(Path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
byte[] bytes = new byte[segment.FileSize];
stream.Seek(segment.Offset, SeekOrigin.Begin);
stream.Read(bytes, 0, bytes.Length);
return bytes;
}
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
elf.Dispose();
DumpFileMemoryReader.Dispose();
}
/// <summary>
/// Interface that explains what different platforms will provide
/// </summary>
private interface IInstance
{
/// <summary>
/// Gets the dumped process identifier.
/// </summary>
uint ProcessId { get; }
/// <summary>
/// Processes the parsed note.
/// </summary>
/// <param name="name">The note name.</param>
/// <param name="content">The note content.</param>
/// <param name="type">The note type.</param>
void ProcessNote(string name, byte[] content, elf_note_type type);
/// <summary>
/// Gets the architecture type.
/// </summary>
ArchitectureType GetProcessArchitectureType();
/// <summary>
/// Gets the array of thread ids available in the dump.
/// </summary>
int[] GetThreadIds();
/// <summary>
/// Gets the thread stack trace.
/// </summary>
/// <param name="threadIndex">Index of the thread.</param>
/// <param name="dumpFileMemoryReader">The dump file memory reader.</param>
/// <param name="process">Process being debugged.</param>
/// <param name="symbolProvider">The symbol provider.</param>
/// <returns>Array of tuples of instruction offset, stack offset and frame offset.</returns>
Tuple<ulong, ulong, ulong>[] GetThreadStackTrace(int threadIndex, DumpFileMemoryReader dumpFileMemoryReader, Process process, DwarfSymbolProvider symbolProvider);
}
/// <summary>
/// Implementation for Intel386 platform
/// </summary>
/// <seealso cref="SharpDebug.DwarfSymbolProvider.ElfCoreDump.IInstance" />
private class Intel386Instance : IInstance
{
/// <summary>
/// The elf reader.
/// </summary>
private ELF<ulong> elf;
/// <summary>
/// The list of available threads in the dump
/// </summary>
private List<elf_prstatus> threads = new List<elf_prstatus>();
/// <summary>
/// Initializes a new instance of the <see cref="Intel386Instance"/> class.
/// </summary>
/// <param name="elf">The elf reader.</param>
public Intel386Instance(ELF<ulong> elf)
{
this.elf = elf;
}
/// <summary>
/// Gets the dumped process identifier.
/// </summary>
public uint ProcessId
{
get
{
return (uint)threads[0].ProcessId;
}
}
/// <summary>
/// Processes the parsed note.
/// </summary>
/// <param name="name">The note name.</param>
/// <param name="content">The note content.</param>
/// <param name="type">The note type.</param>
public void ProcessNote(string name, byte[] content, elf_note_type type)
{
if (type == elf_note_type.Prstatus)
{
using (DwarfMemoryReader data = new DwarfMemoryReader(content))
{
elf_prstatus prstatus = data.ReadStructure<elf_prstatus>();
threads.Add(prstatus);
}
}
else if (type == elf_note_type.Prpsinfo)
{
// TODO: Use when needed
//using (DwarfMemoryReader data = new DwarfMemoryReader(content))
//{
// elf_prpsinfo prpsinfo = data.ReadStructure<elf_prpsinfo>();
// Console.WriteLine($" Filename: {prpsinfo.Filename}");
// Console.WriteLine($" ArgList: {prpsinfo.ArgList}");
//}
}
}
/// <summary>
/// Gets the array of thread ids available in the dump.
/// </summary>
public int[] GetThreadIds()
{
int[] ids = new int[threads.Count];
for (int i = 0; i < ids.Length; i++)
{
ids[i] = threads[i].ProcessId;
}
return ids;
}
/// <summary>
/// Gets the thread stack trace.
/// </summary>
/// <param name="threadIndex">Index of the thread.</param>
/// <param name="dumpFileMemoryReader">The dump file memory reader.</param>
/// <param name="process">Process being debugged.</param>
/// <param name="symbolProvider">The symbol provider.</param>
/// <returns>Array of tuples of instruction offset, stack offset and frame offset.</returns>
public Tuple<ulong, ulong, ulong>[] GetThreadStackTrace(int threadIndex, DumpFileMemoryReader dumpFileMemoryReader, Process process, DwarfSymbolProvider symbolProvider)
{
const int pointerSize = 4;
elf_prstatus prstatus = threads[threadIndex];
ulong bp = prstatus.pr_reg[X86RegisterIndex.EBP];
ulong ip = prstatus.pr_reg[X86RegisterIndex.EIP];
List<Tuple<ulong, ulong, ulong>> result = new List<Tuple<ulong, ulong, ulong>>();
ulong segmentStartAddress, segmentSize;
dumpFileMemoryReader.GetMemoryRange(bp, out segmentStartAddress, out segmentSize);
while (bp >= segmentStartAddress && bp < segmentStartAddress + segmentSize)
{
result.Add(Tuple.Create(ip, bp, bp));
ulong savedLocationForRegisters = bp;
Module module = process.GetModuleByInnerAddress(ip);
if (module != null)
{
DwarfSymbolProviderModule symbolProviderModule = symbolProvider.GetSymbolProviderModule(module) as DwarfSymbolProviderModule;
if (symbolProviderModule != null)
{
ThreadContext frameContext = new ThreadContext(ip, bp, bp, null);
ulong canonicalFrameAddress = symbolProviderModule.GetFunctionCanonicalFrameAddress(process, ip, frameContext);
if (canonicalFrameAddress != 0)
{
savedLocationForRegisters = canonicalFrameAddress - pointerSize * 2;
}
}
}
MemoryBuffer buffer = dumpFileMemoryReader.ReadMemory(savedLocationForRegisters, pointerSize * 2);
bp = UserType.ReadPointer(buffer, 0, pointerSize);
ip = UserType.ReadPointer(buffer, pointerSize, pointerSize);
}
return result.ToArray();
}
/// <summary>
/// Gets the architecture type.
/// </summary>
public ArchitectureType GetProcessArchitectureType()
{
return ArchitectureType.X86;
}
#region Native structures
private static class X86RegisterIndex
{
public const int EBP = 5;
public const int EIP = 12;
public const int ESP = 15;
}
[StructLayout(LayoutKind.Sequential, Pack = 4)]
private struct timeval
{
/// <summary>
/// Seconds
/// </summary>
public int tv_sec;
/// <summary>
/// Microseconds
/// </summary>
public int tv_usec;
}
/// <summary>
/// Definitions to generate Intel SVR4-like core files.
/// These mostly have the same names as the SVR4 types with "elf_"
/// tacked on the front to prevent clashes with linux definitions,
/// and the typedef forms have been avoided.This is mostly like
/// the SVR4 structure, but more Linuxy, with things that Linux does
/// not support and which gdb doesn't really use excluded.
/// Fields present but not used are marked with "XXX".
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 4)]
private struct elf_prstatus
{
/// <summary>
/// Info associated with signal
/// </summary>
public elf_siginfo pr_info;
/// <summary>
/// Current signal
/// </summary>
public short pr_cursig;
/// <summary>
/// Set of pending signals
/// </summary>
public uint pr_sigpend;
/// <summary>
/// Set of held signals
/// </summary>
public uint pr_sighold;
public int pr_pid;
public int pr_ppid;
public int pr_pgrp;
public int pr_sid;
/// <summary>
/// User time
/// </summary>
public timeval pr_utime;
/// <summary>
/// System time
/// </summary>
public timeval pr_stime;
/// <summary>
/// Cumulative user time
/// </summary>
public timeval pr_cutime;
/// <summary>
/// Cumulative system time
/// </summary>
public timeval pr_cstime;
/// <summary>
/// GP registers
/// </summary>
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 17)]
public uint[] pr_reg;
/// <summary>
/// True if math co-processor being used.
/// </summary>
public int pr_fpvalid;
public int ProcessId
{
get
{
return pr_pid;
}
}
}
[StructLayout(LayoutKind.Sequential, Pack = 4)]
private struct elf_prpsinfo
{
/// <summary>
/// Numeric process state
/// </summary>
public sbyte pr_state;
/// <summary>
/// Char for pr_state
/// </summary>
public sbyte pr_sname;
/// <summary>
/// zombie
/// </summary>
public sbyte pr_zomb;
/// <summary>
/// nice val
/// </summary>
public sbyte pr_nice;
/// <summary>
/// Flags
/// </summary>
public uint pr_flag;
public ushort pr_uid;
public ushort pr_gid;
public int pr_pid;
public int pr_ppid;
public int pr_pgrp;
public int pr_sid;
/// <summary>
/// Filename of executable
/// </summary>
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
byte[] pr_fname;
/// <summary>
/// Initial part of arg list
/// </summary>
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 80)]
byte[] pr_psargs;
public string Filename
{
get
{
return Encoding.UTF8.GetString(pr_fname, 0, ZeroIndex(pr_fname));
}
}
public string ArgList
{
get
{
return Encoding.UTF8.GetString(pr_psargs, 0, ZeroIndex(pr_psargs));
}
}
private int ZeroIndex(byte[] bytes)
{
for (int index = 0; index < bytes.Length; index++)
{
if (bytes[index] == 0)
{
return index;
}
}
return bytes.Length;
}
}
#endregion
}
/// <summary>
/// Implementation for AMD64 platform
/// </summary>
/// <seealso cref="SharpDebug.DwarfSymbolProvider.ElfCoreDump.IInstance" />
private class AMD64Instance : IInstance
{
/// <summary>
/// The elf reader.
/// </summary>
private ELF<ulong> elf;
/// <summary>
/// The list of available threads in the dump
/// </summary>
private List<elf_prstatus> threads = new List<elf_prstatus>();
/// <summary>
/// Initializes a new instance of the <see cref="AMD64Instance"/> class.
/// </summary>
/// <param name="elf">The elf reader.</param>
public AMD64Instance(ELF<ulong> elf)
{
this.elf = elf;
}
/// <summary>
/// Gets the dumped process identifier.
/// </summary>
public uint ProcessId
{
get
{
return (uint)threads[0].ProcessId;
}
}
/// <summary>
/// Processes the parsed note.
/// </summary>
/// <param name="name">The note name.</param>
/// <param name="content">The note content.</param>
/// <param name="type">The note type.</param>
public void ProcessNote(string name, byte[] content, elf_note_type type)
{
if (type == elf_note_type.Prstatus)
{
using (DwarfMemoryReader data = new DwarfMemoryReader(content))
{
elf_prstatus prstatus = data.ReadStructure<elf_prstatus>();
threads.Add(prstatus);
}
}
else if (type == elf_note_type.Prpsinfo)
{
// TODO: Use when needed
//using (DwarfMemoryReader data = new DwarfMemoryReader(content))
//{
// elf_prpsinfo prpsinfo = data.ReadStructure<elf_prpsinfo>();
// Console.WriteLine($" Filename: {prpsinfo.Filename}");
// Console.WriteLine($" ArgList: {prpsinfo.ArgList}");
//}
}
}
/// <summary>
/// Gets the array of thread ids available in the dump.
/// </summary>
public int[] GetThreadIds()
{
int[] ids = new int[threads.Count];
for (int i = 0; i < ids.Length; i++)
{
ids[i] = threads[i].ProcessId;
}
return ids;
}
/// <summary>
/// Gets the thread stack trace.
/// </summary>
/// <param name="threadIndex">Index of the thread.</param>
/// <param name="dumpFileMemoryReader">The dump file memory reader.</param>
/// <param name="process">Process being debugged.</param>
/// <param name="symbolProvider">The symbol provider.</param>
/// <returns>Array of tuples of instruction offset, stack offset and frame offset.</returns>
public Tuple<ulong, ulong, ulong>[] GetThreadStackTrace(int threadIndex, DumpFileMemoryReader dumpFileMemoryReader, Process process, DwarfSymbolProvider symbolProvider)
{
const int pointerSize = 8;
elf_prstatus prstatus = threads[threadIndex];
ulong bp = prstatus.pr_reg[X64RegisterIndex.RBP];
ulong ip = prstatus.pr_reg[X64RegisterIndex.RIP];
List<Tuple<ulong, ulong, ulong>> result = new List<Tuple<ulong, ulong, ulong>>();
ulong segmentStartAddress, segmentSize;
dumpFileMemoryReader.GetMemoryRange(bp, out segmentStartAddress, out segmentSize);
while (bp >= segmentStartAddress && bp < segmentStartAddress + segmentSize)
{
result.Add(Tuple.Create(ip, bp, bp));
ulong savedLocationForRegisters = bp;
Module module = process.GetModuleByInnerAddress(ip);
if (module != null)
{
DwarfSymbolProviderModule symbolProviderModule = symbolProvider.GetSymbolProviderModule(module) as DwarfSymbolProviderModule;
if (symbolProviderModule != null)
{
ThreadContext frameContext = new ThreadContext(ip, bp, bp, null);
ulong canonicalFrameAddress = symbolProviderModule.GetFunctionCanonicalFrameAddress(process, ip, frameContext);
if (canonicalFrameAddress != 0)
{
savedLocationForRegisters = canonicalFrameAddress - pointerSize * 2;
}
}
}
MemoryBuffer buffer = dumpFileMemoryReader.ReadMemory(savedLocationForRegisters, pointerSize * 2);
bp = UserType.ReadPointer(buffer, 0, pointerSize);
ip = UserType.ReadPointer(buffer, pointerSize, pointerSize);
}
return result.ToArray();
}
/// <summary>
/// Gets the architecture type.
/// </summary>
public ArchitectureType GetProcessArchitectureType()
{
return ArchitectureType.Amd64;
}
#region Native structures
private static class X64RegisterIndex
{
public const int R15 = 0;
public const int R14 = 1;
public const int R13 = 2;
public const int R12 = 3;
public const int RBP = 4;
public const int RBX = 5;
public const int R11 = 6;
public const int R10 = 7;
public const int R9 = 8;
public const int R8 = 9;
public const int RAX = 10;
public const int RCX = 11;
public const int RDX = 12;
public const int RSI = 13;
public const int RDI = 14;
public const int OrigRAX = 15;
public const int RIP = 16;
public const int CS = 17;
public const int EFlags = 18;
public const int RSP = 19;
public const int SS = 20;
public const int FSBase = 21;
public const int GSBase = 22;
public const int DS = 23;
public const int ES = 24;
public const int FS = 25;
public const int GS = 26;
}
[StructLayout(LayoutKind.Sequential, Pack = 8)]
private struct timeval
{
/// <summary>
/// Seconds
/// </summary>
public long tv_sec;
/// <summary>
/// Microseconds
/// </summary>
public long tv_usec;
}
/// <summary>
/// Definitions to generate Intel SVR4-like core files.
/// These mostly have the same names as the SVR4 types with "elf_"
/// tacked on the front to prevent clashes with linux definitions,
/// and the typedef forms have been avoided.This is mostly like
/// the SVR4 structure, but more Linuxy, with things that Linux does
/// not support and which gdb doesn't really use excluded.
/// Fields present but not used are marked with "XXX".
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 8)]
private struct elf_prstatus
{
/// <summary>
/// Info associated with signal
/// </summary>
public elf_siginfo pr_info;
/// <summary>
/// Current signal
/// </summary>
public short pr_cursig;
/// <summary>
/// Set of pending signals
/// </summary>
public ulong pr_sigpend;
/// <summary>
/// Set of held signals
/// </summary>
public ulong pr_sighold;
public int pr_pid;
public int pr_ppid;
public int pr_pgrp;
public int pr_sid;
/// <summary>
/// User time
/// </summary>
public timeval pr_utime;
/// <summary>
/// System time
/// </summary>
public timeval pr_stime;
/// <summary>
/// Cumulative user time
/// </summary>
public timeval pr_cutime;
/// <summary>
/// Cumulative system time
/// </summary>
public timeval pr_cstime;
/// <summary>
/// GP registers
/// </summary>
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 27)]
public ulong[] pr_reg;
/// <summary>
/// True if math co-processor being used.
/// </summary>
public int pr_fpvalid;
public int ProcessId
{
get
{
return pr_pid;
}
}
}
[StructLayout(LayoutKind.Sequential, Pack = 8)]
private struct elf_prpsinfo
{
/// <summary>
/// Numeric process state
/// </summary>
public sbyte pr_state;
/// <summary>
/// Char for pr_state
/// </summary>
public sbyte pr_sname;
/// <summary>
/// zombie
/// </summary>
public sbyte pr_zomb;
/// <summary>
/// nice val
/// </summary>
public sbyte pr_nice;
/// <summary>
/// Flags
/// </summary>
public ulong pr_flag;
public uint pr_uid;
public uint pr_gid;
public int pr_pid;