Walking the Stack

One little mystery remains. You'll recall that the far function prolog includes the statements:

INC BP

PUSH BP

The epilog then returns BP to normal:

POP BP

DEC BP

What is this for?

Think about this problem: Free memory is very low. A function in one of your program's code segments calls a far function in another of your program's code segments. This function then calls a Windows function. The code segment containing this Windows function is not currently present in memory. To load it into memory, Windows has to move your data segment and discard both your code segments. This sounds like a serious problem, because when the Windows function returns to your program, your program will be gone.

When Windows must discard code segments, it first goes through a little exercise called ”walking the stack.“ Within any function, the value of SS:[BP] is the value of BP from the previous function. If this previous value of BP is even, the previous function is a near function; if it's odd, the previous function is a far function. By using successive values of BP stored on the stack, Windows can trace through the stack until it reaches the top, which is the stack pointer address originally given to your program when the program began executing. Windows can determine the segment addresses and the saved DS register values of all the functions involved in making the current Windows function call.

If Windows has to move your program's data segment (which also requires moving the stack), it can adjust the DS register on the stack to the new segment address. If Windows has to move a code segment containing functions that have been involved in the current Windows function call, it changes the return address on the stack. If Windows has to discard a code segment, it replaces the return address with an address that points to code, which reloads the segment and which then branches to the appropriate return address.

As I mentioned at the onset of this discussion, you may prefer not to think about all this activity going on in the innards of Windows.