0

Using the GNU Assembler I'm trying to call malloc to create a C struct, insert values into that struct and return a pointer to that struct. Below is the struct:

struct node {
    void     *next;     
    void     *last; 
    char     *name;     
    int      id;        
    uint8_t  number;
    uint8_t  numberTwo;
    uint8_t  numberThree;
    uint8_t  numberFour;
}

Below is the GNU Assembly that I'm using:

    push %ebp
    movl %esp, %ebp
    subl $0x1c, %esp
    #movl $20, (%esp)   #I've tried this but it doesn't seem to help
    push $20            #Struct is 20 bytes
    call malloc     
    test %eax, %eax
    jz allocateFailed
    jmp allocateOK

allocateFailed:
    leave
    ret

allocateOK:
    movl 8(%ebp), %edx
    movl %edx, 8(%eax)
    movl 12(%ebp), %edx
    movl %edx, 12(%eax)
    leave
    ret

I've updated the code to stay away from using the %ebx register and taking a look at an Objdump of the function that is how the assembler handled this.

I'm getting the parameters fine but when I try to put them in the newly created struct I get a seg fault. Below is the core dump.

Program terminated with signal 6, Aborted.
0 0xb7727424 in __kernel_vsyscall ()

Below is what I get what I run a backtrace in gdb:

0  allocateOK () at new_student.s:25
1  0x00000014 in ?? ()      #Not sure what this is coming from
2  0xb7fc5a20 in ?? () from /lib/i386-linux-gnu/libc.so.6
3  0x080485ed in test ()    #function that calls and passes in the parameters
4  0x080487b4 in main ()

I've also written this function in C and compiled with the --gstabs and -o and used objdump to get a look at it. I seems to be pretty close to mine but I just can't seem to figure it out.

sub    $0x1c,%esp
movl   $0x14,(%esp)
call   8048350 <malloc@plt>
mov    0x20(%esp),%edx
mov    %edx,0xc(%eax)
mov    0x24(%esp),%edx
mov    %edx,0x8(%eax)

Any help is greatly appreciated. I've never used assembly (only C) to create and work with structs. I've done some research and have been trying a few things but I just seem to get it.

User4679
  • 111
  • 3
  • 12

1 Answers1

0

Best guess: since you're using %ebx without saving and restoring it, you're corrupting something that the caller had in it, causing problems after your routine returns. Also, you're only setting the name and id fields of your newly allocated struct; the rest will contain uninitialized garbage. Use a debugger to get a stack trace of where the abort occurs.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226