0

The reduce function which I want to write in x68-64 may have this functionality:

unsigned reduce( unsigned (*fnct_ptr) (unsigned param_one, unsigned param_two),
                    unsigned init,
                    size_t len,
                    const unsigned arr[]){
    for (int i = 0; i < len; i++) {
            init = fnct_ptr(init, arr[i]);
    }
    return init;
}

The higher-order function takes a pointer to a two parameter function, an initial value, an array and a counter for its length.

My current attempt looks as follows:

reduce:   

    XOR rbx, rbx    ; set counter to zero
    MOV rsp, rdi    ; fnctPntr -> rsp  
    MOV rax, rsi    ; init -> rax  
    
while:
    CMP rbx, rdx    ; if counter >= lengrh -> end 
    JGE  end
        
        MOV  rdi, rax          ; load parameters to rdi and rsi
        MOV  rsi, [rcx+rbx*8]  
        CALL rsp               ; call function with pointer 
        INC  rbx
        JMP  while
end:        
    RET    

The higher order function and the function as parameter may follow the calling convention So the parameters have to be put into rdi and rsi before every call of the function and receive the result in rax. I'm getting segmentation faults at the call if the function. Probably because of a wrong address size, since the value is 32-Bit but dealing with 64-Bit Register.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
HeapUnderStop
  • 378
  • 1
  • 9
  • 1
    `rsp` is the stack pointer! Don't overwrite it with data. `call` pushes are return address to `[rsp-=8]`. Also, RBX is call-preserved, that's why you can use it as a loop counter that will survive across calls. But you aren't saving/restoring your caller's value of it. Also, RCX and RDX are call-clobbered, so you'll need different registers for those in your loop. – Peter Cordes May 13 '23 at 03:48
  • Look at compiler-generated asm for your C function for an example of how to get this right, including stack alignment which will happen for free with pushing an odd number of call-preserved registers. [How to remove "noise" from GCC/clang assembly output?](https://stackoverflow.com/q/38552116) – Peter Cordes May 13 '23 at 03:51

0 Answers0