Search code examples
assemblyarmbootloaderbare-metal

Why do this assembly program end with a infinite loop?


This program is an example from my textbook,the purpose of this program is to calculate N+N-1+...+2+1 , and store the result in R1. Why it is end with the deadloop block, what can it do?

; asm4-1.s
N          EQU 10 
Stack_Size EQU 0x00000400 
           AREA MyStack, NOINIT, READWRITE, ALIGN=3 
Stack_Mem  SPACE Stack_Size 
__initial_sp
           AREA Reset, DATA, READONLY 
__Vectors DCD __initial_sp 
          DCD Reset_Handler 
          THUMB 
          PRESERVE8 
          AREA Init, CODE, READONLY 
          ENTRY

Reset_Handler
            
          LDR r0, =N 
          MOV r1, #0 

loop
          ADD r1, r0 
          SUBS r0, #1 
          BNE loop 
deadloop
          B deadloop ; Does this create an infinite loop? why is it here
          NOP
          END

Solution

  • That looks like its for an ARM microcontroller.

    On bare metal, there's nothing to exit to, and an empty infinite loop is easier than running more instructions to put the CPU into a sleep state.

    If you let execution keep going, it would try to execute whatever is next in memory as instructions, possibly messing up registers before you can attach a debugger and look at them. Or trigger continuous reboots, which would make it harder to tell from looking at external signal pins that your bootloader actually loaded. (e.g. because the bytes right after your instruction fault, and the fault-handler also runs garbage code somewhere else, orsomething.)

    Or in a less totally trivial bootloader, could end up messing up data in video memory.

    There's also a possibility that running random garbage in memory as instructions could do something bad to the hardware, depending on the board and what software would have to do to damage the hardware. (e.g. configure an I/O pin as an output even though it's already connected to power or ground.)