gpt4 book ai didi

C# 如何从进程中检索代码然后运行它?

转载 作者:可可西里 更新时间:2023-11-01 13:48:42 24 4
gpt4 key购买 nike

由于进程是计算机程序的实例并且包含程序代码及其当前事件,因此我尝试了以下操作:

  • 解析我的进程并检索字节数组。
  • 执行那些字节。

我的问题是我检索了程序代码及其当前事件,而我只对第一部分感兴趣。

以下是我如何检索进程“foo”的字节:

 public static byte[] retrieveProcessBytes(String processName) {
Process process = ApplicationFinder.FromProcessName(processName).First();
var sharp = new MemorySharp(process);

List<byte> bytes = new List<byte>();
IntPtr ptr = IntPtr.Zero;
try
{
while (true) {
bytes.Add(sharp.Read<byte>(ptr, 1)[0]);
ptr = IntPtr.Add(ptr, 1);
}
}
catch (Exception e) {
Console.Write("Exception caught : " + e);
}
return bytes.ToArray();
}

下面是我尝试执行它的方式:

byte[] bytes = retrieveProcessBytes("foo");
Assembly asm = Assembly.Load(bytes);
Object[] Args = new Object[0];
asm.EntryPoint.Invoke(null, Args);

它给了我以下错误:

An unhandled exception of type 'System.BadImageFormatException' occurred in mscorlib.dll

同时,如果我从我的“foo.exe”程序中检索字节并执行它们,如下所示,它会起作用。

Byte[] bytes = File.ReadAllBytes(pathToFooExe);
Assembly asm = Assembly.Load(bytes);

我从我的进程中检索到的字节数组比我从“foo.exe”文件中检索到的字节数组大得多。因为我想我也检索了当前的流程事件。

如何才能只检索流程的代码部分?

它是从 IntPtr.Zero 开始还是更晚?我什么时候停止?

如有任何帮助,我们将不胜感激,在此先致谢。

最佳答案

如果您了解函数 Assembly.Load,您会发现您没有正确使用它。仅仅因为它允许一个字节数组作为输入并不意味着您正在为它提供一个正确的字节数组。

Assembly.Load(Byte[])

Loads the assembly with a common object file format (COFF)-based image containing an emitted assembly. The assembly is loaded into the application domain of the caller.

COFF file format

这显然不是您正在做的。基本上,您正在做的事情无法完成。 CherryDT 在他的评论中也给了你很好的理由。

关于C# 如何从进程中检索代码然后运行它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37372089/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com