0

I just learn call assembly code in C code, as below:

caller.c:

#include <stdio.h>
#include <string.h>

void main(void)
{
    char buf[50];
    int a, b, res;
    char *mystr = "calculating...\n";
    char *emsg  = "Error in adding\n";

    a = 5; b = 10;

    mywrite(1, mystr, strlen(mystr));

    if (myadd(a, b, &res))
    {    
        sprintf(buf, "the result is %d\n", res);
        mywrite(1, buf, strlen(buf));
    }   
    else
    {        
        mywrite(1, emsg, strlen(emsg));
    }
} 

callee.s:

.code32

SYSWRITE = 4
.global mywrite, myadd

.text
mywrite:
    pushl %ebp
    movl  %esp, %ebp
    pushl %ebx
    movl  8(%ebp), %ebx
    movl  12(%ebp), %ecx
    movl  16(%ebp), %edx
    movl  $SYSWRITE, %eax
    int   $0x80
    popl   %ebx
    movl  %ebp, %esp
    popl  %ebp
    ret

myadd:
    pushl %ebp
    movl  %esp, %ebp
    movl  8(%ebp), %eax
    movl  12(%ebp), %edx
    xorl  %ecx, %ecx
    addl  %eax, %edx
    jo    1f
    movl  16(%ebp), %eax
    movl  %edx, (%eax)
    incl  %ecx
1:  movl  %ecx, %eax
    movl  %ebp, %esp
    popl  %ebp
    ret

Then I compile:

as -o callee.o callee.s
gcc -o caller caller.c callee.o

But when run caller: ./caller, I got this

Segmentation fault (core dumped)

How to fix it?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
  • 1
    What are `mywrite()` and `myadd()`? Please add their definition. – J...S Sep 29 '17 at 03:36
  • I am surprised the caller.c compiles, given there are no prototypes for mywrite and myadd. Does the first mywrite output anything? Or does it crash before writing anything? Have you tried running it under a debugger? – David Wohlferd Sep 29 '17 at 03:40
  • mywrite() play the role: display the infomation myadd() : add two numbers. – Caesar_lee Sep 29 '17 at 03:44
  • how to use a debugger? i am a junior – Caesar_lee Sep 29 '17 at 03:50
  • 2
    See the bottom of the [x86 tag wiki](https://stackoverflow.com/tags/x86/info) for gdb tips. – Peter Cordes Sep 29 '17 at 04:29
  • Always use `-Wall` option with `gcc` and read [how to debug small programs](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Mathieu Sep 29 '17 at 04:41
  • i just succeed. by removing .code32 in the first line of the assembly code. then use : gcc -m32 -o caller caller.c callee.s to get the caller. it works. – Caesar_lee Sep 29 '17 at 04:43
  • thanks, Peter. i need to learn more about the difference between 32bit and 64bit – Caesar_lee Sep 29 '17 at 04:48

0 Answers0