0

This is the simple factorial program.

.global main

main:
        mov     r0,#7       // insert here the number to calculate the factorial, e.g. 7
        mov     r1,r0       // it will be useful after
        push    {ip,lr} // save the lr
        bl      factorial   // jump to factorial label
        pop     {ip,lr} // reset the lr so the program can return
        bx      lr

factorial:
        cmp     r1,#1       // if r1=1
        moveq   pc,lr       // then return
        sub     r1,r1,#1    // else r1 = r1-1
        mul     r0,r1,r0    // and multiply r0*r1
        b       factorial   // then do it again until moveq return to main

If I execute it I receive wrongs results (very lower):

$ ./a.out 
$ echo $?
176

176 instead of 5040.. There must be some logic error, could you help me?

Mnkisd
  • 504
  • 2
  • 12

1 Answers1

3

5040 & 0xff = 176 -- the exit code of a program is only 8 bits

https://en.wikipedia.org/wiki/Exit_status#POSIX <- there are ways to retrieve the whole number, but $? will give you only the least significant byte.

Of these, the waitid() [7] call retrieves the full 32-bit exit status, but the older wait() and waitpid() [8] calls retrieve only the least significant 8 bits of the exit status.

  • how to use waitd() ? – Mnkisd Sep 08 '20 at 16:53
  • you would have to make a C program like https://www.geeksforgeeks.org/difference-fork-exec/ - in the child branch execv() your assembly binary, in the other branch replace the waitpid() call with waitid() with appropriate arguments –  Sep 08 '20 at 17:55
  • or if you prefer a python launcher... https://www.geeksforgeeks.org/python-os-waitid-method/ –  Sep 08 '20 at 17:56