-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
Copy pathPdbWriter.cs
1031 lines (888 loc) · 78.2 KB
/
PdbWriter.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
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.Emit;
using Roslyn.Utilities;
namespace Microsoft.Cci
{
//Catch all of the exceptions originating from writing PDBs and
//surface them as PDB-writing failure diagnostics to the user.
//Unfortunately, an exception originating in a user-implemented
//Stream derivation will come out of the symbol writer as a COMException
//missing all of the original exception info.
internal sealed class PdbWritingException : Exception
{
internal PdbWritingException(Exception inner) :
base(inner.Message, inner)
{
}
}
internal sealed class PdbWriter : IDisposable
{
internal const uint HiddenLocalAttributesValue = 1u;
internal const uint DefaultLocalAttributesValue = 0u;
private static Type s_lazyCorSymWriterSxSType;
private readonly ComStreamWrapper _stream;
private readonly string _fileName;
private readonly Func<object> _symWriterFactory;
private MetadataWriter _metadataWriter;
private ISymUnmanagedWriter2 _symWriter;
private readonly Dictionary<DebugSourceDocument, ISymUnmanagedDocumentWriter> _documentMap = new Dictionary<DebugSourceDocument, ISymUnmanagedDocumentWriter>();
// { INamespace or ITypeReference -> qualified name }
private readonly Dictionary<object, string> _qualifiedNameCache = new Dictionary<object, string>();
// sequence point buffers:
private uint[] _sequencePointOffsets;
private uint[] _sequencePointStartLines;
private uint[] _sequencePointStartColumns;
private uint[] _sequencePointEndLines;
private uint[] _sequencePointEndColumns;
public PdbWriter(string fileName, Stream stream, Func<object> symWriterFactory = null)
{
_stream = new ComStreamWrapper(stream);
_fileName = fileName;
_symWriterFactory = symWriterFactory;
CreateSequencePointBuffers(capacity: 64);
}
public void Dispose()
{
this.Close();
GC.SuppressFinalize(this);
}
~PdbWriter()
{
this.Close();
}
public void Close()
{
try
{
_symWriter?.Close();
_symWriter = null;
}
catch (Exception ex)
{
throw new PdbWritingException(ex);
}
}
private IModule Module => Context.Module;
private EmitContext Context => _metadataWriter.Context;
public void SerializeDebugInfo(IMethodBody methodBody, uint localSignatureToken, CustomDebugInfoWriter customDebugInfoWriter)
{
Debug.Assert(_metadataWriter != null);
bool isIterator = methodBody.StateMachineTypeName != null;
bool emitDebugInfo = isIterator || methodBody.HasAnySequencePoints;
if (!emitDebugInfo)
{
return;
}
uint methodToken = _metadataWriter.GetMethodToken(methodBody.MethodDefinition);
OpenMethod(methodToken);
var localScopes = methodBody.LocalScopes;
// CCI originally didn't have the notion of the default scope that is open
// when a method is opened. In order to reproduce CSC PDBs, this must be added. Otherwise
// a seemingly unnecessary scope that contains only other scopes is put in the PDB.
if (localScopes.Length > 0)
{
this.DefineScopeLocals(localScopes[0], localSignatureToken);
}
// NOTE: This is an attempt to match Dev10's apparent behavior. For iterator methods (i.e. the method
// that appears in source, not the synthesized ones), Dev10 only emits the ForwardIterator and IteratorLocal
// custom debug info (e.g. there will be no information about the usings that were in scope).
if (!isIterator)
{
IMethodDefinition forwardToMethod;
if (customDebugInfoWriter.ShouldForwardNamespaceScopes(Context, methodBody, methodToken, out forwardToMethod))
{
if (forwardToMethod != null)
{
UsingNamespace("@" + _metadataWriter.GetMethodToken(forwardToMethod), methodBody.MethodDefinition);
}
// otherwise, the forwarding is done via custom debug info
}
else
{
this.DefineNamespaceScopes(methodBody);
}
}
DefineLocalScopes(localScopes, localSignatureToken);
EmitSequencePoints(methodBody.GetSequencePoints());
AsyncMethodBodyDebugInfo asyncDebugInfo = methodBody.AsyncDebugInfo;
if (asyncDebugInfo != null)
{
SetAsyncInfo(
methodToken,
_metadataWriter.GetMethodToken(asyncDebugInfo.KickoffMethod),
asyncDebugInfo.CatchHandlerOffset,
asyncDebugInfo.YieldOffsets,
asyncDebugInfo.ResumeOffsets);
}
var compilationOptions = Context.ModuleBuilder.CommonCompilation.Options;
// We need to avoid emitting CDI DynamicLocals = 5 and EditAndContinueLocalSlotMap = 6 for files processed by WinMDExp until
// bug #1067635 is fixed and available in SDK.
bool suppressNewCustomDebugInfo = !compilationOptions.ExtendedCustomDebugInformation ||
(compilationOptions.OutputKind == OutputKind.WindowsRuntimeMetadata);
bool emitEncInfo = compilationOptions.EnableEditAndContinue && !_metadataWriter.IsFullMetadata;
bool emitExternNamespaces;
byte[] blob = customDebugInfoWriter.SerializeMethodDebugInfo(Context, methodBody, methodToken, emitEncInfo, suppressNewCustomDebugInfo, out emitExternNamespaces);
if (blob != null)
{
DefineCustomMetadata("MD2", blob);
}
if (emitExternNamespaces)
{
this.DefineAssemblyReferenceAliases();
}
// TODO: it's not clear why we are closing a scope here with IL length:
CloseScope((uint)methodBody.IL.Length);
CloseMethod();
}
private void DefineNamespaceScopes(IMethodBody methodBody)
{
var module = Module;
bool isVisualBasic = module.GenerateVisualBasicStylePdb;
IMethodDefinition method = methodBody.MethodDefinition;
var namespaceScopes = methodBody.ImportScope;
// NOTE: All extern aliases are stored on the outermost namespace scope.
PooledHashSet<string> lazyDeclaredExternAliases = null;
if (!isVisualBasic)
{
foreach (var import in GetLastScope(namespaceScopes).GetUsedNamespaces(Context))
{
if (import.TargetNamespaceOpt == null && import.TargetTypeOpt == null)
{
Debug.Assert(import.AliasOpt != null);
Debug.Assert(import.TargetAssemblyOpt == null);
if (lazyDeclaredExternAliases == null)
{
lazyDeclaredExternAliases = PooledHashSet<string>.GetInstance();
}
lazyDeclaredExternAliases.Add(import.AliasOpt);
}
}
}
// file and namespace level
for (IImportScope scope = namespaceScopes; scope != null; scope = scope.Parent)
{
foreach (UsedNamespaceOrType import in scope.GetUsedNamespaces(Context))
{
var importString = TryEncodeImport(import, lazyDeclaredExternAliases, isProjectLevel: false);
if (importString != null)
{
UsingNamespace(importString, method);
}
}
}
lazyDeclaredExternAliases?.Free();
// project level
if (isVisualBasic)
{
string defaultNamespace = module.DefaultNamespace;
if (defaultNamespace != null)
{
// VB marks the default/root namespace with an asterisk
UsingNamespace("*" + defaultNamespace, module);
}
foreach (string assemblyName in module.LinkedAssembliesDebugInfo)
{
UsingNamespace("&" + assemblyName, module);
}
foreach (UsedNamespaceOrType import in module.GetImports(Context))
{
var importString = TryEncodeImport(import, null, isProjectLevel: true);
if (importString != null)
{
UsingNamespace(importString, method);
}
}
// VB current namespace -- VB appends the namespace of the container without prefixes
UsingNamespace(GetOrCreateSerializedNamespaceName(method.ContainingNamespace), method);
}
}
private IImportScope GetLastScope(IImportScope scope)
{
while (true)
{
var parent = scope.Parent;
if (parent == null)
{
return scope;
}
scope = parent;
}
}
private void DefineAssemblyReferenceAliases()
{
foreach (AssemblyReferenceAlias alias in Module.GetAssemblyReferenceAliases(Context))
{
UsingNamespace("Z" + alias.Name + " " + alias.Assembly.GetDisplayName(), Module);
}
}
private string TryEncodeImport(UsedNamespaceOrType import, HashSet<string> declaredExternAliasesOpt, bool isProjectLevel)
{
// NOTE: Dev12 has related cases "I" and "O" in EMITTER::ComputeDebugNamespace,
// but they were probably implementation details that do not affect roslyn.
if (Module.GenerateVisualBasicStylePdb)
{
// VB doesn't support extern aliases
Debug.Assert(import.TargetAssemblyOpt == null);
Debug.Assert(declaredExternAliasesOpt == null);
if (import.TargetTypeOpt != null)
{
Debug.Assert(import.TargetNamespaceOpt == null);
Debug.Assert(import.TargetAssemblyOpt == null);
// Native compiler doesn't write imports with generic types to PDB.
if (import.TargetTypeOpt.IsTypeSpecification())
{
return null;
}
string typeName = GetOrCreateSerializedTypeName(import.TargetTypeOpt);
if (import.AliasOpt != null)
{
return (isProjectLevel ? "@PA:" : "@FA:") + import.AliasOpt + "=" + typeName;
}
else
{
return (isProjectLevel ? "@PT:" : "@FT:") + typeName;
}
}
else if (import.TargetNamespaceOpt != null)
{
string namespaceName = GetOrCreateSerializedNamespaceName(import.TargetNamespaceOpt);
if (import.AliasOpt == null)
{
return (isProjectLevel ? "@P:" : "@F:") + namespaceName;
}
else
{
return (isProjectLevel ? "@PA:" : "@FA:") + import.AliasOpt + "=" + namespaceName;
}
}
else
{
Debug.Assert(import.AliasOpt != null);
Debug.Assert(import.TargetXmlNamespaceOpt != null);
return (isProjectLevel ? "@PX:" : "@FX:") + import.AliasOpt + "=" + import.TargetXmlNamespaceOpt;
}
}
else
{
Debug.Assert(import.TargetXmlNamespaceOpt == null);
if (import.TargetTypeOpt != null)
{
Debug.Assert(import.TargetNamespaceOpt == null);
Debug.Assert(import.TargetAssemblyOpt == null);
string typeName = GetOrCreateSerializedTypeName(import.TargetTypeOpt);
return (import.AliasOpt != null) ?
"A" + import.AliasOpt + " T" + typeName :
"T" + typeName;
}
else if (import.TargetNamespaceOpt != null)
{
string namespaceName = GetOrCreateSerializedNamespaceName(import.TargetNamespaceOpt);
if (import.AliasOpt != null)
{
return (import.TargetAssemblyOpt != null) ?
"A" + import.AliasOpt + " E" + namespaceName + " " + GetAssemblyReferenceAlias(import.TargetAssemblyOpt, declaredExternAliasesOpt) :
"A" + import.AliasOpt + " U" + namespaceName;
}
else
{
return (import.TargetAssemblyOpt != null) ?
"E" + namespaceName + " " + GetAssemblyReferenceAlias(import.TargetAssemblyOpt, declaredExternAliasesOpt) :
"U" + namespaceName;
}
}
else
{
Debug.Assert(import.AliasOpt != null);
Debug.Assert(import.TargetAssemblyOpt == null);
return "X" + import.AliasOpt;
}
}
}
internal string GetOrCreateSerializedNamespaceName(INamespace @namespace)
{
string result;
if (!_qualifiedNameCache.TryGetValue(@namespace, out result))
{
result = TypeNameSerializer.BuildQualifiedNamespaceName(@namespace);
_qualifiedNameCache.Add(@namespace, result);
}
return result;
}
internal string GetOrCreateSerializedTypeName(ITypeReference typeReference)
{
string result;
if (!_qualifiedNameCache.TryGetValue(typeReference, out result))
{
if (Module.GenerateVisualBasicStylePdb)
{
result = SerializeVisualBasicImportTypeReference(typeReference);
}
else
{
result = TypeNameSerializer.GetSerializedTypeName(typeReference, Context);
}
_qualifiedNameCache.Add(typeReference, result);
}
return result;
}
private string SerializeVisualBasicImportTypeReference(ITypeReference typeReference)
{
Debug.Assert(typeReference as IArrayTypeReference == null);
Debug.Assert(typeReference as IPointerTypeReference == null);
Debug.Assert(typeReference as IManagedPointerTypeReference == null);
Debug.Assert(!typeReference.IsTypeSpecification());
var result = PooledStringBuilder.GetInstance();
ArrayBuilder<string> nestedNamesReversed;
INestedTypeReference nestedType = typeReference.AsNestedTypeReference;
if (nestedType != null)
{
nestedNamesReversed = ArrayBuilder<string>.GetInstance();
while (nestedType != null)
{
nestedNamesReversed.Add(nestedType.Name);
typeReference = nestedType.GetContainingType(_metadataWriter.Context);
nestedType = typeReference.AsNestedTypeReference;
}
}
else
{
nestedNamesReversed = null;
}
INamespaceTypeReference namespaceType = typeReference.AsNamespaceTypeReference;
Debug.Assert(namespaceType != null);
string namespaceName = namespaceType.NamespaceName;
if (namespaceName.Length != 0)
{
result.Builder.Append(namespaceName);
result.Builder.Append('.');
}
result.Builder.Append(namespaceType.Name);
if (nestedNamesReversed != null)
{
for (int i = nestedNamesReversed.Count - 1; i >= 0; i--)
{
result.Builder.Append('.');
result.Builder.Append(nestedNamesReversed[i]);
}
nestedNamesReversed.Free();
}
return result.ToStringAndFree();
}
private string GetAssemblyReferenceAlias(IAssemblyReference assembly, HashSet<string> declaredExternAliases)
{
var allAliases = _metadataWriter.Context.Module.GetAssemblyReferenceAliases(_metadataWriter.Context);
foreach (AssemblyReferenceAlias alias in allAliases)
{
// Multiple aliases may be given to an assembly reference.
// We find one that is in scope (was imported via extern alias directive).
// If multiple are in scope then use the first one.
// NOTE: Dev12 uses the one that appeared in source, whereas we use
// the first one that COULD have appeared in source. (DevDiv #913022)
// The reason we're not just using the alias from the syntax is that
// it is non-trivial to locate. In particular, since "." may be used in
// place of "::", determining whether the first identifier in the name is
// the alias requires binding. For example, "using A.B;" could refer to
// either "A::B" or "global::A.B".
if (assembly == alias.Assembly && declaredExternAliases.Contains(alias.Name))
{
return alias.Name;
}
}
// no alias defined in scope for given assembly -> error in compiler
throw ExceptionUtilities.Unreachable;
}
private void DefineLocalScopes(ImmutableArray<LocalScope> scopes, uint localSignatureToken)
{
// The order of OpenScope and CloseScope calls must follow the scope nesting.
var scopeStack = ArrayBuilder<LocalScope>.GetInstance();
for (int i = 1; i < scopes.Length; i++)
{
var currentScope = scopes[i];
// Close any scopes that have finished.
while (scopeStack.Count > 0)
{
LocalScope topScope = scopeStack.Last();
if (currentScope.Offset < topScope.Offset + topScope.Length)
{
break;
}
scopeStack.RemoveLast();
CloseScope(topScope.Offset + topScope.Length);
}
// Open this scope.
scopeStack.Add(currentScope);
OpenScope(currentScope.Offset);
this.DefineScopeLocals(currentScope, localSignatureToken);
}
// Close remaining scopes.
for (int i = scopeStack.Count - 1; i >= 0; i--)
{
LocalScope scope = scopeStack[i];
CloseScope(scope.Offset + scope.Length);
}
scopeStack.Free();
}
private void DefineScopeLocals(LocalScope currentScope, uint localSignatureToken)
{
foreach (ILocalDefinition scopeConstant in currentScope.Constants)
{
uint token = _metadataWriter.SerializeLocalConstantSignature(scopeConstant);
if (!_metadataWriter.IsLocalNameTooLong(scopeConstant))
{
DefineLocalConstant(scopeConstant.Name, scopeConstant.CompileTimeValue.Value, _metadataWriter.GetConstantTypeCode(scopeConstant), token);
}
}
foreach (ILocalDefinition scopeLocal in currentScope.Variables)
{
if (!_metadataWriter.IsLocalNameTooLong(scopeLocal))
{
Debug.Assert(scopeLocal.SlotIndex >= 0);
DefineLocalVariable((uint)scopeLocal.SlotIndex, scopeLocal.Name, scopeLocal.PdbAttributes, localSignatureToken);
}
}
}
#region SymWriter calls
private static Type GetCorSymWriterSxSType()
{
if (s_lazyCorSymWriterSxSType == null)
{
// If an exception is thrown we propagate it - we want to report it every time.
s_lazyCorSymWriterSxSType = Marshal.GetTypeFromCLSID(new Guid("0AE2DEB0-F901-478b-BB9F-881EE8066788"));
}
return s_lazyCorSymWriterSxSType;
}
public void SetMetadataEmitter(MetadataWriter metadataWriter)
{
try
{
var instance = (ISymUnmanagedWriter2)(_symWriterFactory != null ? _symWriterFactory() : Activator.CreateInstance(GetCorSymWriterSxSType()));
instance.Initialize(new PdbMetadataWrapper(metadataWriter), _fileName, _stream, true);
_metadataWriter = metadataWriter;
_symWriter = instance;
}
catch (Exception ex)
{
throw new PdbWritingException(ex);
}
}
public unsafe PeDebugDirectory GetDebugDirectory()
{
ImageDebugDirectory debugDir = new ImageDebugDirectory();
uint dataCount = 0;
try
{
_symWriter.GetDebugInfo(ref debugDir, 0, out dataCount, IntPtr.Zero);
}
catch (Exception ex)
{
throw new PdbWritingException(ex);
}
// See symwrite.cpp - the data don't depend on the content of metadata tables or IL
//
// struct RSDSI
// {
// DWORD dwSig; // "RSDS"
// GUID guidSig;
// DWORD age;
// char szPDB[0]; // zero-terminated UTF8 file name
// };
//
byte[] data = new byte[dataCount];
fixed (byte* pb = data)
{
try
{
_symWriter.GetDebugInfo(ref debugDir, dataCount, out dataCount, (IntPtr)pb);
}
catch (Exception ex)
{
throw new PdbWritingException(ex);
}
}
PeDebugDirectory result = new PeDebugDirectory();
result.AddressOfRawData = (uint)debugDir.AddressOfRawData;
result.Characteristics = (uint)debugDir.Characteristics;
result.Data = data;
result.MajorVersion = (ushort)debugDir.MajorVersion;
result.MinorVersion = (ushort)debugDir.MinorVersion;
result.PointerToRawData = (uint)debugDir.PointerToRawData;
result.SizeOfData = (uint)debugDir.SizeOfData;
result.TimeDateStamp = (uint)debugDir.TimeDateStamp;
result.Type = (uint)debugDir.Type;
return result;
}
public void SetEntryPoint(uint entryMethodToken)
{
try
{
_symWriter.SetUserEntryPoint(entryMethodToken);
}
catch (Exception ex)
{
throw new PdbWritingException(ex);
}
}
private ISymUnmanagedDocumentWriter GetDocumentWriter(DebugSourceDocument document)
{
ISymUnmanagedDocumentWriter writer;
if (!_documentMap.TryGetValue(document, out writer))
{
Guid language = document.Language;
Guid vendor = document.LanguageVendor;
Guid type = document.DocumentType;
try
{
writer = _symWriter.DefineDocument(document.Location, ref language, ref vendor, ref type);
}
catch (Exception ex)
{
throw new PdbWritingException(ex);
}
_documentMap.Add(document, writer);
var checksumAndAlgorithm = document.ChecksumAndAlgorithm;
if (!checksumAndAlgorithm.Item1.IsDefault)
{
try
{
writer.SetCheckSum(checksumAndAlgorithm.Item2, (uint)checksumAndAlgorithm.Item1.Length, checksumAndAlgorithm.Item1.ToArray());
}
catch (Exception ex)
{
throw new PdbWritingException(ex);
}
}
}
return writer;
}
private void OpenMethod(uint methodToken)
{
try
{
_symWriter.OpenMethod(methodToken);
_symWriter.OpenScope(0);
}
catch (Exception ex)
{
throw new PdbWritingException(ex);
}
}
private void CloseMethod()
{
try
{
_symWriter.CloseMethod();
}
catch (Exception ex)
{
throw new PdbWritingException(ex);
}
}
private void OpenScope(uint offset)
{
try
{
_symWriter.OpenScope(offset);
}
catch (Exception ex)
{
throw new PdbWritingException(ex);
}
}
private void CloseScope(uint offset)
{
try
{
_symWriter.CloseScope(offset);
}
catch (Exception ex)
{
throw new PdbWritingException(ex);
}
}
private void UsingNamespace(string fullName, INamedEntity errorEntity)
{
if (_metadataWriter.IsUsingStringTooLong(fullName, errorEntity))
{
return;
}
try
{
_symWriter.UsingNamespace(fullName);
}
catch (Exception ex)
{
throw new PdbWritingException(ex);
}
}
private void CreateSequencePointBuffers(int capacity)
{
_sequencePointOffsets = new uint[capacity];
_sequencePointStartLines = new uint[capacity];
_sequencePointStartColumns = new uint[capacity];
_sequencePointEndLines = new uint[capacity];
_sequencePointEndColumns = new uint[capacity];
}
private void ResizeSequencePointBuffers()
{
int newCapacity = (_sequencePointOffsets.Length + 1) * 2;
Array.Resize(ref _sequencePointOffsets, newCapacity);
Array.Resize(ref _sequencePointStartLines, newCapacity);
Array.Resize(ref _sequencePointStartColumns, newCapacity);
Array.Resize(ref _sequencePointEndLines, newCapacity);
Array.Resize(ref _sequencePointEndColumns, newCapacity);
}
private void EmitSequencePoints(ImmutableArray<SequencePoint> sequencePoints)
{
DebugSourceDocument document = null;
ISymUnmanagedDocumentWriter symDocumentWriter = null;
int i = 0;
foreach (var sequencePoint in sequencePoints)
{
Debug.Assert(sequencePoint.Document != null);
if (document != sequencePoint.Document)
{
if (i > 0)
{
WriteSequencePoints(symDocumentWriter, i);
}
document = sequencePoint.Document;
symDocumentWriter = GetDocumentWriter(document);
i = 0;
}
if (i == _sequencePointOffsets.Length)
{
ResizeSequencePointBuffers();
}
_sequencePointOffsets[i] = (uint)sequencePoint.Offset;
_sequencePointStartLines[i] = (uint)sequencePoint.StartLine;
_sequencePointStartColumns[i] = (uint)sequencePoint.StartColumn;
_sequencePointEndLines[i] = (uint)sequencePoint.EndLine;
_sequencePointEndColumns[i] = (uint)sequencePoint.EndColumn;
i++;
}
if (i > 0)
{
WriteSequencePoints(symDocumentWriter, i);
}
}
private void WriteSequencePoints(ISymUnmanagedDocumentWriter symDocument, int count)
{
try
{
_symWriter.DefineSequencePoints(
symDocument,
(uint)count,
_sequencePointOffsets,
_sequencePointStartLines,
_sequencePointStartColumns,
_sequencePointEndLines,
_sequencePointEndColumns);
}
catch (Exception ex)
{
throw new PdbWritingException(ex);
}
}
private unsafe void DefineCustomMetadata(string name, byte[] metadata)
{
fixed (byte* pb = metadata)
{
try
{
// parent parameter is not used, it must be zero or the current method token passed to OpenMetod.
_symWriter.SetSymAttribute(0, name, (uint)metadata.Length, (IntPtr)pb);
}
catch (Exception ex)
{
throw new PdbWritingException(ex);
}
}
}
private void DefineLocalConstant(string name, object value, PrimitiveTypeCode typeCode, uint constantSignatureToken)
{
if (value == null)
{
// ISymUnmanagedWriter2.DefineConstant2 throws an ArgumentException
// if you pass in null - Dev10 appears to use 0 instead.
// (See EMITTER::VariantFromConstVal)
value = 0;
typeCode = PrimitiveTypeCode.Int32;
}
if (typeCode == PrimitiveTypeCode.String)
{
DefineLocalStringConstant(name, (string)value, constantSignatureToken);
}
else if (value is DateTime)
{
// Marshal.GetNativeVariantForObject would create a variant with type VT_DATE and value equal to the
// number of days since 1899/12/30. However, ConstantValue::VariantFromConstant in the native VB
// compiler actually created a variant with type VT_DATE and value equal to the tick count.
// http://blogs.msdn.com/b/ericlippert/archive/2003/09/16/eric-s-complete-guide-to-vt-date.aspx
_symWriter.DefineConstant2(name, new VariantStructure((DateTime)value), constantSignatureToken);
}
else
{
try
{
_symWriter.DefineConstant2(name, value, constantSignatureToken);
}
catch (Exception ex)
{
throw new PdbWritingException(ex);
}
}
}
private void DefineLocalStringConstant(string name, string value, uint constantSignatureToken)
{
Debug.Assert(value != null);
// ISymUnmanagedWriter2 doesn't handle unicode strings with unmatched unicode surrogates.
// We use the .NET UTF8 encoder to replace unmatched unicode surrogates with unicode replacement character.
if (!MetadataHelpers.IsValidUnicodeString(value))
{
byte[] bytes = Encoding.UTF8.GetBytes(value);
value = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
}
// EDMAURER If defining a string constant and it is too long (length limit is undocumented), this method throws
// an ArgumentException.
// (see EMITTER::EmitDebugLocalConst)
try
{
_symWriter.DefineConstant2(name, value, constantSignatureToken);
}
catch (ArgumentException)
{
// writing the constant value into the PDB failed because the string value was most probably too long.
// We will report a warning for this issue and continue writing the PDB.
// The effect on the debug experience is that the symbol for the constant will not be shown in the local
// window of the debugger. Nor will the user be able to bind to it in expressions in the EE.
//The triage team has deemed this new warning undesirable. The effects are not significant. The warning
//is showing up in the DevDiv build more often than expected. We never warned on it before and nobody cared.
//The proposed warning is not actionable with no source location.
}
catch (Exception ex)
{
throw new PdbWritingException(ex);
}
}
private void DefineLocalVariable(uint index, string name, uint attributes, uint localVariablesSignatureToken)
{
const uint ADDR_IL_OFFSET = 1;
try
{
_symWriter.DefineLocalVariable2(name, attributes, localVariablesSignatureToken, ADDR_IL_OFFSET, index, 0, 0, 0, 0);
}
catch (Exception ex)
{
throw new PdbWritingException(ex);
}
}
private void SetAsyncInfo(
uint thisMethodToken,
uint kickoffMethodToken,
int catchHandlerOffset,
ImmutableArray<int> yieldOffsets,
ImmutableArray<int> resumeOffsets)
{
var asyncMethodPropertyWriter = _symWriter as ISymUnmanagedAsyncMethodPropertiesWriter;
if (asyncMethodPropertyWriter != null)
{
Debug.Assert(yieldOffsets.IsEmpty == resumeOffsets.IsEmpty);
if (!yieldOffsets.IsEmpty)
{
int count = yieldOffsets.Length;
uint[] yields = new uint[count];
uint[] resumes = new uint[count];
uint[] methods = new uint[count];
for (int i = 0; i < count; i++)
{
yields[i] = (uint)yieldOffsets[i];
resumes[i] = (uint)resumeOffsets[i];
methods[i] = (uint)thisMethodToken;
}
try
{
asyncMethodPropertyWriter.DefineAsyncStepInfo((uint)count, yields, resumes, methods);
}
catch (Exception ex)
{
throw new PdbWritingException(ex);
}
}
try
{
if (catchHandlerOffset >= 0)
{
asyncMethodPropertyWriter.DefineCatchHandlerILOffset((uint)catchHandlerOffset);
}
asyncMethodPropertyWriter.DefineKickoffMethod(kickoffMethodToken);
}
catch (Exception ex)
{
throw new PdbWritingException(ex);
}
}
}
public void WriteDefinitionLocations(MultiDictionary<DebugSourceDocument, DefinitionWithLocation> file2definitions)
{
var writer5 = _symWriter as ISymUnmanagedWriter5;
if ((object)writer5 != null)
{
// NOTE: ISymUnmanagedWriter5 reports HRESULT = 0x806D000E in case we open and close
// the map without writing any resords with MapTokenToSourceSpan(...)
bool open = false;
foreach (var kvp in file2definitions)
{
ISymUnmanagedDocumentWriter docWriter = GetDocumentWriter(kvp.Key);
foreach (var definition in kvp.Value)
{
if (!open)
{
try
{
writer5.OpenMapTokensToSourceSpans();
}
catch (Exception ex)
{
throw new PdbWritingException(ex);
}
open = true;
}
uint token = _metadataWriter.GetTokenForDefinition(definition.Definition);