| | 1 | | // Copyright DotNet API Diff Project Contributors - SPDX Identifier: MIT |
| | 2 | | using System.Reflection; |
| | 3 | | using System.Security; |
| | 4 | | using DotNetApiDiff.Interfaces; |
| | 5 | | using Microsoft.Extensions.Logging; |
| | 6 | |
|
| | 7 | | namespace DotNetApiDiff.AssemblyLoading; |
| | 8 | |
|
| | 9 | | /// <summary> |
| | 10 | | /// Implementation of IAssemblyLoader that loads assemblies in isolated contexts |
| | 11 | | /// </summary> |
| | 12 | | public class AssemblyLoader : IAssemblyLoader, IDisposable |
| | 13 | | { |
| | 14 | | private readonly ILogger<AssemblyLoader> logger; |
| 32 | 15 | | private readonly Dictionary<string, Assembly> loadedAssemblies = new Dictionary<string, Assembly>(); |
| 32 | 16 | | private readonly Dictionary<string, IsolatedAssemblyLoadContext> loadContexts = new Dictionary<string, IsolatedAssem |
| | 17 | |
|
| | 18 | | /// <summary> |
| | 19 | | /// Creates a new assembly loader with the specified logger |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="logger">Logger for diagnostic information</param> |
| 32 | 22 | | public AssemblyLoader(ILogger<AssemblyLoader> logger) |
| 32 | 23 | | { |
| 32 | 24 | | this.logger = logger ?? throw new ArgumentNullException(nameof(logger)); |
| 32 | 25 | | } |
| | 26 | |
|
| | 27 | | /// <summary> |
| | 28 | | /// Loads an assembly from the specified file path |
| | 29 | | /// </summary> |
| | 30 | | /// <param name="assemblyPath">Path to the assembly file</param> |
| | 31 | | /// <returns>Loaded assembly</returns> |
| | 32 | | /// <exception cref="ArgumentException">Thrown when assembly path is null or empty</exception> |
| | 33 | | /// <exception cref="FileNotFoundException">Thrown when assembly file is not found</exception> |
| | 34 | | /// <exception cref="BadImageFormatException">Thrown when assembly file is invalid</exception> |
| | 35 | | /// <exception cref="SecurityException">Thrown when there are insufficient permissions to load the assembly</excepti |
| | 36 | | /// <exception cref="PathTooLongException">Thrown when the assembly path is too long</exception> |
| | 37 | | /// <exception cref="ReflectionTypeLoadException">Thrown when types in the assembly cannot be loaded</exception> |
| | 38 | | public Assembly LoadAssembly(string assemblyPath) |
| 17 | 39 | | { |
| 17 | 40 | | if (string.IsNullOrWhiteSpace(assemblyPath)) |
| 5 | 41 | | { |
| 5 | 42 | | this.logger.LogError("Assembly path cannot be null or empty"); |
| 5 | 43 | | throw new ArgumentException("Assembly path cannot be null or empty", nameof(assemblyPath)); |
| | 44 | | } |
| | 45 | |
|
| | 46 | | // Normalize the path to ensure consistent dictionary keys |
| | 47 | | try |
| 12 | 48 | | { |
| 12 | 49 | | assemblyPath = Path.GetFullPath(assemblyPath); |
| 12 | 50 | | } |
| 0 | 51 | | catch (PathTooLongException ex) |
| 0 | 52 | | { |
| 0 | 53 | | this.logger.LogError(ex, "Path too long for assembly: {Path}", assemblyPath); |
| 0 | 54 | | throw; |
| | 55 | | } |
| 0 | 56 | | catch (SecurityException ex) |
| 0 | 57 | | { |
| 0 | 58 | | this.logger.LogError(ex, "Security exception accessing path: {Path}", assemblyPath); |
| 0 | 59 | | throw; |
| | 60 | | } |
| 0 | 61 | | catch (Exception ex) |
| 0 | 62 | | { |
| 0 | 63 | | this.logger.LogError(ex, "Error normalizing assembly path: {Path}", assemblyPath); |
| 0 | 64 | | throw new ArgumentException($"Invalid assembly path: {assemblyPath}", nameof(assemblyPath), ex); |
| | 65 | | } |
| | 66 | |
|
| | 67 | | // Check if we've already loaded this assembly |
| 12 | 68 | | if (this.loadedAssemblies.TryGetValue(assemblyPath, out var loadedAssembly)) |
| 1 | 69 | | { |
| 1 | 70 | | this.logger.LogDebug("Returning previously loaded assembly from {Path}", assemblyPath); |
| 1 | 71 | | return loadedAssembly; |
| | 72 | | } |
| | 73 | |
|
| 11 | 74 | | using (this.logger.BeginScope("Loading assembly {Path}", assemblyPath)) |
| 11 | 75 | | { |
| 11 | 76 | | this.logger.LogInformation("Loading assembly from {Path}", assemblyPath); |
| | 77 | |
|
| | 78 | | try |
| 11 | 79 | | { |
| | 80 | | // Verify the file exists |
| 11 | 81 | | if (!File.Exists(assemblyPath)) |
| 2 | 82 | | { |
| 2 | 83 | | this.logger.LogError("Assembly file not found: {Path}", assemblyPath); |
| 2 | 84 | | throw new FileNotFoundException($"Assembly file not found: {assemblyPath}", assemblyPath); |
| | 85 | | } |
| | 86 | |
|
| | 87 | | // Verify the file is accessible |
| | 88 | | try |
| 9 | 89 | | { |
| 9 | 90 | | using (var fileStream = File.OpenRead(assemblyPath)) |
| 9 | 91 | | { |
| | 92 | | // Just testing if we can open the file |
| 9 | 93 | | } |
| 9 | 94 | | } |
| 0 | 95 | | catch (IOException ex) |
| 0 | 96 | | { |
| 0 | 97 | | this.logger.LogError(ex, "Cannot access assembly file: {Path}", assemblyPath); |
| 0 | 98 | | throw new IOException($"Cannot access assembly file: {assemblyPath}", ex); |
| | 99 | | } |
| | 100 | |
|
| | 101 | | // Create a new isolated load context for this assembly |
| 9 | 102 | | var loadContext = new IsolatedAssemblyLoadContext(assemblyPath, this.logger); |
| | 103 | |
|
| | 104 | | // Add the directory of the assembly as a search path |
| 9 | 105 | | var assemblyDirectory = Path.GetDirectoryName(assemblyPath); |
| 9 | 106 | | if (!string.IsNullOrEmpty(assemblyDirectory)) |
| 9 | 107 | | { |
| 9 | 108 | | loadContext.AddSearchPath(assemblyDirectory); |
| | 109 | |
|
| | 110 | | // Also add any subdirectories that might contain dependencies |
| | 111 | | try |
| 9 | 112 | | { |
| 311 | 113 | | foreach (var subDir in Directory.GetDirectories(assemblyDirectory, "*", SearchOption.TopDirector |
| 142 | 114 | | { |
| 142 | 115 | | loadContext.AddSearchPath(subDir); |
| 142 | 116 | | } |
| 9 | 117 | | } |
| 0 | 118 | | catch (Exception ex) |
| 0 | 119 | | { |
| | 120 | | // Log but don't fail if we can't access subdirectories |
| 0 | 121 | | this.logger.LogWarning(ex, "Could not access subdirectories of {Directory}", assemblyDirectory); |
| 0 | 122 | | } |
| 9 | 123 | | } |
| | 124 | |
|
| | 125 | | // Load the assembly in the isolated context |
| | 126 | | Assembly assembly; |
| | 127 | | try |
| 9 | 128 | | { |
| 9 | 129 | | assembly = loadContext.LoadFromAssemblyPath(assemblyPath); |
| 7 | 130 | | } |
| 2 | 131 | | catch (BadImageFormatException ex) |
| 2 | 132 | | { |
| 2 | 133 | | this.logger.LogError(ex, "Invalid assembly format: {Path}", assemblyPath); |
| | 134 | |
|
| | 135 | | // Try to determine if this is a native DLL or other non-.NET assembly |
| 2 | 136 | | if (IsProbablyNativeDll(assemblyPath)) |
| 0 | 137 | | { |
| 0 | 138 | | this.logger.LogError("The file appears to be a native DLL, not a .NET assembly: {Path}", assembl |
| 0 | 139 | | throw new BadImageFormatException($"The file appears to be a native DLL, not a .NET assembly: {a |
| | 140 | | } |
| | 141 | |
|
| 2 | 142 | | throw; |
| | 143 | | } |
| 0 | 144 | | catch (FileLoadException ex) |
| 0 | 145 | | { |
| 0 | 146 | | this.logger.LogError(ex, "Failed to load assembly file: {Path}, FileName: {FileName}", assemblyPath, |
| 0 | 147 | | throw; |
| | 148 | | } |
| | 149 | |
|
| | 150 | | // Store the assembly and load context for later use |
| 7 | 151 | | this.loadedAssemblies[assemblyPath] = assembly; |
| 7 | 152 | | this.loadContexts[assemblyPath] = loadContext; |
| | 153 | |
|
| | 154 | | // Log assembly details |
| 7 | 155 | | var assemblyName = assembly.GetName(); |
| 7 | 156 | | this.logger.LogInformation( |
| 7 | 157 | | "Successfully loaded assembly: {AssemblyName} v{Version} from {Path}", |
| 7 | 158 | | assemblyName.Name, |
| 7 | 159 | | assemblyName.Version, |
| 7 | 160 | | assemblyPath); |
| | 161 | |
|
| | 162 | | // Log referenced assemblies at debug level |
| 7 | 163 | | if (this.logger.IsEnabled(LogLevel.Debug)) |
| 0 | 164 | | { |
| | 165 | | try |
| 0 | 166 | | { |
| 0 | 167 | | var referencedAssemblies = assembly.GetReferencedAssemblies(); |
| 0 | 168 | | this.logger.LogDebug( |
| 0 | 169 | | "Assembly {AssemblyName} references {Count} assemblies", |
| 0 | 170 | | assemblyName.Name, |
| 0 | 171 | | referencedAssemblies.Length); |
| | 172 | |
|
| 0 | 173 | | foreach (var reference in referencedAssemblies) |
| 0 | 174 | | { |
| 0 | 175 | | this.logger.LogDebug( |
| 0 | 176 | | "Referenced assembly: {Name} v{Version}", |
| 0 | 177 | | reference.Name, |
| 0 | 178 | | reference.Version); |
| 0 | 179 | | } |
| 0 | 180 | | } |
| 0 | 181 | | catch (Exception ex) |
| 0 | 182 | | { |
| 0 | 183 | | this.logger.LogDebug(ex, "Error getting referenced assemblies for {AssemblyName}", assemblyName. |
| 0 | 184 | | } |
| 0 | 185 | | } |
| | 186 | |
|
| 7 | 187 | | return assembly; |
| | 188 | | } |
| 2 | 189 | | catch (FileNotFoundException ex) |
| 2 | 190 | | { |
| 2 | 191 | | this.logger.LogError(ex, "Assembly file not found: {Path}", assemblyPath); |
| 2 | 192 | | throw; |
| | 193 | | } |
| 2 | 194 | | catch (BadImageFormatException ex) |
| 2 | 195 | | { |
| 2 | 196 | | this.logger.LogError(ex, "Invalid assembly format: {Path}", assemblyPath); |
| 2 | 197 | | throw; |
| | 198 | | } |
| 0 | 199 | | catch (SecurityException ex) |
| 0 | 200 | | { |
| 0 | 201 | | this.logger.LogError(ex, "Security exception loading assembly: {Path}", assemblyPath); |
| 0 | 202 | | throw; |
| | 203 | | } |
| 0 | 204 | | catch (PathTooLongException ex) |
| 0 | 205 | | { |
| 0 | 206 | | this.logger.LogError(ex, "Path too long for assembly: {Path}", assemblyPath); |
| 0 | 207 | | throw; |
| | 208 | | } |
| 0 | 209 | | catch (ReflectionTypeLoadException ex) |
| 0 | 210 | | { |
| 0 | 211 | | this.logger.LogError(ex, "Failed to load types from assembly: {Path}", assemblyPath); |
| | 212 | |
|
| | 213 | | // Log the loader exceptions for more detailed diagnostics |
| 0 | 214 | | if (ex.LoaderExceptions != null) |
| 0 | 215 | | { |
| 0 | 216 | | int loaderExceptionCount = ex.LoaderExceptions.Length; |
| 0 | 217 | | this.logger.LogError("Loader exceptions count: {Count}", loaderExceptionCount); |
| | 218 | |
|
| | 219 | | // Log up to 5 loader exceptions to avoid excessive logging |
| 0 | 220 | | int logCount = Math.Min(loaderExceptionCount, 5); |
| 0 | 221 | | for (int i = 0; i < logCount; i++) |
| 0 | 222 | | { |
| 0 | 223 | | var loaderEx = ex.LoaderExceptions[i]; |
| 0 | 224 | | if (loaderEx != null) |
| 0 | 225 | | { |
| 0 | 226 | | this.logger.LogError(loaderEx, "Loader exception {Index}: {Message}", i + 1, loaderEx.Messag |
| 0 | 227 | | } |
| 0 | 228 | | } |
| | 229 | |
|
| 0 | 230 | | if (loaderExceptionCount > logCount) |
| 0 | 231 | | { |
| 0 | 232 | | this.logger.LogError("... and {Count} more loader exceptions", loaderExceptionCount - logCount); |
| 0 | 233 | | } |
| 0 | 234 | | } |
| | 235 | |
|
| 0 | 236 | | throw; |
| | 237 | | } |
| 0 | 238 | | catch (Exception ex) |
| 0 | 239 | | { |
| 0 | 240 | | this.logger.LogError(ex, "Unexpected error loading assembly: {Path}", assemblyPath); |
| 0 | 241 | | throw; |
| | 242 | | } |
| | 243 | | } |
| 8 | 244 | | } |
| | 245 | |
|
| | 246 | | /// <summary> |
| | 247 | | /// Attempts to determine if a file is likely a native DLL rather than a .NET assembly |
| | 248 | | /// </summary> |
| | 249 | | /// <param name="filePath">Path to the file to check</param> |
| | 250 | | /// <returns>True if the file appears to be a native DLL, false otherwise</returns> |
| | 251 | | private bool IsProbablyNativeDll(string filePath) |
| 2 | 252 | | { |
| | 253 | | try |
| 2 | 254 | | { |
| | 255 | | // Read the first few bytes to check for the PE header |
| 2 | 256 | | using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) |
| 2 | 257 | | { |
| 2 | 258 | | if (fileStream.Length < 64) |
| 2 | 259 | | { |
| 2 | 260 | | return false; // Too small to be a valid DLL |
| | 261 | | } |
| | 262 | |
|
| 0 | 263 | | byte[] buffer = new byte[2]; |
| 0 | 264 | | int bytesRead = fileStream.Read(buffer, 0, 2); |
| 0 | 265 | | if (bytesRead < 2) |
| 0 | 266 | | { |
| 0 | 267 | | return false; // Not enough bytes to determine if it's a DLL |
| | 268 | | } |
| | 269 | |
|
| | 270 | | // Check for the MZ header (0x4D, 0x5A) |
| 0 | 271 | | if (buffer[0] != 0x4D || buffer[1] != 0x5A) |
| 0 | 272 | | { |
| 0 | 273 | | return false; // Not a valid PE file |
| | 274 | | } |
| | 275 | |
|
| | 276 | | // Skip to the PE header offset location |
| 0 | 277 | | fileStream.Seek(0x3C, SeekOrigin.Begin); |
| | 278 | |
|
| | 279 | | // Read the PE header offset |
| 0 | 280 | | byte[] offsetBuffer = new byte[4]; |
| 0 | 281 | | bytesRead = fileStream.Read(offsetBuffer, 0, 4); |
| 0 | 282 | | if (bytesRead < 4) |
| 0 | 283 | | { |
| 0 | 284 | | return false; // Not enough bytes to determine if it's a DLL |
| | 285 | | } |
| | 286 | |
|
| 0 | 287 | | int peOffset = BitConverter.ToInt32(offsetBuffer, 0); |
| | 288 | |
|
| | 289 | | // Seek to the PE header |
| 0 | 290 | | fileStream.Seek(peOffset, SeekOrigin.Begin); |
| | 291 | |
|
| | 292 | | // Read the PE signature |
| 0 | 293 | | byte[] peBuffer = new byte[4]; |
| 0 | 294 | | bytesRead = fileStream.Read(peBuffer, 0, 4); |
| 0 | 295 | | if (bytesRead < 4) |
| 0 | 296 | | { |
| 0 | 297 | | return false; // Not enough bytes to determine if it's a DLL |
| | 298 | | } |
| | 299 | |
|
| | 300 | | // Check for PE signature "PE\0\0" |
| 0 | 301 | | if (peBuffer[0] != 0x50 || peBuffer[1] != 0x45 || peBuffer[2] != 0 || peBuffer[3] != 0) |
| 0 | 302 | | { |
| 0 | 303 | | return false; // Not a valid PE file |
| | 304 | | } |
| | 305 | |
|
| | 306 | | // It's a valid PE file, but we need more checks to determine if it's a .NET assembly |
| | 307 | | // Skip the COFF header (20 bytes) |
| 0 | 308 | | fileStream.Seek(peOffset + 4 + 20, SeekOrigin.Begin); |
| | 309 | |
|
| | 310 | | // Read the Optional Header magic value |
| 0 | 311 | | byte[] magicBuffer = new byte[2]; |
| 0 | 312 | | bytesRead = fileStream.Read(magicBuffer, 0, 2); |
| 0 | 313 | | if (bytesRead < 2) |
| 0 | 314 | | { |
| 0 | 315 | | return false; // Not enough bytes to determine if it's a DLL |
| | 316 | | } |
| | 317 | |
|
| | 318 | | // PE32 (0x10B) or PE32+ (0x20B) |
| 0 | 319 | | ushort magic = BitConverter.ToUInt16(magicBuffer, 0); |
| 0 | 320 | | if (magic != 0x10B && magic != 0x20B) |
| 0 | 321 | | { |
| 0 | 322 | | return false; // Not a valid PE optional header |
| | 323 | | } |
| | 324 | |
|
| | 325 | | // Skip to the data directories |
| | 326 | | int dataDirectoryOffset; |
| 0 | 327 | | if (magic == 0x10B) |
| 0 | 328 | | { |
| 0 | 329 | | dataDirectoryOffset = 96; // PE32 |
| 0 | 330 | | } |
| | 331 | | else |
| 0 | 332 | | { |
| 0 | 333 | | dataDirectoryOffset = 112; // PE32+ |
| 0 | 334 | | } |
| | 335 | |
|
| 0 | 336 | | fileStream.Seek(peOffset + 4 + 20 + dataDirectoryOffset, SeekOrigin.Begin); |
| | 337 | |
|
| | 338 | | // The 15th data directory is the CLR header (14 zero-based index) |
| 0 | 339 | | fileStream.Seek(14 * 8, SeekOrigin.Current); |
| | 340 | |
|
| | 341 | | // Read the CLR header RVA and size |
| 0 | 342 | | byte[] clrBuffer = new byte[8]; |
| 0 | 343 | | bytesRead = fileStream.Read(clrBuffer, 0, 8); |
| 0 | 344 | | if (bytesRead < 8) |
| 0 | 345 | | { |
| 0 | 346 | | return false; // Not enough bytes to determine if it's a DLL |
| | 347 | | } |
| | 348 | |
|
| 0 | 349 | | uint clrRva = BitConverter.ToUInt32(clrBuffer, 0); |
| 0 | 350 | | uint clrSize = BitConverter.ToUInt32(clrBuffer, 4); |
| | 351 | |
|
| | 352 | | // If the CLR header RVA is 0, it's not a .NET assembly |
| 0 | 353 | | return clrRva == 0; |
| | 354 | | } |
| | 355 | | } |
| 0 | 356 | | catch (Exception ex) |
| 0 | 357 | | { |
| 0 | 358 | | this.logger.LogDebug(ex, "Error checking if file is a native DLL: {Path}", filePath); |
| 0 | 359 | | return false; // Assume it's not a native DLL if we can't check |
| | 360 | | } |
| 2 | 361 | | } |
| | 362 | |
|
| | 363 | | /// <summary> |
| | 364 | | /// Validates that the specified path contains a valid .NET assembly |
| | 365 | | /// </summary> |
| | 366 | | /// <param name="assemblyPath">Path to validate</param> |
| | 367 | | /// <returns>True if path contains a valid assembly, false otherwise</returns> |
| | 368 | | public bool IsValidAssembly(string assemblyPath) |
| 11 | 369 | | { |
| 11 | 370 | | if (string.IsNullOrWhiteSpace(assemblyPath)) |
| 5 | 371 | | { |
| 5 | 372 | | this.logger.LogDebug("Assembly path is null or empty"); |
| 5 | 373 | | return false; |
| | 374 | | } |
| | 375 | |
|
| | 376 | | try |
| 6 | 377 | | { |
| | 378 | | // Check if the file exists |
| 6 | 379 | | if (!File.Exists(assemblyPath)) |
| 2 | 380 | | { |
| 2 | 381 | | this.logger.LogDebug("Assembly file does not exist: {Path}", assemblyPath); |
| 2 | 382 | | return false; |
| | 383 | | } |
| | 384 | |
|
| | 385 | | // Try to load the assembly in a temporary context to validate it |
| 4 | 386 | | var tempContext = new IsolatedAssemblyLoadContext(assemblyPath, this.logger); |
| | 387 | | try |
| 4 | 388 | | { |
| 4 | 389 | | var assembly = tempContext.LoadFromAssemblyPath(assemblyPath); |
| | 390 | |
|
| | 391 | | // If we got here, the assembly is valid |
| 2 | 392 | | this.logger.LogDebug("Successfully validated assembly: {Path}", assemblyPath); |
| 2 | 393 | | return true; |
| | 394 | | } |
| | 395 | | finally |
| 4 | 396 | | { |
| | 397 | | // Unload the temporary context |
| 4 | 398 | | tempContext.Unload(); |
| 4 | 399 | | } |
| | 400 | | } |
| 2 | 401 | | catch (Exception ex) |
| 2 | 402 | | { |
| 2 | 403 | | this.logger.LogDebug(ex, "Assembly validation failed for {Path}: {Message}", assemblyPath, ex.Message); |
| 2 | 404 | | return false; |
| | 405 | | } |
| 11 | 406 | | } |
| | 407 | |
|
| | 408 | | /// <summary> |
| | 409 | | /// Unloads all loaded assemblies and their contexts |
| | 410 | | /// </summary> |
| | 411 | | public void UnloadAll() |
| 6 | 412 | | { |
| 6 | 413 | | this.logger.LogInformation("Unloading all assemblies"); |
| | 414 | |
|
| 24 | 415 | | foreach (var context in this.loadContexts.Values) |
| 3 | 416 | | { |
| | 417 | | try |
| 3 | 418 | | { |
| 3 | 419 | | context.Unload(); |
| 3 | 420 | | } |
| 0 | 421 | | catch (Exception ex) |
| 0 | 422 | | { |
| 0 | 423 | | this.logger.LogWarning(ex, "Error unloading assembly context"); |
| 0 | 424 | | } |
| 3 | 425 | | } |
| | 426 | |
|
| 6 | 427 | | this.loadContexts.Clear(); |
| 6 | 428 | | this.loadedAssemblies.Clear(); |
| 6 | 429 | | } |
| | 430 | |
|
| | 431 | | /// <summary> |
| | 432 | | /// Disposes the assembly loader and unloads all assemblies |
| | 433 | | /// </summary> |
| | 434 | | public void Dispose() |
| 4 | 435 | | { |
| 4 | 436 | | this.logger.LogDebug("Disposing AssemblyLoader"); |
| 4 | 437 | | UnloadAll(); |
| 4 | 438 | | GC.SuppressFinalize(this); |
| 4 | 439 | | } |
| | 440 | | } |