1

I have this code written on NASM that takes two arguments when used in c: int* ptr and int val. The purpose is to set the memory that ptr points to to val and then return ptr.

    section .text
       global _mptr
_mptr:
       mov ebx, [esp + 4]
       mov ecx, [esp + 8]
       mov [ebx], ecx
       mov eax, [esp + 4]
       ret

This is the C code:

#include <stdio.h>
extern int* _mptr(int* ptr, int val);
int main(void)
{
    int i = 0;
    int* ptr = &i;
    ptr = _mptr(ptr, 225);
    //I want to set i to 225 using _mptr.
    printf("%d\n", i);
}

I compile the program in this way:

nasm -f elf asmCode.asm

gcc -Wall -m32 program.c asmCode.o

on Ubuntu OS.

When I execute it with ./a.out the program fails.

Which is the right way to access the memory that some C-pointer points to in assembly?

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 3
    `ebx` may be callee-save register. Try using `edx` instead. – MikeCAT Apr 28 '21 at 15:03
  • 1
    @mediocrevegetable1: They're not wanting to modify the pointer, they want to modify the pointed-to memory. i.e. `*ptr = val;` – Peter Cordes Apr 28 '21 at 15:18
  • @MikeCAT: Or better, use EAX, since you already want the pointer in EAX as the return value anyway. It's pointless to load it twice, and `[eax]` is a valid addressing mode. (Unlike `[ax]` - 32-bit addressing modes let you use any register.) And yeah, by default GCC is probably making a PIE, and in 32-bit mode that probably means it depends on EBX surviving a function call. Compiler output for a function that did `*ptr = val;` would create working asm, so a good first step would have been comparing known-good asm with the attempt. – Peter Cordes Apr 28 '21 at 15:20
  • If you want to ask a debugging question like this on SO, make sure to include debugging info in your [mcve], like what exactly happens, and assuming it is a segfault, *which* instruction faults. Any debugger can tell you this, like GDB or LLDB. In this case it's fairly easy to guess that violating the calling convention was probably the problem, but without showing where / how it crashed we can't be sure, and it's more work for people that want to answer. – Peter Cordes Apr 28 '21 at 15:26

0 Answers0