繁体   English   中英

有没有办法通过预先分析来避免 Assembly.Load 上的 BadImageFormatException

[英]Is there a way to avoid BadImageFormatException on Assembly.Load by pre-analyzing

我有一个应用程序,它将用户放入一个特殊目录的所有 .dll 加载。 如果它们创建错误 (x86,x64) 或其他内容,则会引发 BadImageFormatException。 没关系,但我不喜欢避免例外。 所以问题是:

有没有办法提前分析文件以避免异常?

  • 检查它是否是正确的平台目标
  • 检查它是否不受管理..
    • 其他可能的问题。

主要目标是避免异常。 如果它可以工作,也可以得到一个布尔值。

当前代码:

    private Assembly TryLoadAssmbly(string file)
    {
        Assembly result;

        try
        {
            result = Assembly.LoadFile(file);
        }
        catch (BadImageFormatException exc)
        {
            Log.Error($"File \"{file}\" could not be loaded");
            result = null;
        }

        return result;
    }

我不确定这是否值得努力,但您可以使用PEReader

static bool IsLoadableManagedAssembly(string assemblyPath) {
   using var reader = new PEReader(new StreamReader(assemblyPath));
   ...
}

首先排除没有元数据的文件,它们肯定不是程序集:

if (!reader.HasMetadata)
   return false;

现在您可以检查它是 32 位还是 64 位......事情变得更复杂了。 有一个不错的reader.PEHeaders.PEHeader.Magic可用于检查文件是否仅为 64 位: PEMagic.PE32Plus (如果您的应用程序仅为 32 位,您可以在此处停止。

还在读书? 然后你的目标是任何 CPU或 X64。 你在 COFF object 中有这个:

bool mightBe64 = reader.PEHeaders.CoffHeader.Machine == Machine.IA64
   || reader.PEHeaders.CoffHeader.Machine == Machine.Unknown;

if (Environment.Is64BitProcess != mightBe64)
   return false;

现在我们可以处理任何具有“所需 32 位”的 CPU

bool requires32 = reader.PEHeaders.CorHeader.Flags.HasFlag(CorFlags.Requires32Bit);
if (Environment.Is64BitProcess && requires32)
   return false;

请注意,您也可以(应该?)将CorFlags.ILOnly用于Any CPU

CoffHeader.Characteristics中还有一个Characteristics.Bit32Machine但我不确定是否有任何尚未涵盖的内容。


最重要的是......您仍然需要处理BadImageFormatException因为文件可能无效或者我们在这里遗漏了其他内容。


您是否考虑过缓存搜索结果,以便在第一次之后无需“尝试”加载它们?


参考:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM