-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Extractor.cs
596 lines (525 loc) · 24.9 KB
/
Extractor.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
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Basic.CompilerLog.Util;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Text;
using Semmle.Util;
using Semmle.Util.Logging;
namespace Semmle.Extraction.CSharp
{
public enum ExitCode
{
Ok, // Everything worked perfectly
Errors, // Trap was generated but there were processing errors
Failed // Trap could not be generated
}
public static class Extractor
{
private class LogProgressMonitor : IProgressMonitor
{
private readonly ILogger logger;
public LogProgressMonitor(ILogger logger)
{
this.logger = logger;
}
public void Analysed(int item, int total, string source, string output, TimeSpan time, AnalysisAction action)
{
if (action != AnalysisAction.UpToDate)
{
var state = action == AnalysisAction.Extracted
? time.ToString()
: action == AnalysisAction.Excluded
? "excluded"
: "up to date";
logger.LogInfo($" {source} ({state})");
}
}
public void Started(int item, int total, string source) { }
public void MissingNamespace(string @namespace) { }
public void MissingSummary(int types, int namespaces) { }
public void MissingType(string type) { }
}
/// <summary>
/// Set the application culture to the invariant culture.
///
/// This is required among others to ensure that the invariant culture is used for value formatting during TRAP
/// file writing.
/// </summary>
public static void SetInvariantCulture()
{
var culture = CultureInfo.InvariantCulture;
CultureInfo.DefaultThreadCurrentCulture = culture;
CultureInfo.DefaultThreadCurrentUICulture = culture;
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
}
public static ILogger MakeLogger(Verbosity verbosity, bool includeConsole)
{
var fileLogger = new FileLogger(verbosity, GetCSharpLogPath(), logThreadId: true);
return includeConsole
? new CombinedLogger(new ConsoleLogger(verbosity, logThreadId: true), fileLogger)
: (ILogger)fileLogger;
}
/// <summary>
/// Command-line driver for the extractor.
/// </summary>
///
/// <remarks>
/// The extractor can be invoked in one of two ways: Either as an "analyser" passed in via the /a
/// option to csc.exe, or as a stand-alone executable. In this case, we need to faithfully
/// drive Roslyn in the way that csc.exe would.
/// </remarks>
///
/// <param name="args">Command line arguments as passed to csc.exe</param>
/// <returns><see cref="ExitCode"/></returns>
public static ExitCode Run(string[] args)
{
var analyzerStopwatch = new Stopwatch();
analyzerStopwatch.Start();
var options = Options.CreateWithEnvironment(args);
using var logger = MakeLogger(options.Verbosity, options.Console);
try
{
var canonicalPathCache = CanonicalPathCache.Create(logger, 1000);
var pathTransformer = new PathTransformer(canonicalPathCache);
if (options.BinaryLogPaths is string[] binlogPaths)
{
logger.LogInfo(" Running binary log analysis.");
return RunBinaryLogAnalysis(analyzerStopwatch, options, binlogPaths, logger, canonicalPathCache, pathTransformer);
}
else
{
logger.LogInfo(" Running tracing analysis.");
return RunTracingAnalysis(analyzerStopwatch, options, logger, canonicalPathCache, pathTransformer);
}
}
catch (Exception ex) // lgtm[cs/catch-of-all-exceptions]
{
logger.LogError($" Unhandled exception: {ex}");
return ExitCode.Errors;
}
}
private static ExitCode RunBinaryLogAnalysis(Stopwatch stopwatch, Options options, string[] binlogPaths, ILogger logger, CanonicalPathCache canonicalPathCache, PathTransformer pathTransformer)
{
var allFailed = true;
foreach (var binlogPath in binlogPaths)
{
var exit = RunBinaryLogAnalysis(stopwatch, options, binlogPath, logger, canonicalPathCache, pathTransformer);
switch (exit)
{
case ExitCode.Ok:
case ExitCode.Errors:
allFailed = false;
break;
case ExitCode.Failed:
break;
}
}
return allFailed ? ExitCode.Failed : ExitCode.Ok;
}
private static ExitCode RunBinaryLogAnalysis(Stopwatch stopwatch, Options options, string binlogPath, ILogger logger, CanonicalPathCache canonicalPathCache, PathTransformer pathTransformer)
{
logger.LogInfo($"Reading compiler calls from binary log {binlogPath}");
try
{
using var fileStream = new FileStream(binlogPath, FileMode.Open, FileAccess.Read, FileShare.Read);
using var reader = BinaryLogReader.Create(fileStream);
// Filter out compiler calls that aren't interesting for examination
static bool filter(CompilerCall compilerCall)
{
return compilerCall.IsCSharp &&
compilerCall.Kind == CompilerCallKind.Regular;
}
var allCompilationData = reader.ReadAllCompilationData(filter);
var allFailed = true;
if (allCompilationData.Count == 0)
{
logger.LogWarning(" No compilations found in binary log.");
return ExitCode.Ok;
}
else
{
logger.LogInfo($" Found {allCompilationData.Count} compilations in binary log");
}
foreach (var compilationData in allCompilationData)
{
if (compilationData.GetCompilationAfterGenerators() is not CSharpCompilation compilation)
{
logger.LogError(" Compilation data is not C#");
continue;
}
var compilerCall = compilationData.CompilerCall;
var diagnosticName = compilerCall.GetDiagnosticName();
logger.LogInfo($" Processing compilation {diagnosticName} at {compilerCall.ProjectDirectory}");
var compilerArgs = compilerCall.GetArguments();
var compilationIdentifierPath = string.Empty;
try
{
compilationIdentifierPath = FileUtils.ConvertPathToSafeRelativePath(
Path.GetRelativePath(Directory.GetCurrentDirectory(), compilerCall.ProjectDirectory));
}
catch (ArgumentException exc)
{
logger.LogWarning($" Failed to get relative path for {compilerCall.ProjectDirectory} from current working directory {Directory.GetCurrentDirectory()}: {exc.Message}");
}
var args = reader.ReadCommandLineArguments(compilerCall);
var generatedSyntaxTrees = compilationData.GetGeneratedSyntaxTrees();
using var analyser = new BinaryLogAnalyser(new LogProgressMonitor(logger), logger, pathTransformer, canonicalPathCache, options.AssemblySensitiveTrap);
var exit = Analyse(stopwatch, analyser, options,
references => [() => compilation.References.ForEach(r => references.Add(r))],
(analyser, syntaxTrees) => [() => syntaxTrees.AddRange(compilation.SyntaxTrees)],
(syntaxTrees, references) => compilation,
(compilation, options) => analyser.Initialize(
compilerCall.ProjectDirectory,
compilerArgs?.ToArray() ?? [],
TracingAnalyser.GetOutputName(compilation, args),
compilation,
generatedSyntaxTrees,
Path.Combine(compilationIdentifierPath, diagnosticName),
options),
() => { });
switch (exit)
{
case ExitCode.Ok:
allFailed = false;
logger.LogInfo($" Compilation {diagnosticName} succeeded");
break;
case ExitCode.Errors:
allFailed = false;
logger.LogWarning($" Compilation {diagnosticName} had errors");
break;
case ExitCode.Failed:
logger.LogWarning($" Compilation {diagnosticName} failed");
break;
}
}
return allFailed ? ExitCode.Failed : ExitCode.Ok;
}
catch (IOException ex)
{
logger.LogError($"Failed to open binary log: {ex.Message}");
return ExitCode.Failed;
}
}
private static ExitCode RunTracingAnalysis(Stopwatch analyzerStopwatch, Options options, ILogger logger, CanonicalPathCache canonicalPathCache, PathTransformer pathTransformer)
{
if (options.ProjectsToLoad.Any())
{
AddSourceFilesFromProjects(options.ProjectsToLoad, options.CompilerArguments, logger);
}
var compilerVersion = new CompilerVersion(options);
if (compilerVersion.SkipExtraction)
{
logger.LogWarning($" Unrecognized compiler '{compilerVersion.SpecifiedCompiler}' because {compilerVersion.SkipReason}");
return ExitCode.Ok;
}
var workingDirectory = Directory.GetCurrentDirectory();
var compilerArgs = options.CompilerArguments.ToArray();
using var analyser = new TracingAnalyser(new LogProgressMonitor(logger), logger, pathTransformer, canonicalPathCache, options.AssemblySensitiveTrap);
var compilerArguments = CSharpCommandLineParser.Default.Parse(
compilerVersion.ArgsWithResponse,
workingDirectory,
compilerVersion.FrameworkPath,
compilerVersion.AdditionalReferenceDirectories
);
if (compilerArguments is null)
{
var sb = new StringBuilder();
sb.Append(" Failed to parse command line: ").AppendList(" ", compilerArgs);
logger.LogError(sb.ToString());
++analyser.CompilationErrors;
return ExitCode.Failed;
}
if (!analyser.BeginInitialize(compilerVersion.ArgsWithResponse))
{
logger.LogInfo("Skipping extraction since files have already been extracted");
return ExitCode.Ok;
}
return AnalyseTracing(workingDirectory, compilerArgs, analyser, compilerArguments, options, analyzerStopwatch);
}
private static void AddSourceFilesFromProjects(IEnumerable<string> projectsToLoad, IList<string> compilerArguments, ILogger logger)
{
logger.LogInfo(" Loading referenced projects.");
var projects = new Queue<string>(projectsToLoad);
var processed = new HashSet<string>();
while (projects.Count > 0)
{
var project = projects.Dequeue();
var fi = new FileInfo(project);
if (processed.Contains(fi.FullName))
{
continue;
}
processed.Add(fi.FullName);
logger.LogInfo($" Processing referenced project: {fi.FullName}");
var csProj = new CsProjFile(fi);
foreach (var cs in csProj.Sources)
{
if (cs.Contains("/obj/"))
{
continue;
}
compilerArguments.Add(cs);
}
foreach (var pr in csProj.ProjectReferences)
{
projects.Enqueue(pr);
}
}
}
/// <summary>
/// Gets the complete list of locations to locate references.
/// </summary>
/// <param name="args">Command line arguments.</param>
/// <returns>List of directories.</returns>
private static IEnumerable<string> FixedReferencePaths(Microsoft.CodeAnalysis.CommandLineArguments args)
{
// See https://msdn.microsoft.com/en-us/library/s5bac5fx.aspx
// on how csc resolves references. Basically,
// 1) Current working directory. This is the directory from which the compiler is invoked.
// 2) The common language runtime system directory.
// 3) Directories specified by / lib.
// 4) Directories specified by the LIB environment variable.
if (args.BaseDirectory is not null)
{
yield return args.BaseDirectory;
}
foreach (var r in args.ReferencePaths)
yield return r;
var lib = System.Environment.GetEnvironmentVariable("LIB");
if (lib is not null)
yield return lib;
}
private static MetadataReference MakeReference(CommandLineReference reference, string path)
{
return MetadataReference.CreateFromFile(path).WithProperties(reference.Properties);
}
/// <summary>
/// Construct tasks for resolving references (possibly in parallel).
///
/// The resolved references will be added (thread-safely) to the supplied
/// list <paramref name="ret"/>.
/// </summary>
private static IEnumerable<Action> ResolveReferences(Microsoft.CodeAnalysis.CommandLineArguments args, Analyser analyser, BlockingCollection<MetadataReference> ret)
{
var referencePaths = new Lazy<string[]>(() => FixedReferencePaths(args).ToArray());
return args.MetadataReferences.Select<CommandLineReference, Action>(clref => () =>
{
if (Path.IsPathRooted(clref.Reference))
{
if (File.Exists(clref.Reference))
{
var reference = MakeReference(clref, analyser.PathCache.GetCanonicalPath(clref.Reference));
ret.Add(reference);
}
else
{
lock (analyser)
{
analyser.Logger.LogError($" Reference '{clref.Reference}' does not exist");
++analyser.CompilationErrors;
}
}
}
else
{
var composed = referencePaths.Value
.Select(path => Path.Combine(path, clref.Reference))
.Where(path => File.Exists(path))
.Select(path => analyser.PathCache.GetCanonicalPath(path))
.FirstOrDefault();
if (composed is not null)
{
var reference = MakeReference(clref, composed);
ret.Add(reference);
}
else
{
lock (analyser)
{
analyser.Logger.LogError($" Unable to resolve reference '{clref.Reference}'");
++analyser.CompilationErrors;
}
}
}
});
}
/// <summary>
/// Construct tasks for reading source code files (possibly in parallel).
///
/// The constructed syntax trees will be added (thread-safely) to the supplied
/// list <paramref name="ret"/>.
/// </summary>
public static IEnumerable<Action> ReadSyntaxTrees(IEnumerable<string> sources, Analyser analyser, CSharpParseOptions? parseOptions, Encoding? encoding, IList<SyntaxTree> ret)
{
return sources.Select<string, Action>(path => () =>
{
try
{
using var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
analyser.Logger.LogTrace($"Parsing source file: '{path}'");
var tree = CSharpSyntaxTree.ParseText(SourceText.From(file, encoding), parseOptions, path);
analyser.Logger.LogTrace($"Source file parsed: '{path}'");
lock (ret)
{
ret.Add(tree);
}
}
catch (IOException ex)
{
lock (analyser)
{
analyser.Logger.LogError($" Unable to open source file {path}: {ex.Message}");
++analyser.CompilationErrors;
}
}
});
}
public static ExitCode Analyse(Stopwatch stopwatch, Analyser analyser, CommonOptions options,
Func<BlockingCollection<MetadataReference>, IEnumerable<Action>> getResolvedReferenceTasks,
Func<Analyser, List<SyntaxTree>, IEnumerable<Action>> getSyntaxTreeTasks,
Func<IEnumerable<SyntaxTree>, IEnumerable<MetadataReference>, CSharpCompilation> getCompilation,
Action<CSharpCompilation, CommonOptions> initializeAnalyser,
Action postProcess)
{
using var references = new BlockingCollection<MetadataReference>();
var referenceTasks = getResolvedReferenceTasks(references);
var syntaxTrees = new List<SyntaxTree>();
var syntaxTreeTasks = getSyntaxTreeTasks(analyser, syntaxTrees);
var sw = new Stopwatch();
sw.Start();
Parallel.Invoke(
new ParallelOptions { MaxDegreeOfParallelism = options.Threads },
referenceTasks.Interleave(syntaxTreeTasks).ToArray());
if (syntaxTrees.Count == 0)
{
analyser.Logger.LogError(" No source files");
++analyser.CompilationErrors;
if (analyser is TracingAnalyser)
{
return ExitCode.Failed;
}
}
syntaxTrees.Sort((a, b) => string.Compare(a.FilePath, b.FilePath, StringComparison.Ordinal));
var compilation = getCompilation(syntaxTrees, references);
initializeAnalyser(compilation, options);
analyser.AnalyseCompilation();
analyser.AnalyseReferences();
foreach (var tree in compilation.SyntaxTrees)
{
analyser.AnalyseTree(tree);
}
sw.Stop();
analyser.Logger.LogInfo($" Models constructed in {sw.Elapsed}");
var elapsed = sw.Elapsed;
var currentProcess = Process.GetCurrentProcess();
var cpuTime1 = currentProcess.TotalProcessorTime;
var userTime1 = currentProcess.UserProcessorTime;
sw.Restart();
analyser.PerformExtraction(options.Threads);
analyser.ExtractAggregatedMessages();
sw.Stop();
var cpuTime2 = currentProcess.TotalProcessorTime;
var userTime2 = currentProcess.UserProcessorTime;
var performance = new Entities.PerformanceMetrics()
{
Frontend = new Entities.Timings() { Elapsed = elapsed, Cpu = cpuTime1, User = userTime1 },
Extractor = new Entities.Timings() { Elapsed = sw.Elapsed, Cpu = cpuTime2 - cpuTime1, User = userTime2 - userTime1 },
Total = new Entities.Timings() { Elapsed = stopwatch.Elapsed, Cpu = cpuTime2, User = userTime2 },
PeakWorkingSet = currentProcess.PeakWorkingSet64
};
analyser.LogPerformance(performance);
analyser.Logger.LogInfo($" Extraction took {sw.Elapsed}");
postProcess();
return analyser.TotalErrors == 0 ? ExitCode.Ok : ExitCode.Errors;
}
private static ExitCode AnalyseTracing(
string cwd,
string[] args,
TracingAnalyser analyser,
CSharpCommandLineArguments compilerArguments,
Options options,
Stopwatch stopwatch)
{
return Analyse(stopwatch, analyser, options,
references => ResolveReferences(compilerArguments, analyser, references),
(analyser, syntaxTrees) =>
{
var paths = compilerArguments.SourceFiles
.Select(src => src.Path)
.ToList();
if (compilerArguments.GeneratedFilesOutputDirectory is not null)
{
paths.AddRange(Directory.GetFiles(compilerArguments.GeneratedFilesOutputDirectory, "*.cs", new EnumerationOptions { RecurseSubdirectories = true, MatchCasing = MatchCasing.CaseInsensitive }));
}
return ReadSyntaxTrees(
paths.Select(analyser.PathCache.GetCanonicalPath).ToHashSet(),
analyser,
compilerArguments.ParseOptions,
compilerArguments.Encoding,
syntaxTrees);
},
(syntaxTrees, references) =>
{
// csc.exe (CSharpCompiler.cs) also provides CompilationOptions
// .WithMetadataReferenceResolver(),
// .WithXmlReferenceResolver() and
// .WithSourceReferenceResolver().
// These would be needed if we hadn't explicitly provided the source/references
// already.
return CSharpCompilation.Create(
compilerArguments.CompilationName,
syntaxTrees,
references,
compilerArguments.CompilationOptions
.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)
.WithStrongNameProvider(new DesktopStrongNameProvider(compilerArguments.KeyFileSearchPaths))
.WithMetadataImportOptions(MetadataImportOptions.All)
);
},
(compilation, options) => analyser.EndInitialize(compilerArguments, options, compilation, cwd, args),
() => { });
}
/// <summary>
/// Gets the path to the `csharp.log` file written to by the C# extractor.
/// </summary>
public static string GetCSharpLogPath() =>
Path.Combine(GetCSharpLogDirectory(), "csharp.log");
/// <summary>
/// Gets the path to a `csharp.{hash}.txt` file written to by the C# extractor.
/// </summary>
public static string GetCSharpArgsLogPath(string hash) =>
Path.Combine(GetCSharpLogDirectory(), $"csharp.{hash}.txt");
/// <summary>
/// Gets a list of all `csharp.{hash}.txt` files currently written to the log directory.
/// </summary>
public static IEnumerable<string> GetCSharpArgsLogs()
{
try
{
return Directory.EnumerateFiles(GetCSharpLogDirectory(), "csharp.*.txt");
}
catch (DirectoryNotFoundException)
{
// If the directory does not exist, there are no log files
return Enumerable.Empty<string>();
}
}
private static string GetCSharpLogDirectory()
{
var codeQlLogDir = Environment.GetEnvironmentVariable("CODEQL_EXTRACTOR_CSHARP_LOG_DIR");
if (!string.IsNullOrEmpty(codeQlLogDir))
return codeQlLogDir;
return Directory.GetCurrentDirectory();
}
}
}