Function Forwarders

[Previous] [Next]

A function forwarder is an entry in a DLL's export section that redirects a function call to another function in another DLL. For example, if you run the Visual C++ DumpBin utility on the Windows 2000 Kernel32.dll, you'll see a part of the output that looks like this:

 C:\winnt\system32>DumpBin -Exports Kernel32.dll  (some output omitted) 360 167 HeapAlloc (forwarded to NTDLL.RtlAllocateHeap) 361 168 HeapCompact (000128D9) 362 169 HeapCreate (000126EF) 363 16A HeapCreateTagsW (0001279E) 364 16B HeapDestroy (00012750) 365 16C HeapExtend (00012773) 366 16D HeapFree (forwarded to NTDLL.RtlFreeHeap) 367 16E HeapLock (000128ED) 368 16F HeapQueryTagW (000127B8) 369 170 HeapReAlloc (forwarded to NTDLL.RtlReAllocateHeap) 370 171 HeapSize (forwarded to NTDLL.RtlSizeHeap)  (remainder of output omitted) 

This output shows four forwarded functions. Whenever your application calls HeapAlloc, HeapFree, HeapReAlloc, or HeapSize, your executable is dynamically linked with Kernel32.dll. When you invoke your executable, the loader loads Kerenl32.dll and sees that forwarded functions are actually contained inside NTDLL.dll. It then loads the NTDLL.dll module as well. When your executable calls HeapAlloc, it is actually calling the RtlAllocateHeap function inside NTDLL.dll. A HeapAlloc function doesn't exist anywhere in the system!

If you call the following function, GetProcAddress looks in Kernel32's export section, sees that HeapAlloc is a forwarded function, and then calls GetProcAddress recursively, looking for RtlAllocateHeap inside NTDLL.dll's export section.

 GetProcAddress(GetModuleHandle("Kernel32"), "HeapAlloc"); 

You can take advantage of function forwarders in your DLL module as well. The easiest way to do this is by using a pragma directive, as shown here:

 // Function forwarders to functions in DllWork #pragma comment(linker, "/export:SomeFunc=DllWork.SomeOtherFunc") 

This pragma tells the linker that the DLL being compiled should export a function called SomeFunc. But the actual implementation of SomeFunc is in another function called SomeOtherFunc, which is contained in a module called DllWork.dll. You must create separate pragma lines for each function you want to forward.



Programming Applications for Microsoft Windows
Programming Applications for Microsoft Windows (Microsoft Programming Series)
ISBN: 1572319968
EAN: 2147483647
Year: 1999
Pages: 193

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net