C # How to get code from a process and then run it?

Since the process is an instance of a computer program and contains the program code and its current activity, I tried the following:

  • Parse my process and extract an array of bytes.
  • Execute these bytes.

My problem is that I am extracting both the program code and its current activity, while I am only interested in the first part.

This is how I extract the bytes of my "foo" process:

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(); } 

And this is how I try to execute it:

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

And this gives me the following error:

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

Meanwhile, if I extract the bytes from my program "foo.exe" and execute them as shown below, it works.

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

The byte array that I extract from my process is significantly larger than the one that I extract from my "foo.exe" file. Because I believe that I also extract the current activity of the process.

How can I get only part of my process code?

Does it launch IntPtr.Zero or later? And when will I stop?

Any help would be appreciated, thanks in advance.

+5
source share
1 answer

If you read about the Assembly.Load function, you can see that you are using it incorrectly. Just because it allows you to use an array of bytes as input, this does not mean that you are supplying it with the correct array of bytes.

Assembly.Load (Byte [])

Loads an assembly with an image based on a shared object file (COFF) containing the emitted assembly. The assembly is loaded into the caller's application domain.

File format COFF

This is not what you are doing, obviously. Basically, what you do cannot be done. CherryDT also gave you good reason in your comments.

0
source

All Articles