From 5fe7a7fbb2b364e9e21552c2f0f9038c8ce7fb07 Mon Sep 17 00:00:00 2001
From: rswindell <>
Date: Thu, 26 Oct 2017 20:39:00 +0000
Subject: [PATCH] Added range checks when initializing textinfo.screenwidth and
 screeheight (don't wrap around if value is > 255) - presumably these textinfo
 struct members were left as unsigned chars (8-bits) to preserve compatiblity
 with legacy conio apps, but I'm not sure. Perhaps we could increase these to
 at least 16-bit integers or bigger in the future, in which case these range
 checks would need to be removed or replaced.

---
 src/conio/bitmap_con.c | 13 +++++++++++--
 src/conio/win32cio.c   | 15 ++++++++++++---
 2 files changed, 23 insertions(+), 5 deletions(-)

diff --git a/src/conio/bitmap_con.c b/src/conio/bitmap_con.c
index 5554e29c68..41fc86d600 100644
--- a/src/conio/bitmap_con.c
+++ b/src/conio/bitmap_con.c
@@ -184,8 +184,17 @@ int bitmap_init_mode(int mode, int *width, int *height)
 	cio_textinfo.attribute=7;
 	cio_textinfo.normattr=7;
 	cio_textinfo.currmode=mode;
-	cio_textinfo.screenheight=vstat.rows;
-	cio_textinfo.screenwidth=vstat.cols;
+
+	if (vstat.rows > 0xff)
+		cio_textinfo.screenheight = 0xff;
+	else
+		cio_textinfo.screenheight = vstat.rows;
+
+	if (vstat.cols > 0xff)
+		cio_textinfo.screenwidth = 0xff;
+	else
+		cio_textinfo.screenwidth = vstat.cols;
+
 	cio_textinfo.curx=1;
 	cio_textinfo.cury=1;
 	cio_textinfo.winleft=1;
diff --git a/src/conio/win32cio.c b/src/conio/win32cio.c
index 6db868aba8..052faf51bd 100644
--- a/src/conio/win32cio.c
+++ b/src/conio/win32cio.c
@@ -548,8 +548,17 @@ int win32_initciolib(long inmode)
 	}
 	else {
 		/* Switch to closest mode to current screen size */
-		cio_textinfo.screenwidth=sbuff.srWindow.Right-sbuff.srWindow.Left+1;
-		cio_textinfo.screenheight=sbuff.srWindow.Bottom-sbuff.srWindow.Top+1;
+		unsigned screenwidth = sbuff.srWindow.Right - sbuff.srWindow.Left + 1;
+		unsigned screenheight = sbuff.srWindow.Bottom - sbuff.srWindow.Top + 1;
+		if (screenwidth > 0xff)
+			cio_textinfo.screenwidth = 0xff;
+		else
+			cio_textinfo.screenwidth = screenwidth;
+		if (screenheight > 0xff)
+			cio_textinfo.screenheight = 0xff;
+		else
+			cio_textinfo.screenheight = screenheight;
+
 		if(cio_textinfo.screenwidth>=132) {
 			if(cio_textinfo.screenheight<25)
 				win32_textmode(VESA_132X21);
@@ -644,7 +653,7 @@ void win32_textmode(int mode)
 	if ((h=GetStdHandle(STD_OUTPUT_HANDLE)) == INVALID_HANDLE_VALUE)
 		return;
 	if (!SetConsoleScreenBufferSize(h,sz))
-		return;
+		return;	// Note: This fails and returns here with large windows (e.g. width > 255)
 	if (!SetConsoleWindowInfo(h,TRUE,&rc))
 		return;
 	sz.X=vparams[modeidx].cols;
-- 
GitLab