Could somebody please explain...

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
Kyretzn

Could somebody please explain...

Post by Kyretzn »

Hi! Its me again, the Nugget :P

Anyways, I was reading through a bootstrap tutorial and it was setting "segments"

Im not quite sure why I have to do it, but im sure its important. So ill ask you guys :)

this is the code:

Start:
; Update the segment registers?
; Im not really sure why we are doing this.
mov ax, cs
mov ds, ax
mov es, ax

a) What exactly does this do?
b) Why do we have to do it? :)

Thanks!
~kyretzn
Kyretzn

Re:Could somebody please explain...

Post by Kyretzn »

Cheers!
User avatar
Pype.Clicker
Member
Member
Posts: 5964
Joined: Wed Oct 18, 2006 2:31 am
Location: In a galaxy, far, far away
Contact:

Re:Could somebody please explain...

Post by Pype.Clicker »

mainly, when your bootloader gets started, you have no idea of what the BIOS left in the data segment registers. All you know is that you're running code that lies at physical address 0x7c00. You don't even know if the BIOS used "jmp 0x7c0:0" or "jmp 0:0x7c00". Both are valid and both are met in different BIOSes

so

Code: Select all

mov ax,cs
mov ds,ax
mov es,ax
may not be that helpful ...

E.g.

Code: Select all

org 0   ; we're assuming jmp 0x7c0:0, 
          ; thus program starts at offset 0 in code segment
mov ax, cs
mov ds, ax  ; loads ds with 0x7c0 ... hopefully
mov es, ax  ; data access will get wrong if BIOS used 0:0x7c00
So the proper way would rather be

Code: Select all

org 0   ; we're assuming jmp 0x7c0:0, 
          ; thus program starts at offset 0 in code segment
jmp 0x7c0:here
here:
          ; enforce cs = 7c0 in case BIOS used 0:0x7c00
mov ax, cs
mov ds, ax  ; loads ds with 0x7c0 ...
mov es, ax  ; data access will be ok, now :)
And it's somehow a short way to say

Code: Select all

org 0
jmp 0x7c0:here
mov ax,0x7c0 ; takes 3 bytes
mov ds,ax  ; takes 2 bytes, such as "mov ax,cs"
mov es,ax  ; you can't load immediates to segments anyway
pradeep

Re:Could somebody please explain...

Post by pradeep »

you have to store the .text segment address in DS & ES for referring to the strings but in case of a boot loader your strings will be placed in the code segment so you have to set DS & ES equal to CS. If you are not going to use any strings in your boot loader then no need of setting DS & ES = CS . You may need string to display some error messages
AR

Re:Could somebody please explain...

Post by AR »

If the program is written in C then the compiler will assume a flat memory model (that all segments start and end at the same addresses), if you write the program in assembly then you can rearrange the segments however you like, just remember to use the proper offsets when you access data compiled into the program.
Post Reply