Execute a program: GOEXEC

Both user interfaces of course allow to start a user program.

On the keyboard the GO key is used to start the program (line 138, via a JMP to GOEXEC)

0678   1CA4 C9 13               CMP   #$13       ; RUN
0679   1CA6 F0 31               BEQ   GOV

0711   1CD9 4C C8 1D    GOV     JMP   GOEXEC  

The TTY CLI the G command handler at line 292 calls GOEXEC.

0864   1DEF C9 47               CMP   #'G'       ; GO EXEC
0865   1DF1 F0 D5               BEQ   GOEXEC

GOEXEC itself

0072   00EF             PCL     .BLOCK  1          ; PROGRAM CNT LOW
0073   00F0             PCH     .BLOCK  1          ; PROGRAM CNT HI
0074   00F1             PREG    .BLOCK  1          ; CURRENT STATUS REG
0075   00F2             SPUSER  .BLOCK  1          ; CURRENT STACK POINTER
0076   00F3             ACC     .BLOCK  1          ; ACCUMULATOR
0077   00F4             YREG    .BLOCK  1          ; Y INDEX
0078   00F5             XREG    .BLOCK  1          ; X INDEX

0841   1DC8 A6 F2       GOEXEC  LDX   SPUSER    
0842   1DCA 9A                  TXS   
0843   1DCB A5 FB               LDA   POINTH       ; PROGRAM RUNS FROM
0844   1DCD 48                  PHA                ; OPEN CELL ADDRESS
0845   1DCE A5 FA               LDA   POINTL
0846   1DD0 48                  PHA   
0847   1DD1 A5 F1               LDA   PREG
0848   1DD3 48                  PHA   
0849   1DD4 A6 F5               LDX   XREG         ; RESTORE REGS
0850   1DD6 A4 F4               LDY   YREG
0851   1DD8 A5 F3               LDA   ACC
0852   1DDA 40                  RTI    

What is happening here?

Note that GOEXEC is essentially build for SST operation! That is why all those registers are loaded from zeropage, where they were stored by the SAVE interrupt handler.

Program counter, Stack pointer SP, Process register PS, X, Y, ACC are initialized from the zeropage locations and the RTI transfers the CPU execution.
The RTI (return from Interrupt) restores all registers from the stack, including the Program counter.
So the user program starts at the current selected address (in POINTL, POINTH).

While this way of starting a program has the advantage that the program may start with user supplied values for the CPU registers, there is no guarantee that these zeropage locations contain meaningfull values. In fact, after a RESET the contents of RAM and therefore these start values are random. That can create a malfunction program if it does not itself initialize registers.
And not all do, like Microsoft Basic: the decimal flag is not cleared via CLD. And the program crashes if by chance the CPU is in decimal mode.

So before using the G command it is good practice to clear location 00F1, the Processor Status register to clear the decimal flag and 00F2, the stack pointer to FF.
A well behaving program should initialize stack and do a CLD just to be sure.

Returning to the KIM monitor can be done with a JMP START (1C4F).