【问题标题】:Injecting and modifying C# executable注入和修改 C# 可执行文件
【发布时间】:2016-01-26 00:07:15
【问题描述】:

我想问是否有可能以某种方式将 C# 代码注入到现有的 *.exe 文件中,该文件也是用 C# 编写的,而无需反编译。

换句话说,我正在尝试对已经存在的 C# 程序进行“扩展”,但我想在不使用“基本”代码(.*exe 文件)进行任何操作的情况下对其进行修改。

有没有办法做到这一点?或者是否需要反编译过程来修改基本代码的方法、类和/或添加扩展等?

【问题讨论】:

  • 可以直接编辑 IL 代码,而无需将其反编译为 C#、编辑 C#,然后重新编译它,但可能会更难 i> 为您服务,并不容易。
  • 你看过Extension Methods吗?
  • @Servy 编辑 IL 仍在反编译可执行文件。
  • 我同意 Servy,虽然可以将 C# 代码注入到 C# 进程或可执行文件中,但为进程开发“扩展”并将其注入是完全复杂的。修改函数的返回值,很简单,其他的就比较麻烦了。
  • @Jetti 反编译 IL 意味着将 IL 翻译回 C# 代码。您不需要需要来编辑代码的 IL,即使这是最实用的方法。直接编辑 IL 代码只是编辑 IL 代码。编译是将代码从一种语言翻译成另一种语言的过程;编辑 IL 不会更改该代码的语言。

标签: c# reverse-engineering


【解决方案1】:

您可以使用Mono.CecilMicrosoft CCI project 等框架来实现它。这些框架允许您阅读和修改/注入 IL。但是学习那些框架和 IL 代码的使用并不容易。

认为有一个可用的库 FluentIL 构建在 Mono.Cecil 之上,为 IL 代码提供 C# 包装器。它不会反编译程序集,而是加载它,注入程序集可以使用注入的代码编写/生成一个新程序集。

这是一个示例,我用于在项目汇编后编译中将参数标记为 [NotNull] 的方法中注入“Null Checking code”。

var assembly = AssemblyDefinition.ReadAssembly(SourceAssemblyPath);
var module = assembly.MainModule;

var q = from type in module.Types
        from method in type.Methods
        from parameter in method.Parameters
        where parameter.HasCustomAttributes
        from attribute in parameter.CustomAttributes
        where attribute.AttributeType.FullName == NotNullAttribute.FullName
        select new { Method = method, Parameter = parameter };

foreach (var item in q)
{
    item.Method.InsertBefore()
        .Ldarg(item.Parameter.Name)
        .IfNull()
            .Throw<ArgumentNullException>()
        .EndIf();
}

SourceAssemblyPath = SourceAssemblyPath.Replace("\\debug\\", "\\release\\");
assembly.Write(SourceAssemblyPath, new WriterParameters { WriteSymbols = false });

【讨论】:

    猜你喜欢
    • 2011-04-23
    • 1970-01-01
    • 1970-01-01
    • 2011-01-28
    • 2018-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多