Page 1 of 1

Setting code register

Posted: Sat Oct 08, 2022 1:02 pm
by maor36a
Hey all,

I am writing my first bootloader and going through some tutorials and can't really figure out the answer.

Some tutorials do that:

Code: Select all

[ORG 0]
    jmp 07C0h:start         ; Goto segment 07C0

    start:
            ; Update the segment registers
            mov ax, cs
            mov ds, ax
            mov es, ax
I totally understand why it is important to initialize the data and extra segment.
Why is the first jmp also initializes the code segment?
I guess that IPC begins to run from the beginning of the code segment, along the code segment, so it'll be set as a result of setting the code segment register.

Re: Setting code register

Posted: Tue Oct 11, 2022 10:20 pm
by Octocontrabass
The value of CS affects indirect jumps. You need to set CS to a known value before you can use any indirect jumps. Indirect jumps are pretty uncommon, especially in simple code like a tutorial bootloader, so you might end up not needing it for a while.

I would also recommend using "org 0x7c00" and setting the segment registers to 0 instead of using "org 0" and setting the segment registers to 0x7c0. Setting the segment registers to nonzero values means a non-flat address space, which will complicate things later when you switch to protected or long mode with a flat address space.

Re: Setting code register

Posted: Wed Oct 12, 2022 3:30 pm
by devc1
What IPC are you talking about ?

Using the code segment is just like using the data segment, so the code is read from cs:offset.

If cs = 0x100, jmp 0x10 will actually jump to 0x1010. It is the same thing as data segments.

You can just use the org directive.

Re: Setting code register

Posted: Wed Oct 12, 2022 3:58 pm
by nexos
Because BIOSes aren't consistent with how they set CS. E.g., some old Compaq BIOSes set CS to 0x7C0 on entry and the vast majority of BIOSes set CS to 0.
I guess that IPC begins to run from the beginning of the code segment, along the code segment, so it'll be set as a result of setting the code segment register.
I assume you're talking about IP when you say IPC.

No, IP does not start at the start of the code segment. The far jump set CS to 0x7C0, and IP to whatever the value of start is (probably 0x3 in your case).

Now as Octo said, it's a good idea to use "org 0x7C00" and use flat segments (i.e., set CS, DS, ES, and SS to 0). Also, if you haven't yet, you should brush up on seg:offset memory addressing. Like this: https://en.wikipedia.org/wiki/X86_memor ... #Real_mode