I used to code on a non-intel 8-bit processor years ago, and am now having a go at a little assembly from Delphi. I've been reading some of Intel's documentation (the IA-32 Intel Architechture Software Developers Manual) and am slowly getting the idea of all this stuff about segment registers. Now here's the question...

Is it utterly true that I can just ignore segments when I'm coding Win32 applications? Everywhere on the net seems to indicate that Windows uses a flat memory model and that I can just use simple 32 bit addressing. The reason I'm asking is that the CS, DS, SS, ES, FS, GS registers don't all seem to hold the same value in my application and I expected that they would on a true flat memory model.

I've been trying out the idea of creating code on the fly by placing it into an array of bytes and calling the VirtualProtect API call to get the relevant access rights from Windows, and it seems to work fine. But my guess is that my ordinary Delphi array must exist in the the data segment, and that code would normally reside in the code segment. So is it really safe me executing code that resides in the data segment?

If anyone could enlighten me I'd be dead grateful!

Posted on 2004-02-17 11:28:32 by philthy256
(don't cross-post)

Yes, you can ignore segment registers - while they might not contain the same value (CS segment/selector references a descriptor with the CODE type, DS/ES has DATA type, SS has STACK type), they all point to the same piece of base=0 limit=4GB linear memory. The exception is FS, which points to some per-thread information (of which most people will only, if ever, need the SEH stuff), and GS is... well, I dunno and don't care ^_^.

Since we're in a flat memory model, it doesn't really matter that you're using DS to write to the code but CS to execute it. What matters is that you write to memory *pages* that are writable (code typically isn't), and execute memory *pages* that are executable (as indicated with VirtualAlloc or VirtualProtect). Also note that the IA32 doesn't really have a per-page "execute allowed" bit (it can be implemented with "pretty tricky code" though), but it's coming with AMD64...

So... under win32, you don't have to worry about physical addresses, and logical=linear addresses. You don't have to worry about segments/selectors, you just have to worry about memory pages.
Posted on 2004-02-17 11:40:06 by f0dder
(re: cross post - whoops, sorry!)

Excellent - that made good sense. Thanks soo much!
Posted on 2004-02-17 13:14:58 by philthy256
Hope that I've helped ^_^
Posted on 2004-02-17 13:16:51 by f0dder
Exactly what I needed - thank you!
Posted on 2004-02-18 03:17:56 by philthy256