段故障(核心哑)x86汇编AT& T语法

时间:2017-02-13 04:51:34

标签: assembly x86 gnu

我尝试编写一个代码,该代码需要3个数组,并返回最后一个数组中的最大数字(是的,就像在ProgramminGroundUp一书中那样)但我希望函数根据数组大小退出,而不是在它到达时元素零 但代码给了我

Segment fault (Core Dumped)

我用'作为'汇编'和gnu loader' ld' 这是完整的代码

.section .data
first_data_items:
.long 48,65,49,25,36
second_data_items:
.long 123,15,48,67,25,69
third_data_items:
.long 102,120,156,32,14,78,100
.section .text
.globl _start
_start:
pushl $first_data_items
pushl $5
call max  
addl $8, %esp
pushl $second_data_items
pushl $6
call max
addl $8, %esp 
pushl $third_data_items
pushl $7
call max
addl $8, %esp
movl %eax, %ebx
movl $1, %eax
int $0x80

.type max, @function
max:
pushl %ebp
movl %esp, %ebp
movl 8(%ebp), %ecx   #ecx will be the size of the array
movl 12(%ebp), %ebx  #ebx will be the base pointer
movl $0, %edi         #edi will be the index
movl 0(%ebx, %edi, 4), %eax   #eax will hold the maximum number
start_loop:
cmpl $0, %ecx
je end_loop
incl %edi
movl 0(%ebx, %edi,4), %esi     #esi will hold the current element
cmpl %eax, %esi
jle start_loop
movl %esi, %eax
decl %ecx
jmp start_loop 
end_loop:
movl %ebp, %esp
popl %ebp
ret

2 个答案:

答案 0 :(得分:0)

我已经在比较statemnt之后移动了decl %ecx(感谢Michael Petch),以便在每个循环中使ecx减1 所以代码将是

.section .data
first_data_items:
.long 48,65,49,25,36
second_data_items:
.long 123,15,48,67,25,69
third_data_items:
.long 102,120,156,32,14,170,100
.section .text
.globl _start
_start:
pushl $first_data_items
pushl $5
call max
addl $8, %esp
pushl $second_data_items
pushl $6
call max
addl $8, %esp
pushl $third_data_items
pushl $7
call max
addl $8, %esp
movl %eax, %ebx
movl $1, %eax
int $0x80
.type max, @function
max:
pushl %ebp
movl %esp, %ebp
movl 8(%ebp), %ecx   #ecx will be the size of the array
movl 12(%ebp), %ebx  #ebx will be the base pointer
movl $0, %edi         #edi will be the index
movl 0(%ebx, %edi, 4), %eax   #eax will hold the maximum number
start_loop:
cmpl $0, %ecx
je end_loop
decl %ecx
incl %edi
movl 0(%ebx, %edi,4), %esi         #esi will hold the current element
cmpl %eax, %esi
jle start_loop
movl %esi, %eax
jmp start_loop
end_loop:
movl %ebp, %esp
popl %ebp
ret

答案 1 :(得分:0)

关于我对lodsd用法的评论,max函数的示例:

.type max, @function
max:
    pushl   %ebp
    movl    %esp, %ebp
    movl    8(%ebp), %ecx       # ecx will be the size of the array
    movl    12(%ebp), %esi      # esi will be the base pointer
    popl    %ebp                # stack_frame usage complete, restore ebp
    lea     (%esi,%ecx,4), %ecx # ecx = (base pointer + 4*size) (end() ptr)
    mov     $0x80000000,%edi    # current max = INT_MIN
start_loop:
    cmp     %ecx, %esi
    jae     end_loop            # end() ptr reached (esi >= ecx)
    lodsl                       # eax = [esi+=4]
    cmp     %edi, %eax          # check if it is new max
    cmovg   %eax, %edi          # update max as needed (eax > edi)
    jmp     start_loop          # go through whole array
end_loop:
    mov     %edi, %eax          # eax = current_max
    ret

CMOVcc需要i686 +目标架构)