Segmentation fault protection: Difference between revisions

Line 22:
 
It's very unlikely that you'll index an array out of bounds, however, as you can only index up to 255 bytes forward from the base address. What's more likely to happen is forgetting to pop all registers you pushed before returning from a subroutine, and the program counter getting loaded with some unknown value and executing from there. Again, the 6502 won't stop you from trying to execute RAM or memory-mapped ports, and there's no guarantee what will happen (most bytes with a low nibble of 2 will crash the CPU if it tries to execute them.)
 
=={{header|68000 Assembly}}==
The closest thing the 68000 has to a segfault is an "alignment fault." <code>MOVE.W (An),Dn</code> or <code>MOVE.W (An),Dn</code> where <code>An</code> is any address register that contains an odd value will crash the CPU. More specifically, it will trigger one of the CPU's traps, forcing the program counter to jump to an error handler that is looked up from the trap table in low memory (on some machines such as the NEOGEO this just reboots the CPU. Note that byte-length commands are not subject to this aligment rule, which can lead to problems when working with structs that contain mixed data types. The programmer can avoid this very easily by either padding all their data to word length, use of the <code>EVEN</code> assembler directive after a sequence of byte-length data, or carefully arranging structs/unions as follows:
 
<lang 68000devpac>;as long as you arrange your structs so that byte-length data is in pairs you can avoid alignment problems
myStruct:
dc.b $20
dc.b $40
dc.w $2222
dc.b $60
dc.b $80
dc.l $55555555
 
LEA myStruct,A0
MOVE.B (A0)+,D0
MOVE.B (A0)+,D1
MOVE.W (A0)+,D2
MOVE.B (A0)+,D3
MOVE.B (A0)+,D4
MOVE.L (A0)+,D5 ;none of these MOVE commands will cause an alignment fault.</lang>
 
As for executing RAM, or writing to code areas, there is no protection for either on the 68000. Failing to "balance" the stack will likely cause the alignment problem mentioned earlier, as the program counter needs to be even-aligned as well as any address registers you use.
 
(Note: Simply having an odd number stored in an address register will not crash the CPU by itself. As long as you never attempt to dereference the address register's value, no crash will occur. Otherwise you'd never be able to load byte data! As mentioned before, dereferencing an odd memory address is fine if you use a <code>.B</code> instruction to do so.
 
=={{header|Phix}}==
1,489

edits