Skip to content

Instantly share code, notes, and snippets.

@danmoseley
Created October 26, 2019 23:21
Show Gist options
  • Save danmoseley/f2a6aac094842a233334a94d9ece9a1e to your computer and use it in GitHub Desktop.
Save danmoseley/f2a6aac094842a233334a94d9ece9a1e to your computer and use it in GitHub Desktop.
// This test should apply equally to Unix, but this reliably hits a particular one of the
// myriad ways that assembly load can fail
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsWindows))]
public void LoadFile_ValidPEBadIL_ThrowsBadImageFormatExceptionWithPath()
{
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "kernelbase.dll");
if (!File.Exists(path))
return;
AssertExtensions.ThrowsContains<BadImageFormatException>(() => Assembly.LoadFile(path), path);
}
[Theory]
[InlineData(0)]
[InlineData(5)]
[InlineData(50)]
[InlineData(100)]
// Higher numbers hit some codepaths that currently don't include the path in the exception message
public void LoadFile_ValidPEBadIL_ThrowsBadImageFormatExceptionWithPath(int seek)
{
ReadOnlySpan<byte> garbage = Encoding.UTF8.GetBytes(new string('X', 500));
string path = GetTestFilePath();
File.Copy(SourceTestAssemblyPath, path);
using (var fs = new FileStream(path, FileMode.Open))
{
fs.Seek(seek, SeekOrigin.Begin);
fs.Write(garbage);
}
AssertExtensions.ThrowsContains<BadImageFormatException>(() => Assembly.LoadFile(path), path);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment