From 8b62f515e7e16b0f91241ea1553b13395c7c6556 Mon Sep 17 00:00:00 2001
Message-ID: <8b62f515e7e16b0f91241ea1553b13395c7c6556.1795916095.git.sam@gentoo.org>
In-Reply-To: <416760ff7fc109de2d486baac0a8ad7197ed6824.1795916095.git.sam@gentoo.org>
References: <416760ff7fc109de2d486baac0a8ad7197ed6824.1795916095.git.sam@gentoo.org>
From: Carl Drougge <bearded@longhaired.org>
Date: Wed, 23 Feb 2022 16:23:22 +0200
Subject: [PATCH 3/3] [PATCH] encoding: Replace out of range unicode with
 U+FFFD

Also correct the mask for four byte UTF-8.

bug #62097

Link: https://savannah.gnu.org/bugs/index.php?item_id=68978
(cherry picked from commit 916d0523137b6ce9d56c2ec6a602a3dc471779a4)
---
 encoding.c | 13 +++++++++++--
 1 file changed, 11 insertions(+), 2 deletions(-)

diff --git a/encoding.c b/encoding.c
index b9f210b..d17ddb9 100644
--- a/encoding.c
+++ b/encoding.c
@@ -545,8 +545,13 @@ void AddUtf8(uint32_t c)
 		AddUtf8(combchars[c - 0xd800]->c1);
 		c = combchars[c - 0xd800]->c2;
 	}
+
+	/* replace out of range values with U+FFFD "replacement character" */
+	if (c > 0x10ffff)
+		c = 0xfffd;
+
 	if (c >= 0x10000) {
-		AddChar((c & 0x1fc0000) >> 18 ^ 0xf0);
+		AddChar((c & 0x1c0000) >> 18 ^ 0xf0);
 		c = (c & 0x3ffff) ^ ((0xe0 ^ 0x80) << 12);
 	}
 	if (c >= 0x800) {
@@ -574,9 +579,13 @@ size_t ToUtf8_comb(char *p, uint32_t c)
 size_t ToUtf8(char *p, uint32_t c)
 {
 	int l = 1;
+	/* replace out of range values with U+FFFD "replacement character" */
+	if (c > 0x10ffff)
+		c = 0xfffd;
+
 	if (c >= 0x10000) {
 		if (p)
-			*p++ = (c & 0x1fc0000) >> 18 ^ 0xf0;
+			*p++ = (c & 0x1c0000) >> 18 ^ 0xf0;
 		l++;
 		c = (c & 0x3ffff) ^ ((0xe0 ^ 0x80) << 12);
 	}
-- 
2.56.1

