INTERCEPTING WINDOWS FUNCTION CALLS

One interesting use of dynamic libraries is in debugging. For instance, you might want to write a dynamic link library that extensively checks the parameters your program is passing to the normal Windows functions. Such a library for checking parameters to the GDI functions might be called CHECKGDI; a typical function in CHECKGDI.C would look something like this:

int xRectangle (hdc, xLeft, yTop, xRight, yBottom)

HDC hdc ;

short xLeft, yTop, xRight, yBottom ;

{

BOOL bError = FALSE ;

int iCode ;

/* check parameters, set bError to FALSE and iCode

to an error code if errors are encountered */

if (bError)

FatalExit (iCode) ;

return Rectangle (hdc, xLeft, yTop, xRight, yBottom) ;

}

You can give this function any name you want, as long as it isn't the same as the name of a real Windows function. (I've called it xRectangle.) The FatalExit function causes the debugging version of Windows to display a stack trace on a terminal attached to the COM1 port.

The EXPORTS section of CHECKGDI.DEF lists all these checking functions but gives each of them an external name that is the name of the actual Windows function:

EXPORTS Rectangle = xRectangle @1

Ellipse = xEllipse @2

LineTo = xLineTo @3

[and so forth]

You compile and link this CHECKGDI library in the same way as STRLIB. The creation of the CHECKGDI.LIB import library looks like this:

implib checkgdi.lib checkgdi.def

Now if you have a program in development that calls normal GDI functions, you can do parameter checks during run time by linking the program (I'll assume the program is called MYPROG) as shown below:

link myprog, /align:16, NUL, /nod /noe checkgdi slibcew libw, myprog

Because you have included the CHECKGDI.LIB library in the library field of LINK, any calls in your program to Rectangle, Ellipse, LineTo, and so forth will actually reference the xRectangle, xEllipse, and xLineTo functions in the CHECKGDI.EXE library. In CHECKGDI the functions perform the checks you want and then call the actual GDI functions.

Once you're done debugging, you can make the program call the regular Windows GDI functions simply by deleting MYPROG.EXE and relinking like this without the CHECKGDI.LIB import library:

link myprog, /align:16, NUL, slibcew libw, myprog

Now LINK will use LIBW.LIB to reconcile your GDI calls with the functions in the normal GDI module. Because this approach requires no changes to your program source code, it is a clean way of inserting debugging code between your calls to Windows functions and the actual functions.