如何在汇编程序中访问数组的一个elemento

时间:2016-06-08 11:07:23

标签: c arrays ubuntu assembly nasm

我需要你的帮助......实际上,我正在我的学者项目中工作,我正在努力完成它。但我不知道如何在汇编程序中访问一个数组的一个元素。

我的想法是从C调用函数汇编程序并同时传递参数。例如

float* calc(int n, int d, float*data){
    float* result = _mm_malloc(sizeof (float)*n*d, 16);
    calc_x86_asm(n, d, data, result)
    //Line edited, I forget to put the return
    return result; 
}

函数calc_x86_asm在文件的初始声明。

extern calc_x86_asm(int n, int d, float* data, float* result);

我的功能有以下内容:

;External asm function
extern calculate_value
section .text                   ;program
    n      equ         8
    d      equ         12
    data   equ         16
    rta    equ         20 

global calc_x86_asm    ;for linux

calc_x86_asm:
        ;Initialize a stack frame
        push    ebp
        mov     ebp, esp
        pushad
.body:
        ;Load information
        mov     ebx, [ebp+rta]
        ;Initialization counters
        xor     edx, edx
.loop:
        cmp     edx, [ebp+n]            ; if(ecx < n){
        jz      .done                   ; goto .done
                                    ; else
        push    dword [ebp+d]       ; d 
        push    dword [ebp+n]       ; n
        push    dword [edx]        ; current_row
        push    dword [ebp+data]    ; data to evaluate
        call    calculate_value
        add     esp, 16             ; restore stack after to call function.
        mov     [ebx+edx*4], eax    ;<<< Here the problem
        add     edx, 1
        jmp     .loop
.done:
        .done:
        ;Pop registries
        popad
        ;Restore the call's stack frame pointer
        pop     ebp                 ; restore ebp
        ret 

真的,我不知道我是否正在以正确的形式分配数组内存中的值。因为当我运行我的项目时,应用程序会让我错误。顺便说一句,calculate_value是一个C函数。

在C中将采用以下形式:

for(int i=0; i<n; i++){
    result[i] = calc(n, d, i, data);
}

1 个答案:

答案 0 :(得分:0)

您的问题是,在仔细设置寄存​​器后,您正在调用C函数:C函数将绝对覆盖它们。在调用函数之前,需要保存重要的寄存器:

push ebx ; Save for later
push edx ; Save for later

push    dword [ebp+d]       ; d 
push    dword [ebp+n]       ; n
push    dword [edx]        ; current_row
push    dword [ebp+data]    ; data to evaluate
call    calculate_value
add     esp, 16             ; restore stack after to call function.

pop edx ; It's later! (Note reversed restore...)
pop ebx ; It's later!

但这整个

  • 设置注册表;
  • 保存他们
  • 致电C
  • 恢复寄存器
  • 返回更多

首先完全不需要使用程序集:您可能已经用C语言编写了整个内容。