Click here to Skip to main content
11,633,425 members (80,721 online)
Click here to Skip to main content
Add your own
alternative version

Dynamic Libraries with Delayed Function Loading

, 27 Oct 2011 Public Domain 10.7K 251 6
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

Share

About the Author

Vasil Bachvarov
Software Developer (Senior)
Bulgaria Bulgaria
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.

You may also be interested in...

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150728.1 | Last Updated 27 Oct 2011
Article Copyright 2011 by Vasil Bachvarov
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid