Click here to Skip to main content
15,881,812 members
Articles / Desktop Programming / Win32

Dynamic Libraries with Delayed Function Loading

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
27 Oct 2011Public Domain4 min read 24.5K   306   5  
This article explains how to create a dynamic library that loads exported functions the first time they are used, opposed to loading them when the library is loaded.
#include <windows.h>

#include "macros.h"
#include "hooks.h"

#include "delayedfunc.h"

const char *called_proc = NULL;

FARPROC rtn_addr;

DWORD eax_save;
DWORD ebx_save;
DWORD ecx_save;
DWORD edx_save;
DWORD esi_save;
DWORD edi_save;
DWORD esp_save;
DWORD ebp_save;


__declspec(naked)
void proxy_proc_LoadLibrary()
{
	SAVE_RTN_ADDRESS
	SAVE_REGISTERS
	
	{
		HMODULE lib = LoadLibrary("payload_dll.dll");
		if (lib)
		{
			FARPROC payload_proc = GetProcAddress(lib, called_proc);
			if (payload_proc)
			{
				hook_proc_start();

				LOAD_REGISTERS
				__asm
				{
					add esp, 4
					call payload_proc
					sub esp, 4
				}
				SAVE_REGISTERS

				hook_proc_end();
			}

			FreeLibrary(lib);
			lib = NULL;
		}
	}

	LOAD_RTN_ADDRESS
	LOAD_REGISTERS
	__asm ret
}

__declspec(naked)
void proxy_proc()
{
	SAVE_RTN_ADDRESS
	SAVE_REGISTERS
	
	{
		FARPROC payload_proc = Delayed_Function_Load("payload_dll.dll", called_proc);
		if (payload_proc)
		{
			hook_proc_start();

			LOAD_REGISTERS
			__asm
			{
				add esp, 4
				call payload_proc
				sub esp, 4
			}
			SAVE_REGISTERS

			hook_proc_end();
		}
		Delayed_Function_Free(payload_proc);
		// Instead of freeing the function now, you can
		// substitute the JMP address in the export table
		// of the function in proxy_dll with payload_proc.
		// The memory can be freed when proxy_dll is unloaded.
	}

	LOAD_RTN_ADDRESS
	LOAD_REGISTERS
	__asm ret
}

#include "exports.inl"

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under A Public Domain dedication


Written By
Founder
Germany Germany
Software developer since April 2000.
Active in various areas, most notably C/C++ development with Windows platform, web development, scripting.
Coder by heart.
Interested in higher level software development techniques, abstractions, modeling, software factories.
Nuts and bolts guy.

Comments and Discussions