功能端的ARM ASM段故障

时间:2019-04-26 06:44:56

标签: assembly segmentation-fault arm

我有以下ARM汇编代码。目的是逐字符打印出十六进制的32位整数。该汇编函数的函数原型为printx(int, int),其中第一个int是要打印的整数,第二个标志用于指定应以大写还是小写十六进制打印。当我尝试通过比较printf输出和代码输出来自己调试代码时,就使用了数据变量。

.data

derp: .asciz "\nDerp\n"
hex: .asciz "HEX %x\n"
dec: .asciz "\nDEC %d\n"
count: .asciz "\nCOUNT %d\n"

.text

.global printx

printx:
    push {fp, lr}
    mov fp, sp

    mov r11, #1         // firstloop counter "i"
firstloop:              // loop to extract hex character
    cmp r11, #1         // if i == 1
    beq endsecond       // jump to end of loop (no shift necessary)
    lsr r0, r0, #4      // logical shift right 4 bits
endsecond:
    and r4, r0, #0xf    // gets first 4 bits
    cmp r4, #9          // is it greater than 9?
    bgt alpha           // jump to alpha
    add r4, r4, #48     // add 48 to get ascii for number
    b beta              // jump to beta
alpha:
    cmp r1, #1          // if uppercase flag is set
    beq upper           // jump to upper
    add r4, r4, #87     // add 87 to get ascii for lowercase letters
    b beta              // jump to beta
upper:
    add r4, r4, #55     // add 55 to get ascii for uppercase letters
beta:
    push {r4}           // push ascii character onto stack
    cmp r11, #8         // if i == 8
    beq popping         // branch to popping
    add r11, #1         // i++
    b firstloop         // branch to firstloop
popping:
    mov r10, #1          // let r9 indicate leading (1 is true)
poploop:
    pop {r0}            // pop into r5
    cmp r0, #0          // if r5 != 0
    bne nonzero         // branch to nonzero
    cmp r10, #1          // if r10 == 1 (if leading)
    beq counter         // branch to counter
    b print             // branch to print
nonzero:
    mov r10, #0          // set leading (r10) to false (0)
print:
    bl putchar          // call putchar
counter:
    sub r11, #1         // i--
    cmp r11, #0         // if i != 0
    bne poploop         // branch to poploop
    ldr r0, =derp
    bl printf

    mov sp, fp
    pop {fp, pc}
.end

运行gdb时,我得到以下信息:

Program received signal SIGSEGV, Segmentation fault.
counter () at printinteger.s:62
62      pop {fp, pc}

我已经反复检查过,我弹出的次数与推入堆栈的次数完全相同,因此我认为这可能与我如何弹出帧指针和程序计数器有关。在gdb上,或者我将堆栈指针移到了错误的位置。诊断问题的任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:4)

您破坏了呼叫者的sp,因为fpr11是同义词,因此您的mov r11, #1覆盖了fp,并将此垃圾复制到{ {1}}会在您的函数结尾处显示。