assemblyx86x86-16memory-segmentation

What would happen if the CS segment register is changed? (And how would you do so?)


I read this article: http://static.patater.com/gbaguy/day3pc.htm

It includes the sentence

DON'T EVER CHANGE CS!!

But what exactly would happen if you did modify the CS segment register? Why is it so dangerous?


Solution

  • cs is the code segment. cs:ip, which means cs together with ip (instruction pointer) points to the location of the next instruction. So any change to cs or ip, or to both changes the address from where the next instruction will be fetched and executed.

    Usually you change cs with a jmp (long jump), call (long call), retf, int3, int or iret. In 8088 and 8086 pop cs is also available (opcode 0x0F). pop cs won't work in 186+, in which the code 0x0F is reserved for multi-byte opcodes. http://en.wikipedia.org/wiki/X86_instruction_listings

    There is nothing inherently dangerous in long jump or long call. You just have to know where you jump or call, and in protected mode you need to have sufficient privileges to do it. In 16-bit real mode (eg. DOS) you can jump and call whatever address you wish, eg. jmp 0xF000:0xFFF0 sets cs to 0xF000 and ip to 0xFFF0, which is the start address of BIOS code, and thus reboots the computer. Different memory addresses have different code and thus cause different kinds of results, in theory everything possible can happen (if you jump into BIOS code used for formatting hard-drive, with valid register and/or stack values, then the hard drive will be formatted 'as requested'). In practice jmp's and call's to most addresses probably result in invalid opcode or some other exception (divide by zero, divide overflow, etc.) quite soon.