From e4e3dbf756933141f5991fbecaed43212f57d8d8 Mon Sep 17 00:00:00 2001
From: Christian Groessler <chris@groessler.org>
Date: Wed, 12 Sep 2018 01:05:52 +0200
Subject: [PATCH] atarixl: check at startup whether RAM beneath the ROM is in
 use

If detected, the program refuses to run, preventing a crash.
The check only works with SpartaDOS. I don't have an overview which
DOSes potentially use the RAM under the ROM. Or which other installed
programs might use it.

No additional runtime memory space is consumed, since the change
is in the "system check" load chunk which gets replaced by the
user program during loading.
---
 libsrc/atari/system_check.s | 33 +++++++++++++++++++++++++++++++--
 1 file changed, 31 insertions(+), 2 deletions(-)

diff --git a/libsrc/atari/system_check.s b/libsrc/atari/system_check.s
index 2f1feefc4..df55f3d13 100644
--- a/libsrc/atari/system_check.s
+++ b/libsrc/atari/system_check.s
@@ -68,8 +68,32 @@ cont:   ldx     #0              ; channel 0
 
 .segment        "SYSCHK"
 
+        rts     ; for older DOSes which unconditionally run the first load chunk
+
 .ifdef __ATARIXL__
 
+; check for SpartaDOS and its usage of RAM below ROM
+; return CF 0/1 for bad/ok
+sdcheck:lda     DOS
+        cmp     #'S'
+        bne     sdcrts0         ; not SpartaDOS, assume RAM is not used
+        lda     DOS+1           ; SD version
+        cmp     #$40            ; SD-X has $40 or higher
+        bcc     sdcrts1         ; older versions (except maybe 1.x) always use the RAM under the ROM
+        ldy     #31             ; offset for OSRMFLG
+        lda     (DOSVEC),y      ; get OSRMFLG
+        bne     sdcrts1
+        
+sdcrts0:clc
+        rts
+sdcrts1:sec
+        rts
+
+ramrom_txt:
+        .byte   "Memory under ROM is in use.", ATEOL
+        .byte   "Cannot run this program.", ATEOL
+ramrom_txt_len = * - ramrom_txt
+
 lmemerrxl_txt:
         .byte   "Not enough memory to move screen", ATEOL
         .byte   "memory to low memory. Consider using", ATEOL
@@ -94,8 +118,13 @@ syschk: lda     $fcd8           ; from ostype.s
 
         jmp     mem_err
 
-sys_ok:
-        .include "xlmemchk.inc"         ; calculate lowest address we will use when we move the screen buffer down
+sys_ok: jsr     sdcheck         ; check for SpartaDOS-X, and if found, whether it uses the RAM under the ROM
+        bcc     sd_ok
+
+        print_string2 ramrom_txt, ramrom_txt_len
+        jmp     fail
+
+sd_ok:  .include "xlmemchk.inc" ; calculate lowest address we will use when we move the screen buffer down
 
         lda     MEMLO
         cmp     lowadr