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.