In: Computer Science
This problem is adapted from an earlier edition of P&H.
Consider the following code used to implement the instruction: foo $s0,$s1,$s2
mask: .word 0xFFFFF83F
start: la $t0,mask
lw $t0,0($t0)
la $s0,shftr
lw $s0,0($s0)
and $s0,$s0,$t0
andi $s2,$s2,0x1f
sll $s2,$s2,6
or $s0,$s0,$s2
la $t5,shftr
sw $s0,0($t5)
shftr: sll $s0,$s1,0
Add meaningful comments to the code. Please explain each line and write a paragraph describing how it works. Why do you suppose that writing “self-modifying code” such as this is a bad idea (and often times not actually allowed)?
Please explain it. thank you.
Note: We have not covered the .word directive yet. This is an assembler directive, which is essentially an instruction to the assembler (NOT an assembly language instruction). In this case, it tells the assembler to reserve a word of memory initialized to 0xfffff83f. Mask is the address of this word (just as start is the address of the word in memory containing the machine code for that lw instruction).
Answer:
mask: .word 0xFFFFF83F
start: la $t0,mask //$t0 = 0xfffff83f, 1111111...100000111111 ( meaning word is loaded to register t0 )
lw $t0,0($t0) //load word at RAM address ($t0+0) into register $t0
la $s0,shftr //$s0 = sll instruction( shifting to left) means loading the shift instruction.
lw $s0,0($s0) // clear the shamt
and $s0,$s0,$t0 //clears the shamt field in the sll instruction stored in $s0
andi $s2,$s2,0x1f //clear all but the last 5 bits in $s2
sll $s2,$s2,6 //move those bits to the position that corresponds to shamt
or $s0,$s0,$s2 //set the shamt field in $s0 as the value from $s2
la $t5,shftr // load all sll instruction in register t5
sw $s0,0($t5) //store the sll instruction back into memory
shftr: sll $s0,$s1,0 //shifts the contents of $s0 left 0 which is stored in $s0. perform the modified instr.
The last shift instruction is modified so that its shamt field is written by the 5 LSBs from $s2. It's actually modifying the instruction in-memory to perform the shift.
self modifying means we are changing code generated by the compiler which will make our code machine dependent.because of this it is bad idea as it complicates the instruction cache implementation, the instruction cache is usually read only cache. Also it makes detecting defects that overwrite code harder to detect.