From 12ae6d550fc14964185a7349953b91888a8f9202 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Deuc=D0=B5?= <shurd@sasktel.net>
Date: Tue, 23 May 2023 15:56:57 -0400
Subject: [PATCH] Fix crash when erasing pop-ups with no startup mode set.

1) In savescreen(), if the vmode is not found, explicitly set
   pixels to NULL rather than leaving it uninitialized.
2) Ensure that currmode is never left as _ORIGMODE (which is not
   a defined mode, so can result in vmode not being found).
---
 src/conio/bitmap_con.c | 2 ++
 src/conio/ciolib.c     | 3 +++
 src/conio/vidmodes.c   | 2 ++
 src/conio/win32cio.c   | 7 +++----
 4 files changed, 10 insertions(+), 4 deletions(-)

diff --git a/src/conio/bitmap_con.c b/src/conio/bitmap_con.c
index 74ce972613..2d1dc95b76 100644
--- a/src/conio/bitmap_con.c
+++ b/src/conio/bitmap_con.c
@@ -1765,6 +1765,8 @@ int bitmap_drv_init_mode(int mode, int *width, int *height, int maxwidth, int ma
 	if(!bitmap_initialized)
 		return(-1);
 
+	if (mode == _ORIGMODE)
+		mode = C80;
 	if(load_vmode(&vstat, mode)) {
 		return(-1);
 	}
diff --git a/src/conio/ciolib.c b/src/conio/ciolib.c
index c5887eec72..1724b8a24a 100644
--- a/src/conio/ciolib.c
+++ b/src/conio/ciolib.c
@@ -1770,6 +1770,9 @@ CIOLIBEXPORT struct ciolib_screen * ciolib_savescreen(void)
 	if (vmode != -1) {
 		ret->pixels = ciolib_getpixels(0, 0, vparams[vmode].xres - 1, vparams[vmode].yres - 1, FALSE);
 	}
+	else {
+		ret->pixels = NULL;
+	}
 	ciolib_vmem_gettext(1, 1, ret->text_info.screenwidth, ret->text_info.screenheight, ret->vmem);
 	ret->fg_colour = ciolib_fg;
 	ret->bg_colour = ciolib_bg;
diff --git a/src/conio/vidmodes.c b/src/conio/vidmodes.c
index 7738fae586..e7d3eb1e4f 100644
--- a/src/conio/vidmodes.c
+++ b/src/conio/vidmodes.c
@@ -286,6 +286,8 @@ int find_vmode(int mode)
 {
     unsigned i;
 
+	if(mode==_ORIGMODE)
+		mode=C80;
 	for (i = 0; i < NUMMODES; i++)
 		if (vparams[i].mode == mode)
 			return i;
diff --git a/src/conio/win32cio.c b/src/conio/win32cio.c
index 66af5578a0..8f7046fdf7 100644
--- a/src/conio/win32cio.c
+++ b/src/conio/win32cio.c
@@ -632,10 +632,9 @@ void win32_textmode(int mode)
 	CONSOLE_SCREEN_BUFFER_INFOEX	bi;
 #endif
 
-	for(i=0;i<NUMMODES;i++) {
-		if(vparams[i].mode==mode)
-			modeidx=i;
-	}
+	modeidx = find_vmode(mode);
+	if (modeidx == -1)
+		modeidx = CO80;
 	sz.X = cio_textinfo.screenwidth > vparams[modeidx].cols ? cio_textinfo.screenwidth : vparams[modeidx].cols;
 	sz.Y = cio_textinfo.screenheight > vparams[modeidx].rows ? cio_textinfo.screenheight : vparams[modeidx].rows;
 	rc.Left=0;
-- 
GitLab