-
Notifications
You must be signed in to change notification settings - Fork 106
/
Copy pathSymbolReader.cs
1434 lines (1242 loc) · 58.7 KB
/
SymbolReader.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using System.Runtime.InteropServices;
using System.Text;
namespace NetCoreDbg
{
public class SymbolReader
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct DebugInfo
{
public int lineNumber;
public int ilOffset;
public string fileName;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct LocalVarInfo
{
public int startOffset;
public int endOffset;
public string name;
}
[StructLayout(LayoutKind.Sequential)]
internal struct MethodDebugInfo
{
public IntPtr points;
public int size;
public IntPtr locals;
public int localsSize;
}
[StructLayout(LayoutKind.Sequential)]
internal struct DbgSequencePoint
{
public int startLine;
public int startColumn;
public int endLine;
public int endColumn;
public int offset;
public IntPtr document;
}
/// <summary>
/// Read memory callback
/// </summary>
/// <returns>number of bytes read or 0 for error</returns>
internal unsafe delegate int ReadMemoryDelegate(ulong address, byte* buffer, int count);
private sealed class OpenedReader : IDisposable
{
public readonly MetadataReaderProvider Provider;
public readonly MetadataReader Reader;
public OpenedReader(MetadataReaderProvider provider, MetadataReader reader)
{
Debug.Assert(provider != null);
Debug.Assert(reader != null);
Provider = provider;
Reader = reader;
}
public void Dispose() => Provider.Dispose();
}
/// <summary>
/// Stream implementation to read debugger target memory for in-memory PDBs
/// </summary>
private class TargetStream : Stream
{
readonly ulong _address;
readonly ReadMemoryDelegate _readMemory;
public override long Position { get; set; }
public override long Length { get; }
public override bool CanSeek { get { return true; } }
public override bool CanRead { get { return true; } }
public override bool CanWrite { get { return false; } }
public TargetStream(ulong address, int size, ReadMemoryDelegate readMemory)
: base()
{
_address = address;
_readMemory = readMemory;
Length = size;
Position = 0;
}
public override int Read(byte[] buffer, int offset, int count)
{
if (Position + count > Length)
{
throw new ArgumentOutOfRangeException();
}
unsafe
{
fixed (byte* p = &buffer[offset])
{
int read = _readMemory(_address + (ulong)Position, p, count);
Position += read;
return read;
}
}
}
public override long Seek(long offset, SeekOrigin origin)
{
switch (origin)
{
case SeekOrigin.Begin:
Position = offset;
break;
case SeekOrigin.End:
Position = Length + offset;
break;
case SeekOrigin.Current:
Position += offset;
break;
}
return Position;
}
public override void Flush()
{
}
public override void SetLength(long value)
{
throw new NotImplementedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
}
/// <summary>
/// Quick fix for Path.GetFileName which incorrectly handles Windows-style paths on Linux
/// </summary>
/// <param name="pathName"> File path to be processed </param>
/// <returns>Last component of path</returns>
private static string GetFileName(string pathName)
{
int pos = pathName.LastIndexOfAny(new char[] { '/', '\\'});
if (pos < 0)
return pathName;
return pathName.Substring(pos + 1);
}
/// <summary>
/// Checks availability of debugging information for given assembly.
/// </summary>
/// <param name="assemblyPath">
/// File path of the assembly or null if the module is in-memory or dynamic (generated by Reflection.Emit)
/// </param>
/// <param name="isFileLayout">type of in-memory PE layout, if true, file based layout otherwise, loaded layout</param>
/// <param name="loadedPeAddress">
/// Loaded PE image address or zero if the module is dynamic (generated by Reflection.Emit).
/// Dynamic modules have their PDBs (if any) generated to an in-memory stream
/// (pointed to by <paramref name="inMemoryPdbAddress"/> and <paramref name="inMemoryPdbSize"/>).
/// </param>
/// <param name="loadedPeSize">loaded PE image size</param>
/// <param name="inMemoryPdbAddress">in memory PDB address or zero</param>
/// <param name="inMemoryPdbSize">in memory PDB size</param>
/// <param name="readMemory">read memory callback</param>
/// <returns>Symbol reader handle or zero if error</returns>
internal static IntPtr LoadSymbolsForModule([MarshalAs(UnmanagedType.LPWStr)] string assemblyPath, bool isFileLayout, ulong loadedPeAddress, int loadedPeSize,
ulong inMemoryPdbAddress, int inMemoryPdbSize, ReadMemoryDelegate readMemory)
{
try
{
TargetStream peStream = null;
if (assemblyPath == null && loadedPeAddress != 0)
{
peStream = new TargetStream(loadedPeAddress, loadedPeSize, readMemory);
}
TargetStream pdbStream = null;
if (inMemoryPdbAddress != 0)
{
pdbStream = new TargetStream(inMemoryPdbAddress, inMemoryPdbSize, readMemory);
}
OpenedReader openedReader = GetReader(assemblyPath, isFileLayout, peStream, pdbStream);
if (openedReader != null)
{
GCHandle gch = GCHandle.Alloc(openedReader);
return GCHandle.ToIntPtr(gch);
}
}
catch
{
}
return IntPtr.Zero;
}
/// <summary>
/// Cleanup and dispose of symbol reader handle
/// </summary>
/// <param name="symbolReaderHandle">symbol reader handle returned by LoadSymbolsForModule</param>
internal static void Dispose(IntPtr symbolReaderHandle)
{
Debug.Assert(symbolReaderHandle != IntPtr.Zero);
try
{
GCHandle gch = GCHandle.FromIntPtr(symbolReaderHandle);
((OpenedReader)gch.Target).Dispose();
gch.Free();
}
catch
{
}
}
internal static SequencePointCollection GetSequencePointCollection(int methodToken, MetadataReader reader)
{
Handle handle = MetadataTokens.Handle(methodToken);
if (handle.Kind != HandleKind.MethodDefinition)
throw new System.ArgumentException();
MethodDebugInformationHandle methodDebugHandle = ((MethodDefinitionHandle)handle).ToDebugInformationHandle();
if (methodDebugHandle.IsNil)
throw new System.ArgumentException();
MethodDebugInformation methodDebugInfo = reader.GetMethodDebugInformation(methodDebugHandle);
return methodDebugInfo.GetSequencePoints();
}
/// <summary>
/// Find current user code sequence point by IL offset.
/// </summary>
/// <param name="symbolReaderHandle">symbol reader handle returned by LoadSymbolsForModule</param>
/// <param name="methodToken">method token</param>
/// <param name="ilOffset">IL offset</param>
/// <param name="sequencePoint">sequence point return</param>
/// <returns>"Ok" if information is available</returns>
private static RetCode GetSequencePointByILOffset(IntPtr symbolReaderHandle, int methodToken, uint ilOffset, out DbgSequencePoint sequencePoint)
{
Debug.Assert(symbolReaderHandle != IntPtr.Zero);
sequencePoint.document = IntPtr.Zero;
sequencePoint.startLine = 0;
sequencePoint.startColumn = 0;
sequencePoint.endLine = 0;
sequencePoint.endColumn = 0;
sequencePoint.offset = 0;
try
{
GCHandle gch = GCHandle.FromIntPtr(symbolReaderHandle);
MetadataReader reader = ((OpenedReader)gch.Target).Reader;
SequencePointCollection sequencePoints = GetSequencePointCollection(methodToken, reader);
SequencePoint nearestPoint = sequencePoints.GetEnumerator().Current;
bool found = false;
foreach (SequencePoint point in sequencePoints)
{
if (found && point.Offset > ilOffset)
break;
if (point.StartLine != 0 && point.StartLine != SequencePoint.HiddenLine)
{
nearestPoint = point;
found = true;
}
}
if (!found)
return RetCode.Fail;
var fileName = reader.GetString(reader.GetDocument(nearestPoint.Document).Name);
sequencePoint.document = Marshal.StringToBSTR(fileName);
sequencePoint.startLine = nearestPoint.StartLine;
sequencePoint.startColumn = nearestPoint.StartColumn;
sequencePoint.endLine = nearestPoint.EndLine;
sequencePoint.endColumn = nearestPoint.EndColumn;
sequencePoint.offset = nearestPoint.Offset;
fileName = null;
}
catch
{
return RetCode.Exception;
}
return RetCode.OK;
}
/// <summary>
/// Find IL offset for next close user code sequence point by IL offset.
/// </summary>
/// <param name="symbolReaderHandle">symbol reader handle returned by LoadSymbolsForModule</param>
/// <param name="methodToken">method token</param>
/// <param name="ilOffset">IL offset</param>
/// <param name="sequencePoint">sequence point return</param>
/// <param name="noUserCodeFound">return 1 in case all sequence points checked and no user code was found, otherwise return 0</param>
/// <returns>"Ok" if information is available</returns>
private static RetCode GetNextSequencePointByILOffset(IntPtr symbolReaderHandle, int methodToken, uint ilOffset, out uint ilCloseOffset, out int noUserCodeFound)
{
Debug.Assert(symbolReaderHandle != IntPtr.Zero);
ilCloseOffset = 0;
noUserCodeFound = 0;
try
{
GCHandle gch = GCHandle.FromIntPtr(symbolReaderHandle);
MetadataReader reader = ((OpenedReader)gch.Target).Reader;
SequencePointCollection sequencePoints = GetSequencePointCollection(methodToken, reader);
foreach (SequencePoint point in sequencePoints)
{
if (point.StartLine == 0 || point.StartLine == SequencePoint.HiddenLine)
continue;
if (point.Offset >= ilOffset)
{
ilCloseOffset = (uint)point.Offset;
return RetCode.OK;
}
}
noUserCodeFound = 1;
return RetCode.Fail;
}
catch
{
return RetCode.Exception;
}
}
/// <summary>
/// Find and return last method's offset for user code.
/// </summary>
/// <param name="assemblyPath">file path of the assembly or null if the module is in-memory or dynamic</param>
/// <param name="methodToken">method token</param>
/// <param name="LastIlOffset">return last found IL offset in user code</param>
/// <returns>"Ok" if last IL offset was found</returns>
internal static RetCode GetMethodLastIlOffset(IntPtr symbolReaderHandle, int methodToken, out uint LastIlOffset)
{
Debug.Assert(symbolReaderHandle != IntPtr.Zero);
LastIlOffset = 0;
bool foundOffset = false;
try
{
GCHandle gch = GCHandle.FromIntPtr(symbolReaderHandle);
MetadataReader reader = ((OpenedReader)gch.Target).Reader;
// We don't use LINQ in order to reduce memory consumption for managed part, so, Reverse() usage not an option here.
// Note, SequencePointCollection is IEnumerable based collections.
foreach (SequencePoint p in GetSequencePointCollection(methodToken, reader))
{
if (p.StartLine == 0 || p.StartLine == SequencePoint.HiddenLine || p.Offset < 0)
continue;
// Method's IL start only from 0, use uint for IL offset.
LastIlOffset = (uint)p.Offset;
foundOffset = true;
}
}
catch
{
return RetCode.Exception;
}
return foundOffset ? RetCode.OK : RetCode.Fail;
}
[StructLayout(LayoutKind.Sequential)]
internal struct method_data_t
{
public int methodDef;
public int startLine; // first segment/method SequencePoint's startLine
public int endLine; // last segment/method SequencePoint's endLine
public int startColumn; // first segment/method SequencePoint's startColumn
public int endColumn; // last segment/method SequencePoint's endColumn
public method_data_t(int methodDef_, int startLine_, int endLine_, int startColumn_, int endColumn_)
{
methodDef = methodDef_;
startLine = startLine_;
endLine = endLine_;
startColumn = startColumn_;
endColumn = endColumn_;
}
public void SetRange(int startLine_, int endLine_, int startColumn_, int endColumn_)
{
startLine = startLine_;
endLine = endLine_;
startColumn = startColumn_;
endColumn = endColumn_;
}
public void SetRangeEnd(int endLine_, int endColumn_)
{
endLine = endLine_;
endColumn = endColumn_;
}
public void ExtendRange(int startLine_, int endLine_, int startColumn_, int endColumn_)
{
if (startLine > startLine_)
{
startLine = startLine_;
startColumn = startColumn_;
}
else if (startLine == startLine_ && startColumn > startColumn_)
{
startColumn = startColumn_;
}
if (endLine < endLine_)
{
endLine = endLine_;
endColumn = endColumn_;
}
else if (endLine == endLine_ && endColumn < endColumn_)
{
endColumn = endColumn_;
}
}
}
[StructLayout(LayoutKind.Sequential)]
internal struct file_methods_data_t
{
public IntPtr document;
public int methodNum;
public IntPtr methodsData; // method_data_t*
}
[StructLayout(LayoutKind.Sequential)]
internal struct module_methods_data_t
{
public int fileNum;
public IntPtr moduleMethodsData; // file_methods_data_t*
}
/// <summary>
/// Get all method ranges for all methods (in case of constructors ranges for all segments).
/// </summary>
/// <param name="symbolReaderHandle">symbol reader handle returned by LoadSymbolsForModule</param>
/// <param name="constrNum">number of constructors tokens in array</param>
/// <param name="constrTokens">array of constructors tokens</param>
/// <param name="normalNum">number of normal methods tokens in array</param>
/// <param name="normalTokens">array of normal methods tokens</param>
/// <param name="data">pointer to memory with result</param>
/// <returns>"Ok" if information is available</returns>
internal static RetCode GetModuleMethodsRanges(IntPtr symbolReaderHandle, int constrNum, IntPtr constrTokens, int normalNum, IntPtr normalTokens, out IntPtr data)
{
Debug.Assert(symbolReaderHandle != IntPtr.Zero);
data = IntPtr.Zero;
var unmanagedPTRList = new List<IntPtr>();
var unmanagedBSTRList = new List<IntPtr>();
try
{
GCHandle gch = GCHandle.FromIntPtr(symbolReaderHandle);
MetadataReader reader = ((OpenedReader)gch.Target).Reader;
Dictionary<DocumentHandle, List<method_data_t>> ModuleData = new Dictionary<DocumentHandle, List<method_data_t>>();
int elementSize = 4;
// Make sure we add constructors related data first, since this data can't be nested for sure.
for (int i = 0; i < constrNum * elementSize; i += elementSize)
{
int methodToken = Marshal.ReadInt32(constrTokens, i);
method_data_t currentData = new method_data_t(methodToken, 0, 0, 0, 0);
DocumentHandle currentDocHandle = new DocumentHandle();
foreach (SequencePoint p in GetSequencePointCollection(methodToken, reader))
{
if (p.StartLine == 0 || p.StartLine == SequencePoint.HiddenLine)
continue;
if (currentData.startLine == 0)
{
currentData.SetRange(p.StartLine, p.EndLine, p.StartColumn, p.EndColumn);
currentDocHandle = p.Document;
}
// same segment only in case same file and on next line or on same line but on the right
else if ((p.StartLine == currentData.endLine + 1 ||
(p.StartLine == currentData.endLine && p.StartColumn > currentData.endColumn)) &&
currentDocHandle == p.Document )
{
currentData.SetRangeEnd(p.EndLine, p.EndColumn);
}
else // SequencePoint from another segment
{
if (!ModuleData.ContainsKey(currentDocHandle))
ModuleData[currentDocHandle] = new List<method_data_t>();
ModuleData[currentDocHandle].Add(currentData);
currentData.SetRange(p.StartLine, p.EndLine, p.StartColumn, p.EndColumn);
currentDocHandle = p.Document;
}
}
if (currentData.startLine != 0)
{
if (!ModuleData.ContainsKey(currentDocHandle))
ModuleData[currentDocHandle] = new List<method_data_t>();
ModuleData[currentDocHandle].Add(currentData);
}
}
for (int i = 0; i < normalNum * elementSize; i += elementSize)
{
int methodToken = Marshal.ReadInt32(normalTokens, i);
method_data_t currentData = new method_data_t(methodToken, 0, 0, 0, 0);
DocumentHandle currentDocHandle = new DocumentHandle();
foreach (SequencePoint p in GetSequencePointCollection(methodToken, reader))
{
if (p.StartLine == 0 || p.StartLine == SequencePoint.HiddenLine)
continue;
// first access, init all fields and document with proper data from first user code sequence point
if (currentData.startLine == 0)
{
currentData.SetRange(p.StartLine, p.EndLine, p.StartColumn, p.EndColumn);
currentDocHandle = p.Document;
continue;
}
currentData.ExtendRange(p.StartLine, p.EndLine, p.StartColumn, p.EndColumn);
}
if (currentData.startLine != 0)
{
if (!ModuleData.ContainsKey(currentDocHandle))
ModuleData[currentDocHandle] = new List<method_data_t>();
ModuleData[currentDocHandle].Add(currentData);
}
}
int structModuleMethodsDataSize = Marshal.SizeOf<file_methods_data_t>();
module_methods_data_t managedData;
managedData.fileNum = ModuleData.Count;
managedData.moduleMethodsData = Marshal.AllocCoTaskMem(ModuleData.Count * structModuleMethodsDataSize);
unmanagedPTRList.Add(managedData.moduleMethodsData);
IntPtr currentModuleMethodsDataPtr = managedData.moduleMethodsData;
foreach (KeyValuePair<DocumentHandle, List<method_data_t>> fileData in ModuleData)
{
int structMethodDataSize = Marshal.SizeOf<method_data_t>();
file_methods_data_t fileMethodData;
fileMethodData.document = Marshal.StringToBSTR(reader.GetString(reader.GetDocument(fileData.Key).Name));
unmanagedBSTRList.Add(fileMethodData.document);
fileMethodData.methodNum = fileData.Value.Count;
fileMethodData.methodsData = Marshal.AllocCoTaskMem(fileData.Value.Count * structMethodDataSize);
unmanagedPTRList.Add(fileMethodData.methodsData);
IntPtr currentMethodDataPtr = fileMethodData.methodsData;
foreach (var p in fileData.Value)
{
Marshal.StructureToPtr(p, currentMethodDataPtr, false);
currentMethodDataPtr = currentMethodDataPtr + structMethodDataSize;
}
Marshal.StructureToPtr(fileMethodData, currentModuleMethodsDataPtr, false);
currentModuleMethodsDataPtr = currentModuleMethodsDataPtr + structModuleMethodsDataSize;
}
data = Marshal.AllocCoTaskMem(Marshal.SizeOf<module_methods_data_t>());
unmanagedPTRList.Add(data);
Marshal.StructureToPtr(managedData, data, false);
}
catch
{
foreach (var p in unmanagedPTRList)
{
Marshal.FreeCoTaskMem(p);
}
foreach (var p in unmanagedBSTRList)
{
Marshal.FreeBSTR(p);
}
return RetCode.Exception;
}
return RetCode.OK;
}
[StructLayout(LayoutKind.Sequential)]
internal struct resolved_bp_t
{
public int startLine;
public int endLine;
public int ilOffset;
public int methodToken;
public resolved_bp_t(int startLine_, int endLine_, int ilOffset_, int methodToken_)
{
startLine = startLine_;
endLine = endLine_;
ilOffset = ilOffset_;
methodToken = methodToken_;
}
}
/// <summary>
/// Resolve breakpoints.
/// </summary>
/// <param name="symbolReaderHandle">symbol reader handle returned by LoadSymbolsForModule</param>
/// <param name="tokenNum">number of elements in Tokens</param>
/// <param name="Tokens">array of method tokens, that have sequence point with sourceLine</param>
/// <param name="sourceLine">initial source line for resolve</param>
/// <param name="nestedToken">close nested token for sourceLine</param>
/// <param name="Count">entry's count in data</param>
/// <param name="data">pointer to memory with result</param>
/// <returns>"Ok" if information is available</returns>
internal static RetCode ResolveBreakPoints(IntPtr symbolReaderHandle, int tokenNum, IntPtr Tokens, int sourceLine, int nestedToken, out int Count, out IntPtr data)
{
Debug.Assert(symbolReaderHandle != IntPtr.Zero);
Count = 0;
data = IntPtr.Zero;
var list = new List<resolved_bp_t>();
try
{
GCHandle gch = GCHandle.FromIntPtr(symbolReaderHandle);
MetadataReader reader = ((OpenedReader)gch.Target).Reader;
// In case nestedToken + sourceLine is part of constructor (tokenNum > 1) we could have cases:
// 1. type FieldName1 = new Type();
// void MethodName() {}; type FieldName2 = new Type(); ... <-- sourceLine
// 2. type FieldName1 = new Type(); void MethodName() {}; ... <-- sourceLine
// type FieldName2 = new Type();
// In first case, we need setup breakpoint in nestedToken's method (MethodName in examples above), in second - ignore it.
// In case nestedToken + sourceLine in normal method we could have cases:
// 1. ... line without code ... <-- sourceLine
// void MethodName { ...
// 2. ... line with code ... void MethodName { ... <-- sourceLine
// We need check if nestedToken's method code closer to sourceLine than code from methodToken's method.
// If sourceLine closer to nestedToken's method code - setup breakpoint in nestedToken's method.
SequencePoint FirstSequencePointForSourceLine(int methodToken)
{
// Note, SequencePoints ordered by IL offsets, not by line numbers.
// For example, infinite loop `while(true)` will have IL offset after cycle body's code.
SequencePoint nearestSP = new SequencePoint();
foreach (SequencePoint p in GetSequencePointCollection(methodToken, reader))
{
if (p.StartLine == 0 || p.StartLine == SequencePoint.HiddenLine || p.EndLine < sourceLine)
continue;
// first access, assign to first user code sequence point
if (nearestSP.StartLine == 0)
{
nearestSP = p;
continue;
}
if (p.EndLine != nearestSP.EndLine)
{
if (p.EndLine < nearestSP.EndLine)
nearestSP = p;
}
else
{
if (p.EndColumn < nearestSP.EndColumn)
nearestSP = p;
}
}
return nearestSP;
}
int elementSize = 4;
for (int i = 0; i < tokenNum * elementSize; i += elementSize)
{
int methodToken = Marshal.ReadInt32(Tokens, i);
SequencePoint current_p = FirstSequencePointForSourceLine(methodToken);
// Note, we don't check that current_p was found or not, since we know for sure, that sourceLine could be resolved in method.
// Same idea for nested_p below, if we have nestedToken - it will be resolved for sure.
if (nestedToken != 0)
{
SequencePoint nested_p = FirstSequencePointForSourceLine(nestedToken);
if (current_p.EndLine > nested_p.EndLine || (current_p.EndLine == nested_p.EndLine && current_p.EndColumn > nested_p.EndColumn))
{
list.Add(new resolved_bp_t(nested_p.StartLine, nested_p.EndLine, nested_p.Offset, nestedToken));
// (tokenNum > 1) can have only lines, that added to multiple constructors, in this case - we will have same for all Tokens,
// we need unique tokens only for breakpoints, prevent adding nestedToken multiple times.
break;
}
}
nestedToken = 0; // Don't check nested block next cycle (will have same results).
list.Add(new resolved_bp_t(current_p.StartLine, current_p.EndLine, current_p.Offset, methodToken));
}
if (list.Count == 0)
return RetCode.OK;
int structSize = Marshal.SizeOf<resolved_bp_t>();
data = Marshal.AllocCoTaskMem(list.Count * structSize);
IntPtr dataPtr = data;
foreach (var p in list)
{
Marshal.StructureToPtr(p, dataPtr, false);
dataPtr = dataPtr + structSize;
}
Count = list.Count;
}
catch
{
if (data != IntPtr.Zero)
Marshal.FreeCoTaskMem(data);
data = IntPtr.Zero;
return RetCode.Exception;
}
return RetCode.OK;
}
internal static RetCode GetStepRangesFromIP(IntPtr symbolReaderHandle, int ip, int methodToken, out uint ilStartOffset, out uint ilEndOffset)
{
Debug.Assert(symbolReaderHandle != IntPtr.Zero);
ilStartOffset = 0;
ilEndOffset = 0;
try
{
GCHandle gch = GCHandle.FromIntPtr(symbolReaderHandle);
MetadataReader reader = ((OpenedReader)gch.Target).Reader;
var list = new List<SequencePoint>();
foreach (SequencePoint p in GetSequencePointCollection(methodToken, reader))
list.Add(p);
var pointsArray = list.ToArray();
for (int i = 1; i < pointsArray.Length; i++)
{
SequencePoint p = pointsArray[i];
if (p.Offset > ip && p.StartLine != 0 && p.StartLine != SequencePoint.HiddenLine)
{
ilStartOffset = (uint)pointsArray[0].Offset;
for (int j = i - 1; j > 0; j--)
{
if (pointsArray[j].Offset <= ip)
{
ilStartOffset = (uint)pointsArray[j].Offset;
break;
}
}
ilEndOffset = (uint)p.Offset;
return RetCode.OK;
}
}
// let's handle correctly last step range from last sequence point till
// end of the method.
if (pointsArray.Length > 0)
{
ilStartOffset = (uint)pointsArray[0].Offset;
for (int j = pointsArray.Length - 1; j > 0; j--)
{
if (pointsArray[j].Offset <= ip)
{
ilStartOffset = (uint)pointsArray[j].Offset;
break;
}
}
ilEndOffset = ilStartOffset; // Should set this to IL code size in calling code
return RetCode.OK;
}
}
catch
{
return RetCode.Exception;
}
return RetCode.Fail;
}
internal static RetCode GetLocalVariableNameAndScope(IntPtr symbolReaderHandle, int methodToken, int localIndex, out IntPtr localVarName, out int ilStartOffset, out int ilEndOffset)
{
localVarName = IntPtr.Zero;
ilStartOffset = 0;
ilEndOffset = 0;
try
{
string localVar = null;
if (!GetLocalVariableAndScopeByIndex(symbolReaderHandle, methodToken, localIndex, out localVar, out ilStartOffset, out ilEndOffset))
return RetCode.Fail;
localVarName = Marshal.StringToBSTR(localVar);
localVar = null;
}
catch
{
return RetCode.Exception;
}
return RetCode.OK;
}
internal static bool GetLocalVariableAndScopeByIndex(IntPtr symbolReaderHandle, int methodToken, int localIndex, out string localVarName, out int ilStartOffset, out int ilEndOffset)
{
Debug.Assert(symbolReaderHandle != IntPtr.Zero);
localVarName = null;
ilStartOffset = 0;
ilEndOffset = 0;
// caller must care about exception during this code execution
GCHandle gch = GCHandle.FromIntPtr(symbolReaderHandle);
MetadataReader reader = ((OpenedReader)gch.Target).Reader;
Handle handle = MetadataTokens.Handle(methodToken);
if (handle.Kind != HandleKind.MethodDefinition)
return false;
MethodDebugInformationHandle methodDebugHandle = ((MethodDefinitionHandle)handle).ToDebugInformationHandle();
LocalScopeHandleCollection localScopes = reader.GetLocalScopes(methodDebugHandle);
foreach (LocalScopeHandle scopeHandle in localScopes)
{
LocalScope scope = reader.GetLocalScope(scopeHandle);
LocalVariableHandleCollection localVars = scope.GetLocalVariables();
foreach (LocalVariableHandle varHandle in localVars)
{
LocalVariable localVar = reader.GetLocalVariable(varHandle);
if (localVar.Index == localIndex)
{
if (localVar.Attributes == LocalVariableAttributes.DebuggerHidden)
return false;
localVarName = reader.GetString(localVar.Name);
ilStartOffset = scope.StartOffset;
ilEndOffset = scope.EndOffset;
return true;
}
}
}
return false;
}
/// <summary>
/// Returns local variable name for given local index and IL offset.
/// </summary>
/// <param name="symbolReaderHandle">symbol reader handle returned by LoadSymbolsForModule</param>
/// <param name="methodToken">method token</param>
/// <param name="data">pointer to memory with histed local scopes</param>
/// <param name="hoistedLocalScopesCount">histed local scopes count</param>
/// <returns>"Ok" if information is available</returns>
internal static RetCode GetHoistedLocalScopes(IntPtr symbolReaderHandle, int methodToken, out IntPtr data, out int hoistedLocalScopesCount)
{
data = IntPtr.Zero;
hoistedLocalScopesCount = 0;
try
{
GCHandle gch = GCHandle.FromIntPtr(symbolReaderHandle);
MetadataReader reader = ((OpenedReader)gch.Target).Reader;
Handle handle = MetadataTokens.Handle(methodToken);
if (handle.Kind != HandleKind.MethodDefinition)
return RetCode.Fail;
MethodDebugInformationHandle methodDebugInformationHandle = ((MethodDefinitionHandle)handle).ToDebugInformationHandle();
var entityHandle = MetadataTokens.EntityHandle(MetadataTokens.GetToken(methodDebugInformationHandle.ToDefinitionHandle()));
// Guid is taken from Roslyn source code:
// https://github.com/dotnet/roslyn/blob/afd10305a37c0ffb2cfb2c2d8446154c68cfa87a/src/Dependencies/CodeAnalysis.Debugging/PortableCustomDebugInfoKinds.cs#L14
Guid stateMachineHoistedLocalScopes = new Guid("6DA9A61E-F8C7-4874-BE62-68BC5630DF71");
var HoistedLocalScopes = new List<UInt32>();
foreach (var cdiHandle in reader.GetCustomDebugInformation(entityHandle))
{
var cdi = reader.GetCustomDebugInformation(cdiHandle);
if (reader.GetGuid(cdi.Kind) == stateMachineHoistedLocalScopes)
{
// Format of this blob is taken from Roslyn source code:
// https://github.com/dotnet/roslyn/blob/afd10305a37c0ffb2cfb2c2d8446154c68cfa87a/src/Compilers/Core/Portable/PEWriter/MetadataWriter.PortablePdb.cs#L600
var blobReader = reader.GetBlobReader(cdi.Value);
while (blobReader.Offset < blobReader.Length)
{
HoistedLocalScopes.Add(blobReader.ReadUInt32()); // StartOffset
HoistedLocalScopes.Add(blobReader.ReadUInt32()); // Length
}
}
}
if (HoistedLocalScopes.Count == 0)
return RetCode.Fail;
data = Marshal.AllocCoTaskMem(HoistedLocalScopes.Count * 4);
IntPtr dataPtr = data;
foreach (var p in HoistedLocalScopes)
{
Marshal.StructureToPtr(p, dataPtr, false);
dataPtr = dataPtr + 4;
}
hoistedLocalScopesCount = HoistedLocalScopes.Count / 2;
}
catch
{
if (data != IntPtr.Zero)
Marshal.FreeCoTaskMem(data);
return RetCode.Exception;
}
return RetCode.OK;
}
/// <summary>
/// Returns local variable name for given local index and IL offset.
/// </summary>
/// <param name="symbolReaderHandle">symbol reader handle returned by LoadSymbolsForModule</param>
/// <param name="methodToken">method token</param>
/// <param name="localIndex">local variable index</param>
/// <param name="localVarName">local variable name return</param>
/// <returns>true if name has been found</returns>
internal static bool GetLocalVariableName(IntPtr symbolReaderHandle, int methodToken, int localIndex, out IntPtr localVarName)
{
localVarName = IntPtr.Zero;
string localVar = null;
if (!GetLocalVariableByIndex(symbolReaderHandle, methodToken, localIndex, out localVar))
return false;
localVarName = Marshal.StringToBSTR(localVar);
localVar = null;
return true;
}
/// <summary>
/// Helper method to return local variable name for given local index and IL offset.
/// </summary>
/// <param name="symbolReaderHandle">symbol reader handle returned by LoadSymbolsForModule</param>
/// <param name="methodToken">method token</param>
/// <param name="localIndex">local variable index</param>
/// <param name="localVarName">local variable name return</param>
/// <returns>true if name has been found</returns>
internal static bool GetLocalVariableByIndex(IntPtr symbolReaderHandle, int methodToken, int localIndex, out string localVarName)
{
Debug.Assert(symbolReaderHandle != IntPtr.Zero);
localVarName = null;
try
{
GCHandle gch = GCHandle.FromIntPtr(symbolReaderHandle);
MetadataReader reader = ((OpenedReader)gch.Target).Reader;
Handle handle = MetadataTokens.Handle(methodToken);
if (handle.Kind != HandleKind.MethodDefinition)
return false;
MethodDebugInformationHandle methodDebugHandle = ((MethodDefinitionHandle)handle).ToDebugInformationHandle();
LocalScopeHandleCollection localScopes = reader.GetLocalScopes(methodDebugHandle);
foreach (LocalScopeHandle scopeHandle in localScopes)
{
LocalScope scope = reader.GetLocalScope(scopeHandle);
LocalVariableHandleCollection localVars = scope.GetLocalVariables();
foreach (LocalVariableHandle varHandle in localVars)
{
LocalVariable localVar = reader.GetLocalVariable(varHandle);
if (localVar.Index == localIndex)
{
if (localVar.Attributes == LocalVariableAttributes.DebuggerHidden)
return false;
localVarName = reader.GetString(localVar.Name);
return true;
}
}
}