Assembly Language for Beginners

(Jeff_L) #1

1.11 More about results returning


There are two different addition instructions in MIPS:ADDandADDU. The difference between them is not
related to signedness, but to exceptions. ADDcan raise an exception on overflow, which is sometimes
useful^86 and supported in AdaPL, for instance.ADDUdoes not raise exceptions on overflow.


Since C/C++ does not support this, in our example we seeADDUinstead ofADD.


The 32-bit result is left in $V0.


There is a new instruction for us inmain():JAL(“Jump and Link”).


The difference betweenJALandJALRis that a relative offset is encoded in the first instruction, whileJALR
jumps to the absolute address stored in a register (“Jump and Link Register”).


Bothf()andmain()functions are located in the same object file, so the relative address off()is known
and fixed.


1.11 More about results returning


In x86, the result of function execution is usually returned^87 in theEAXregister. If it is byte type or a
character (char), then the lowest part of registerEAX(AL) is used. If a function returns afloatnumber, the
FPU registerST(0)is used instead. In ARM, the result is usually returned in theR0register.


1.11.1 Attempt to use the result of a function returningvoid


So, what if themain()function return value was declared of typevoidand notint? The so-called startup-
code is callingmain()roughly as follows:


push envp
push argv
push argc
call main
push eax
call exit


In other words:


exit(main(argc,argv,envp));


If you declaremain()asvoid, nothing is to be returned explicitly (using thereturnstatement), then
something random, that has been stored in theEAXregister at the end ofmain()becomes the sole
argumentoftheexit()function. Mostlikely, therewillbearandomvalue, leftfromyourfunctionexecution,
so the exit code of program is pseudorandom.


We can illustrate this fact. Please note that here themain()function has avoidreturn type:


#include <stdio.h>


void main()
{
printf ("Hello, world!\n");
};


Let’s compile it in Linux.


GCC 4.8.1 replacedprintf()withputs()(we have seen this before:1.5.4 on page 21), but that’s OK,
sinceputs()returns the number of characters printed out, just likeprintf(). Please notice thatEAXis
not zeroed beforemain()’s end.


This implies that the value ofEAXat the end ofmain()contains whatputs()has left there.


Listing 1.96: GCC 4.8.1

.LC0:
.string "Hello, world!"
main:


(^86) http://go.yurichev.com/17326
(^87) See also: MSDN: Return Values (C++):MSDN

Free download pdf