【问题标题】:Self-Modifying MIPS Code自修改 MIPS 代码
【发布时间】:2015-05-29 12:30:02
【问题描述】:

我正在尝试在 MIPS 中编写一个程序,它不断提示输入两个整数并打印总和,直到总和为 0。诀窍是,如果总和为 13,我需要调用一个方法来更改组装的 MIPS代码以便

add $t2, $t0, $t1

变成

and $t2, $t0, $t1

循环的所有后续运行都使用 and 指令。

我有求和循环工作,因此当总和为 13 时,调用方法 instMod,我想修改指令。不幸的是,我不知道从哪里开始,也找不到任何在线示例。我假设我需要以某种方式从汇编代码中获取 add 的十六进制代码,并将其替换为 and 的十六进制代码,但我不知道该怎么做,或者这是否是正确的做法。

# 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

【问题讨论】:

    标签: mips self-modifying


    【解决方案1】:

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

    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的位置。

    指令的“来源”标记在指令到替换中。

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

    【讨论】:

      【解决方案2】:

      试试这个:

      1. 将您需要的指令组装到目标文件中
      2. 提取等效机器码的十六进制
      3. 在需要更改的代码前放置标签
      4. mov 将第 2 步中的十六进制转换为 instMod 部分中第 3 步中的位置

      为此,带有操作数的两条指令必须具有相同的长度。如果不是,请酌情用nop 填充原件或替换件。

      【讨论】:

      • MIPS 是 RISC 架构,所以所有指令都是 4 个字节长。
      • 我认为这是最好的策略,问题是我如何以编程方式从第 3 步中提取位置
      • 汇编代码并检查编译代码中该指令的偏移量是多少... objdump -d
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-06
      • 2013-06-29
      • 2023-04-05
      • 2013-10-12
      • 2012-02-01
      • 2012-05-06
      相关资源
      最近更新 更多