Skip to content
Advertisement

Pass values from C program to Assembly language

I would like to pass values from C program to Assembly using the linked assembly method instead of inline assembly method in C. Below is the Assembly program(GCD) which is am working on.

JavaScript

And this is the C program from with I am trying to pass the values to assembly program

JavaScript

When I compile using the below method and run it. I get either error Floating point exception or an empty prompt waiting for input

JavaScript

I am unable to figure out the error. Kindly help me out. Thank you.

Advertisement

Answer

Passing arguments to gcdasm()

The two int arguments are passed through registers, not the stack. The first and second arguments are passed in the lower-half of rdi and rsi (i.e.: edi and esi), respectively. So, by sign extending edi and esi into rax and rbx respectively, you load the passed arguments into those registers:

JavaScript

However, note that rbx is not a scratch register, therefore the callee needs to save it before modifying it and then restore it back before leaving the gcdasm function.

You can simply replace rbx by rcx (which isn’t a callee-saved register) everywhere in your code. You don’t need rbp at all, so you can remove all the instructions where rbp appears.


Other problems

  • There is also a problem with the logic of the program with:

    JavaScript

    Instead of this, the divisor (rcx) should become the dividend (rax) and the remainder (rdx) should become the divisor (rcx), that is:

    JavaScript
  • When dividing signed values, you have to use the idiv instruction, not div.


Improvement

There are also some reasons regarding performance and code size to use test rdx, rdx instead of cmp rdx, 0 for comparing rdx against zero.


With all that above in mind:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement