0

Hello I am very new to writing assembly and have a question regarding my attempt at writing a recursive function to compute the factorial of n.

Here is my attempt at writing the factorial function:

            .global main

main:
    MOV r1, #3

fact:
    SUB sp, sp, #8      
    STR lr, [sp, #0]    
    STR r1, [sp,#4]     

    CMP r1, #1          
    BGT Else            


    ADD sp, sp, #8      

    MOV pc, lr 

Else: 
    SUB r1, r1, #1      
    BL fact             
    MOV r2, r1
    LDR r1, [sp, #4]    
    LDR lr, [sp, #0]    
    ADD sp, sp, #8      
    MUL r1, r2, r1      
    MOV pc, lr 

    MOV r0, #1
    SWI 0x6b        
    SWI 0x11        

The issue is this: i successfully can compute that 3 factorial is 6 and it gets stored in r1 at the end of the program; however, I can never get passed the last "MOV pc, lr" statement in the third execution of the loop and I cannot understand the logic behind why.

When I get to the third loop of MOV pc, lr I get an error stating: "PC out of valid memory range" but I am not sure why this is the case. Any pointers in the right direction would be greatly appreciated because I am an absolute beginner and cannot understand why this error is occurring. Thank you for your time!

Biggytiny
  • 519
  • 10
  • 29
  • What environment are you running this under? Are you sure you can return from `main`? – Jester Apr 11 '17 at 23:26
  • @Jester I am running this on Arm Sim sorry should have mentioned that. I am not really sure what you're asking to be honest, could you elaborate? – Biggytiny Apr 12 '17 at 00:13
  • Whether `lr` is valid at the start - under some environments you have to use an exit syscall and can't just return. PS: you know your last 3 lines are never reached, right? – Jester Apr 12 '17 at 00:26
  • @Jester yes I know that the last three lines aren't reached, the program halts with the error after the third MOV pc, lr execution. I am pretty sure that lr is valid at the start, in ARM Sim i can walk through each individual step up until the point at which the MOV pc, lr is called for the third time. Do you have any idea why? Sorry if I am not really interpreting your questions right, I truly am an absolute beginner here and don't fully comprehend exactly what you're asking. – Biggytiny Apr 12 '17 at 01:24
  • If you put `MOV pc, lr` right after `main:` (first instruction of code to execute), does it work as expected? (clean exit of program, doing nothing else) That's what Jester is asking. – Ped7g Apr 12 '17 at 14:45

0 Answers0