Exercise 3: Safeguarding R7 Around a TRAP Call Inside a Subroutine — Possible Solution ==================================================================== THE SAFEGUARD NEEDED ------------------------------ The subroutine needs to PUSH R7 onto the stack immediately after it's entered (before the TRAP x22 call), and POP it back before its own RET — exactly the same push-before-call, pop-before-return pattern assembly1-7 established for a nested JSR call. WHY IT'S NEEDED ------------------------------ Per this chapter's own tip-box, "TRAP inherits JSR's own R7 rules" -- TRAP saves a return address into R7 exactly the way JSR does. The subroutine in question was itself entered via a JSR, which already placed ITS OWN return address (pointing back to whoever called it) into R7. If that subroutine then executes TRAP x22 without saving R7 first, the TRAP instruction will overwrite R7 with the trap routine's own return address, permanently destroying the subroutine's original return address -- the exact same failure mode assembly1-7's own A-calls-B-calls-C example demonstrated, just triggered by a TRAP call instead of a second JSR. THE CORRECTED SUBROUTINE SHAPE ------------------------------ MYSUB ADD R6, R6, #-1 STR R7, R6, #0 ; save the original return address first LEA R0, MSG TRAP x22 ; safe now — R7 is preserved on the stack LDR R7, R6, #0 ; restore the original return address ADD R6, R6, #1 RET ; now correctly returns to the real caller Without this save/restore pair, RET would jump to wherever PUTS's own internal TRAP call last left R7 pointing, not back to whoever originally called MYSUB -- the program would appear to work (PUTS still prints the message correctly) right up until the RET sends execution somewhere unintended, exactly the "symptom shows up far from the actual mistake" pattern assembly1-7's own warn-box described. WHY THIS WORKS AS AN ANSWER ------------------------------ It identifies the exact safeguard (push/pop R7 around the TRAP call), explains why it's needed by connecting TRAP's R7-saving behavior (stated in this chapter's tip-box) back to assembly1-7's own nested- call failure mode, and shows the corrected subroutine in full rather than describing the fix only in the abstract.