自修改MIPS代码

时间:2015-03-25 17:24:33

标签: mips self-modifying

我试图在MIPS中编写一个程序,它连续提示两个整数并打印总和,直到总和为0.诀窍是如果总和为13,我需要调用一个方法来改变汇编MIPS代码以便

add $t2, $t0, $t1

变为

and $t2, $t0, $t1

并且循环的所有后续运行都使用和指令。

我有求和循环工作,所以当13是调用方法instMod的总和时,我想修改指令。不幸的是,我不知道从哪里开始,无法在网上找到任何这样的例子。我假设我需要以某种方式获取添加了汇编代码的十六进制代码,并将其替换为十六进制代码,但我不知道如何执行此操作或者这是正确的操作过程。< / p>

# Nick Gilbert
# MIPS Program to demonstrate self-modifying code

.data
num1Prompt:     .asciiz     "Enter num1: "
num2Prompt:     .asciiz     "Enter num2: "
num1:           .word       0
num2:           .word       0
addOut:         .asciiz     "ADD: "
andOut:         .asciiz     "AND: "

.text
main:
sumLoop:
    la $a0, num1Prompt  #Asking user for num1
    li $v0, 4       #Call code to print string
    syscall     

    li $v0, 5       #Call code to read an int
    syscall
    move $t0, $v0       #Moving read int to $t1

    la $a0, num2Prompt  #Asking user for num2
    li $v0, 4       #Call code to print string
    syscall

    li $v0, 5       #Call code to read an int
    syscall
    move $t1, $v0       #Moving read int to $t2

    add $t2, $t0, $t1   #Adding num1 and num2 together

    la $a0, addOut
    li $v0, 4
    syscall

    move $a0, $t2
    li $v0, 1
    syscall

    beq $t2, 13, instMod    #Calling method to modify add instruction if sum = 13
    bne $t2, 0, sumLoop #If result is not yet 0, ask for new sum

endSumLoop:
    li $v0, 10
    syscall

instMod: #Method to change add instruction to an and instruction

2 个答案:

答案 0 :(得分:2)

在要替换的指令处添加标签,例如:

instruction_to_be_replaced:
  add $t2, $t0, $t1   #Adding num1 and num2 together

然后在你的例程instMod

instMod: #Method to change add instruction to an and instruction
    lw $t1, instruction_to_replace
    sw $t1, instruction_to_be_replaced
    j sumLoop  # go back to your sumLooop

instruction_to_replace:
    and $t2, $t0, $t1

代码在临时寄存器$t1中加载要替换的指令的内容,然后将其存储在标有instruction_to_be_replaced的位置。

&#34;来源&#34;该指令的内容在instruction_to_replace中标记。

要做到这一点,你需要能够在我认为你有的代码部分写字,否则你不会问这个问题。

答案 1 :(得分:1)

试试这个:

  1. 将您需要的指令汇编到目标文件
  2. 提取等效机器代码的十六进制
  3. 在需要更改的代码前放置一个标签
  4. mov第2步中的十六进制到instMod部分中第3步的位置
  5. 为了使其起作用,带有操作数的两条指令必须具有相同的长度。如果不是,请根据需要使用nop填充原件或替换件。

相关问题