C#: Try resolve relative paths in line mappings

This commit is contained in:
Tamas Vajk
2024-02-07 15:51:11 +01:00
parent 54c9135936
commit 1c7e6e769b
33 changed files with 120 additions and 94 deletions

View File

@@ -1,5 +1,7 @@
using System;
using System.IO;
using Microsoft.CodeAnalysis;
using Semmle.Util.Logging;
namespace Semmle.Extraction.CSharp.Entities
{
@@ -25,7 +27,8 @@ namespace Semmle.Extraction.CSharp.Entities
var mapped = Symbol.GetMappedLineSpan();
if (mapped.HasMappedPath && mapped.IsValid)
{
var mappedLoc = Create(Context, Location.Create(mapped.Path, default, mapped.Span));
var path = TryAdjustRelativeMappedFilePath(mapped.Path, Position.Path, Context.Extractor.Logger);
var mappedLoc = Create(Context, Location.Create(path, default, mapped.Span));
trapFile.locations_mapped(this, mappedLoc);
}
@@ -61,5 +64,25 @@ namespace Semmle.Extraction.CSharp.Entities
public override NonGeneratedSourceLocation Create(Context cx, Location init) => new NonGeneratedSourceLocation(cx, init);
}
public static string TryAdjustRelativeMappedFilePath(string mappedToPath, string mappedFromPath, ILogger logger)
{
if (!Path.IsPathRooted(mappedToPath))
{
try
{
var fullPath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(mappedFromPath)!, mappedToPath));
logger.LogDebug($"Found relative path in line mapping: '{mappedToPath}', interpreting it as '{fullPath}'");
mappedToPath = fullPath;
}
catch (Exception e)
{
logger.LogDebug($"Failed to compute absolute path for relative path in line mapping: '{mappedToPath}': {e}");
}
}
return mappedToPath;
}
}
}

View File

@@ -25,9 +25,11 @@ namespace Semmle.Extraction.CSharp.Entities
{
trapFile.directive_lines(this, kind);
if (!string.IsNullOrWhiteSpace(Symbol.File.ValueText))
var path = Symbol.File.ValueText;
if (!string.IsNullOrWhiteSpace(path))
{
var file = File.Create(Context, Symbol.File.ValueText);
path = NonGeneratedSourceLocation.TryAdjustRelativeMappedFilePath(path, Symbol.SyntaxTree.FilePath, Context.Extractor.Logger);
var file = File.Create(Context, path);
trapFile.directive_line_file(this, file);
}
}

View File

@@ -12,7 +12,8 @@ namespace Semmle.Extraction.CSharp.Entities
protected override void PopulatePreprocessor(TextWriter trapFile)
{
var file = File.Create(Context, Symbol.File.ValueText);
var path = NonGeneratedSourceLocation.TryAdjustRelativeMappedFilePath(Symbol.File.ValueText, Symbol.SyntaxTree.FilePath, Context.Extractor.Logger);
var file = File.Create(Context, path);
trapFile.pragma_checksums(this, file, Symbol.Guid.ToString(), Symbol.Bytes.ToString());
}