views:

41

answers:

3

lpBuffer is a pointer to the first byte of a (binary)resource. How can I execute it straight away without dumping it to a temporary file?

HMODULE hLibrary;
HRSRC hResource;
HGLOBAL hResourceLoaded;
LPBYTE lpBuffer;

hLibrary = LoadLibrary("C:\\xyz.exe");
if (NULL != hLibrary)
{
    hResource = FindResource(hLibrary, MAKEINTRESOURCE(104), RT_RCDATA);
    if (NULL != hResource)
    {
        hResourceLoaded = LoadResource(hLibrary, hResource);
        if (NULL != hResourceLoaded)        
        {
            lpBuffer = (LPBYTE) LockResource(hResourceLoaded);            
            if (NULL != lpBuffer)            
            {                
                // do something with lpBuffer here            
            }
        }    
    }
    FreeLibrary(hLibrary);
}
+2  A: 

There isn't a function built into Windows for this; your only option is CreateProcess, which takes an EXE file.

It's possible to parse the executable file format yourself. You'd effectively be recreating what the LoadLibrary function does.

Here's an explanation of how to load a DLL and call functions within it: http://www.joachim-bauch.de/tutorials/loading-a-dll-from-memory/. To adapt this for your EXE, you'd follow the same relocation and import steps. Once you're done you'd call the EXE's entry point. (The tutorial explains how to call a DLL's exported function.)

Depending on what's in the EXE you might have problems loading it directly into an existing process. For instance, your own EXE performs various Win32 and C initialization code, and the embedded EXE is likely to attempt to perform the same initialization again. If this becomes a problem, your alternative is to put the embedded EXE in its own process; then, you're back to creating a temp file and calling CreateProcess.

Tim Robinson
Things don't work like that. You can't just execute code which has been loaded as a resource. Relocations have to be performed. Imports have to be resolved.
wj32
Things could work like that, hence my "what's your format" question. The OP doesn't mention what's in the binary resource.
Tim Robinson
It's an exe file
Bubblegun
@wj32 @Bubblegun I've rewritten my answer based on this new information
Tim Robinson
@Tim Thanks for your input. I'll check the tutorial
Bubblegun
+1  A: 

If the resource is a PE file, then is no way AFAIK. If it is a simple compiled procedure try Tim's trick.

Edit: After Tim's answer update, it the most complete answer.

mmonem
A: 
stakx