-
Notifications
You must be signed in to change notification settings - Fork 115
/
DebugInformationManager.cs
488 lines (439 loc) · 18.7 KB
/
DebugInformationManager.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
// -----------------------------------------------------------------------------
// ILGPU
// Copyright (c) 2016-2019 Marcel Koester
// www.ilgpu.net
//
// File: DebugInformationManager.cs
//
// This file is part of ILGPU and is distributed under the University of
// Illinois Open Source License. See LICENSE.txt for details
// -----------------------------------------------------------------------------
using ILGPU.Util;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
namespace ILGPU.Frontend.DebugInformation
{
/// <summary>
/// Represents a debug-information manager.
/// </summary>
public sealed class DebugInformationManager : DisposeBase, ICache
{
#region Constants
/// <summary>
/// The PDB file extension (.pdb).
/// </summary>
public const string PDBFileExtensions = ".pdb";
/// <summary>
/// The PDB file-search extension (*.pdb).
/// </summary>
public const string PDBFileSearchPattern = "*" + PDBFileExtensions;
#endregion
#region Nested Types
/// <summary>
/// Represents a custom PDB loader.
/// </summary>
private interface ILoader
{
/// <summary>
/// Executes the actual loader logic.
/// </summary>
/// <param name="assembly">The current assembly.</param>
/// <param name="assemblyDebugInformation">The loaded debug-information instance.</param>
/// <returns>True, if the requested debug information could be loaded.</returns>
bool Load(Assembly assembly, out AssemblyDebugInformation assemblyDebugInformation);
}
/// <summary>
/// Represents a file loader for PDB files.
/// </summary>
readonly struct FileLoader : ILoader
{
/// <summary>
/// Constructs a new file loader.
/// </summary>
/// <param name="parent">The parent manager.</param>
/// <param name="pdbFileName">The file name to load.</param>
public FileLoader(DebugInformationManager parent, string pdbFileName)
{
Parent = parent;
PDBFileName = pdbFileName;
}
/// <summary>
/// Returns the parent debug-information manager.
/// </summary>
public DebugInformationManager Parent { get; }
/// <summary>
/// Returns the file name to load.
/// </summary>
public string PDBFileName { get; }
/// <summary cref="ILoader.Load(Assembly, out AssemblyDebugInformation)"/>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Loading exceptions will be published on the debug output")]
public bool Load(Assembly assembly, out AssemblyDebugInformation assemblyDebugInformation)
{
if (Parent.pdbFiles.TryGetValue(PDBFileName, out string fileName))
{
try
{
using (var pdbFileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
assemblyDebugInformation = new AssemblyDebugInformation(assembly, pdbFileStream);
}
}
catch (Exception ex)
{
Debug.WriteLine("Error loading PDB file: " + PDBFileName);
Debug.WriteLine(ex.ToString());
assemblyDebugInformation = new AssemblyDebugInformation(assembly);
}
}
else
assemblyDebugInformation = new AssemblyDebugInformation(assembly);
Parent.assemblies.Add(assembly, assemblyDebugInformation);
return assemblyDebugInformation.IsValid;
}
}
/// <summary>
/// Represents a automatic file loader for PDB files.
/// </summary>
readonly struct AutoFileLoader : ILoader
{
/// <summary>
/// Constructs a new automatic file loader.
/// </summary>
/// <param name="parent">The parent manager.</param>
public AutoFileLoader(DebugInformationManager parent)
{
Parent = parent;
}
/// <summary>
/// Returns the parent debug-information manager.
/// </summary>
public DebugInformationManager Parent { get; }
/// <summary cref="ILoader.Load(Assembly, out AssemblyDebugInformation)"/>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Loading exceptions will be published on the debug output")]
public bool Load(Assembly assembly, out AssemblyDebugInformation assemblyDebugInformation)
{
assemblyDebugInformation = null;
if (assembly.IsDynamic)
return false;
var debugDir = Path.GetDirectoryName(assembly.Location);
if (!Parent.lookupDirectories.Contains(debugDir))
Parent.RegisterLookupDirectory(debugDir);
var pdbFileName = assembly.GetName().Name;
var loader = new FileLoader(Parent, pdbFileName);
return loader.Load(assembly, out assemblyDebugInformation);
}
}
/// <summary>
/// Represents a stream loader for PDB files.
/// </summary>
readonly struct StreamLoader : ILoader
{
/// <summary>
/// Constructs a new stream loader.
/// </summary>
/// <param name="parent">The parent manager.</param>
/// <param name="pdbStream">The stream to load from.</param>
public StreamLoader(DebugInformationManager parent, Stream pdbStream)
{
Parent = parent;
PDBStream = pdbStream;
}
/// <summary>
/// Returns the parent debug-information manager.
/// </summary>
public DebugInformationManager Parent { get; }
/// <summary>
/// Returns the stream to load from.
/// </summary>
public Stream PDBStream { get; }
/// <summary cref="ILoader.Load(Assembly, out AssemblyDebugInformation)"/>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Loading exceptions will be published on the debug output")]
public bool Load(Assembly assembly, out AssemblyDebugInformation assemblyDebugInformation)
{
try
{
assemblyDebugInformation = new AssemblyDebugInformation(assembly, PDBStream);
if (!assemblyDebugInformation.IsValid)
return false;
Parent.assemblies.Add(assembly, assemblyDebugInformation);
return true;
}
catch (Exception ex)
{
assemblyDebugInformation = null;
Debug.WriteLine($"Error reading from PDB stream for assembly '{assembly}'");
Debug.WriteLine(ex.ToString());
return false;
}
}
}
#endregion
#region Instance
private readonly ReaderWriterLockSlim cacheLock = new ReaderWriterLockSlim(
LockRecursionPolicy.SupportsRecursion);
private readonly Dictionary<string, string> pdbFiles = new Dictionary<string, string>();
private readonly HashSet<string> lookupDirectories = new HashSet<string>();
private readonly Dictionary<Assembly, AssemblyDebugInformation> assemblies =
new Dictionary<Assembly, AssemblyDebugInformation>();
/// <summary>
/// Constructs a new debug-information manager.
/// </summary>
public DebugInformationManager()
{
// Register the current application path
var currentDirectory = Directory.GetCurrentDirectory();
if (Directory.Exists(currentDirectory))
RegisterLookupDirectory(currentDirectory);
}
#endregion
#region Methods
/// <summary>
/// Tries to load symbols for the given assemlby.
/// </summary>
/// <param name="assembly">The assembly.</param>
/// <param name="assemblyDebugInformation">The loaded debug information (or null).</param>
/// <returns>True, iff the debug information could be loaded.</returns>
public bool TryLoadSymbols(
Assembly assembly,
out AssemblyDebugInformation assemblyDebugInformation) =>
TryLoadSymbolsInternal(
assembly,
new AutoFileLoader(this),
out assemblyDebugInformation);
/// <summary>
/// Tries to load symbols for the given assembly based on the given debug-information file.
/// </summary>
/// <param name="assembly">The assembly.</param>
/// <param name="pdbFileName">The name of the debug-information file.</param>
/// <param name="assemblyDebugInformation">The loaded debug information (or null).</param>
/// <returns>True, iff the debug information could be loaded.</returns>
public bool TryLoadSymbols(
Assembly assembly,
string pdbFileName,
out AssemblyDebugInformation assemblyDebugInformation)
{
if (pdbFileName == null)
throw new ArgumentNullException(nameof(pdbFileName));
if (!File.Exists(pdbFileName))
throw new FileNotFoundException();
return TryLoadSymbolsInternal(
assembly,
new FileLoader(this, pdbFileName),
out assemblyDebugInformation);
}
/// <summary>
/// Tries to load symbols for the given assembly based on the given PDB stream.
/// </summary>
/// <param name="assembly">The assembly.</param>
/// <param name="pdbStream">The source PDB stream.</param>
/// <param name="assemblyDebugInformation">The loaded debug information (or null).</param>
/// <returns>True, iff the debug information could be loaded.</returns>
public bool TryLoadSymbols(
Assembly assembly,
Stream pdbStream,
out AssemblyDebugInformation assemblyDebugInformation)
{
if (pdbStream == null)
throw new ArgumentNullException(nameof(pdbStream));
return TryLoadSymbolsInternal(
assembly,
new StreamLoader(this, pdbStream),
out assemblyDebugInformation);
}
/// <summary>
/// Tries to load symbols for the given assembly based on the given debug-information file.
/// </summary>
/// <param name="assembly">The assembly.</param>
/// <param name="loader">The internal loader.</param>
/// <param name="assemblyDebugInformation">The loaded debug information (or null).</param>
/// <returns>True, iff the debug information could be loaded.</returns>
private bool TryLoadSymbolsInternal<TLoader>(
Assembly assembly,
in TLoader loader,
out AssemblyDebugInformation assemblyDebugInformation)
where TLoader : struct, ILoader
{
if (assembly == null)
throw new ArgumentNullException(nameof(assembly));
cacheLock.EnterUpgradeableReadLock();
try
{
if (assemblies.TryGetValue(assembly, out assemblyDebugInformation))
return true;
cacheLock.EnterWriteLock();
try
{
return loader.Load(assembly, out assemblyDebugInformation);
}
finally
{
cacheLock.ExitWriteLock();
}
}
finally
{
cacheLock.ExitUpgradeableReadLock();
}
}
/// <summary>
/// Tries to find a debug-information file with the name <paramref name="pdbFileName"/>.
/// </summary>
/// <param name="pdbFileName">The name of the debug-information file.</param>
/// <param name="fileName">The resolved filename (or null).</param>
/// <returns>True, iff the given debug-information file could be found.</returns>
public bool TryFindPbdFile(string pdbFileName, out string fileName)
{
cacheLock.EnterReadLock();
try
{
return pdbFiles.TryGetValue(pdbFileName, out fileName);
}
finally
{
cacheLock.ExitReadLock();
}
}
/// <summary>
/// Registers the given directory as a source directory for debug-information files.
/// </summary>
/// <param name="directory">The directory to register.</param>
public void RegisterLookupDirectory(string directory)
{
if (directory == null)
throw new ArgumentNullException(nameof(directory));
if (!Directory.Exists(directory))
throw new DirectoryNotFoundException();
cacheLock.EnterUpgradeableReadLock();
try
{
if (lookupDirectories.Contains(directory))
return;
cacheLock.EnterWriteLock();
try
{
var files = Directory.GetFiles(directory, PDBFileSearchPattern);
foreach (var file in files)
pdbFiles[Path.GetFileNameWithoutExtension(file)] = file;
lookupDirectories.Add(directory);
}
finally
{
cacheLock.ExitWriteLock();
}
}
finally
{
cacheLock.ExitUpgradeableReadLock();
}
}
/// <summary>
/// Tries to load debug information for the given method.
/// </summary>
/// <param name="methodBase">The method.</param>
/// <param name="methodDebugInformation">Loaded debug information (or null).</param>
/// <returns>True, iff debug information could be loaded.</returns>
public bool TryLoadDebugInformation(
MethodBase methodBase,
out MethodDebugInformation methodDebugInformation)
{
Debug.Assert(methodBase != null, "Invalid method");
methodDebugInformation = null;
if (!TryLoadSymbols(
methodBase.Module.Assembly,
out AssemblyDebugInformation assemblyDebugInformation))
return false;
return assemblyDebugInformation.TryLoadDebugInformation(
methodBase,
out methodDebugInformation);
}
/// <summary>
/// Loads the sequence points of the given method.
/// </summary>
/// <param name="methodBase">The method base.</param>
/// <returns>A sequence-point enumerator that targets the given method.</returns>
/// <remarks>
/// If no debug information could be loaded for the given method, an empty
/// <see cref="SequencePointEnumerator"/> will be returned.
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public SequencePointEnumerator LoadSequencePoints(MethodBase methodBase)
{
if (TryLoadDebugInformation(methodBase, out MethodDebugInformation methodDebugInformation))
return methodDebugInformation.CreateSequencePointEnumerator();
return SequencePointEnumerator.Empty;
}
/// <summary>
/// Loads the scopes of the given method.
/// </summary>
/// <param name="methodBase">The method base.</param>
/// <returns>A scope-enumerator that targets the given method.</returns>
/// <remarks>
/// If no debug information could be loaded for the given method, an empty
/// <see cref="MethodScopeEnumerator"/> will be returned.
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public MethodScopeEnumerator LoadScopes(MethodBase methodBase)
{
if (TryLoadDebugInformation(methodBase, out MethodDebugInformation methodDebugInformation))
return methodDebugInformation.CreateScopeEnumerator();
return MethodScopeEnumerator.Empty;
}
/// <summary>
/// Clears cached debug information.
/// </summary>
/// <param name="mode">The clear mode.</param>
public void ClearCache(ClearCacheMode mode)
{
cacheLock.EnterWriteLock();
try
{
if (mode == ClearCacheMode.Everything)
{
foreach (var debugInformation in assemblies.Values)
debugInformation.Dispose();
assemblies.Clear();
}
else
{
// Do not dispose system assemblies
var assembliesToRemove = new List<Assembly>(assemblies.Count);
foreach (var assembly in assemblies.Keys)
{
if (assembly.FullName.StartsWith(Context.AssemblyName, StringComparison.OrdinalIgnoreCase))
continue;
assembliesToRemove.Add(assembly);
}
foreach (var assemblyToRemove in assembliesToRemove)
{
assemblies[assemblyToRemove].Dispose();
assemblies.Remove(assemblyToRemove);
}
}
}
finally
{
cacheLock.ExitWriteLock();
}
}
#endregion
#region IDisposable
/// <summary cref="DisposeBase.Dispose(bool)"/>
[SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "cacheLock",
Justification = "Dispose method will be invoked by a helper method")]
protected override void Dispose(bool disposing)
{
ClearCache(ClearCacheMode.Everything);
cacheLock.Dispose();
}
#endregion
}
}