Run Program from byte array

13,461

Solution 1

Yes. This answer shows you can directly execute the contents of a byte array. Basically, you use VirtualAlloc to allocate an executable region on the heap with a known address (a IntPtr). You then copy your byte array to that address with Marshal.Copy. You convert the pointer to a delegate with GetDelegateForFunctionPointer, and finally call it as a normal delegate.

Solution 2

Sure.

  1. Save the byte array to an .exe file.
  2. Use the Process class to execute the file.

Note: this is assuming that your byte array is executable code, and not source code. This also assumes that you have a valid PE header or know how to make one.

Solution 3

Assuming the byte array contains a .net assembly (.exe or .dll):

 Assembly assembly = AppDomain.Load(yourByteArray)
 Type typeToExecute = assembly.GetType("ClassName");
 Object instance = Activator.CreateInstance(typeToExecute);

Now, if typeToExecute implements an interface known to your calling program, you can cast it to this interface and invoke methods on it:

 ((MyInterface)instance).methodToInvoke();

Solution 4

If the byte array is a .Net assembly with an EntryPoint (Main method) you could just do this. Most of the time returnValue would be null. And if you wanted to provide command line arguments you could put them in the commandArgs string listed below.

var assembly = Assembly.Load(assemblyBuffer);
var entryPoint = assembly.EntryPoint;
var commandArgs = new string[0];
var returnValue = entryPoint.Invoke(null, new object[] { commandArgs });

Solution 5

You can create a virtual machine and execute the code OR you could use reflection and dynamic types to create a dynamic assembly, potentially. You can dynamically load assembly.

http://msdn.microsoft.com/en-us/library/system.reflection.assembly.load.aspx

You could thus perhaps do something with that. If my memory serves me though there are some limitations.

See

Reflection Assembly.Load Application Domain

Share:
13,461
DanSpd
Author by

DanSpd

Updated on June 05, 2022

Comments

  • DanSpd
    DanSpd about 2 years

    I have a program stored in byte array.

    Is it possible to run it inside C#?

  • DanSpd
    DanSpd about 14 years
    Is it possible to do that but without actually saving byte array into exe file? Also yes it is executable.
  • JSBձոգչ
    JSBձոգչ about 14 years
    @DanSpd, no. The OS doesn't allow you to execute a separate process from an in-memory executable. You can, with sufficient wizardry, execute in-memory code within your own process space, but this is highly not recommended. And it will make your program look like malware to many scanners, since this technique is often used by viruses and other undesirables.
  • Raquel
    Raquel about 14 years
    You may not be able to spawn it in a second process, but you can run it in a new appdomain.