Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 941
SmRndGuy Avatar asked Sep 04 '12 12:09

SmRndGuy


2 Answers

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 opcode 0x0F is reserved for multibyte instructions. 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 priviledges to do it. In 16-bit real mode (eg. DOS) you can jump and call what ever 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.

like image 177
nrz Avatar answered Nov 18 '22 04:11

nrz


In protected mode and long mode (i.e. not 16-bit mode), segment registers including CS are no longer just an extra 4 bits of address. They index into the table of segment descriptors, with a base + limit (normal base=0 limit=4GiB, i.e. a flat memory model), but also with other attributes.

The code segment descriptor determines the CPU mode (e.g. 32-bit compat mode vs. 64-bit long mode). On a 64-bit kernel, a 64-bit user-space process could make a far jmp to some 32-bit code. This is not useful in practice, and may even break when the OS returns to your process after a context switch.

TODO: dig up a link where someone showed how to do this. I think there was even a recent question about this with a detailed answer about how to even find the right segment numbers.

like image 28
Peter Cordes Avatar answered Nov 18 '22 03:11

Peter Cordes