Run program from byte array

I have a program stored in an array of bytes.

Is it possible to run it inside C #?

+15
arrays c # byte
Jun 04 '10 at 19:24
source share
5 answers

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

+15
Jun 04 '10 at 19:41
source share

Sure.

  • Save the byte array in the .exe .
  • Use the Process class to execute the file.

Note : it is assumed that your byte array is executable code, not source code. It also assumes that you have a valid PE header or know how to create one.

+11
Jun 04 '10 at 19:29
source share

Assuming the byte array contains the .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 caller, you can apply it to this interface and call methods on it:

  ((MyInterface)instance).methodToInvoke(); 
+11
Jun 04 '10 at 19:42
source share

If the byte array is an .Net assembly with EntryPoint (the main method), you can just do it. In most cases, returnValue will be null . And if you want to provide command line arguments, you can put them in the commandArgs line below.

 var assembly = Assembly.Load(assemblyBuffer); var entryPoint = assembly.EntryPoint; var commandArgs = new string[0]; var returnValue = entryPoint.Invoke(null, new object[] { commandArgs }); 
+6
Jun 04 '10 at 20:28
source share

You can create a virtual machine and execute the code OR use potential reflections and dynamic types to create a dynamic assembly. You can dynamically load the assembly.

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

So you could do something about it. If my memory serves me, though there are some limitations.

Cm.

Reflection Assembly.Load Application Area

+4
Jun 04 '10 at 19:36
source share



All Articles