понедельник, 22 октября 2007 г.

Just before improving implementation for dynamic SEH unwinding support

All times we declare local variables of finalized types the Delphi compiler inserts hidden try finally block that forces local variables of finalized types to be finalized under any circumstances.

Look at the next sample.

Delphi code

procedure TForm1.Button1Click(Sender: TObject);
var a:string;
begin
a:='abcdef';
end;

is mapped to appropriate x86 assembler code.
Something like this

push ebp
mov ebp,esp
push $00
xor eax,eax

{
This is the hidden try
}
push ebp
push $XXXXXXXX
push dword ptr fs:[eax]
mov fs:[eax],esp


Unit1.pas. XX: a:='abcdef';
lea eax,[ebp-$04]
mov edx,$XXXXXXXX
call @LStrLAsg
Unit1.pas.XX: end;
xor eax,eax
pop edx
pop ecx
pop ecx
mov fs:[eax],edx
push $XXXXXXXX
{
Local variable Finalization code
}
lea eax,[ebp-$04]
call @LStrClr

ret

{
And this is the hidden finally block
}
jmp @HandleFinally
jmp $XXXXXXXX

{Normal procedure Exit }
pop ecx
pop ebp
ret

Little explanation about SEH.

FS is protected mode selector that indexes descriptor of segment in descriptor tables (descriptors map logical address space to linear) .
Segment that is indexed by FS has special meaning for Windows Operation System.
This segment contains structure known as Thread Environment Block, TEB. But TEB structure includes at start of it a Win32 Thread Information Block (TIB). Win32 Thread Information Block (TIB) is a data structure in Win32 on x86 that stores info about the currently running thread.
First field of TIB (i.e. fs:[0]) is current Structured Exception Handling frame.
This field is used by system to provide your code the ability to react on raised exception.
Because your procedures and functions may consist of not only hidden try/finally blocks, but yours try/finally try/except blocks, I have to implement some special SEH unwinding code and if there is any displacement I need to correct this dynamically.

And because Yield has a very specific behaviour I have to dynamically attach/detach/correct local SEH frames.

Read about this in my next article.

Комментариев нет: