From 7c824682d2028432ee082703ef0ab399867a089b Mon Sep 17 00:00:00 2001
From: Bram Moolenaar <Bram@vim.org>
Date: Sun, 8 May 2022 22:32:58 +0100
Subject: [PATCH] patch 8.2.4919: can add invalid bytes with :spellgood

Problem:    Can add invalid bytes with :spellgood.
Solution:   Check for a valid word string.
---
 src/globals.h                  |  5 +++++
 src/mbyte.c                    |  2 +-
 src/spellfile.c                | 10 ++++++++++
 src/testdir/test_spellfile.vim |  6 ++++++
 4 files changed, 22 insertions(+), 1 deletion(-)

diff --git a/src/globals.h b/src/globals.h
index 7be3bfd..086d04e 100644
--- a/src/globals.h
+++ b/src/globals.h
@@ -1745,3 +1745,8 @@ EXTERN int did_repeated_msg INIT(= 0);
 # define REPEATED_MSG_LOOKING	    1
 # define REPEATED_MSG_SAFESTATE	    2
 #endif
+
+#ifdef FEAT_SPELL
+EXTERN char e_illegal_character_in_word[]
+       INIT(= N_("E1280: Illegal character in word"));
+#endif
diff --git a/src/mbyte.c b/src/mbyte.c
index 5dd2562..28c5e85 100644
--- a/src/mbyte.c
+++ b/src/mbyte.c
@@ -4045,7 +4045,7 @@ theend:
     convert_setup(&vimconv, NULL, NULL);
 }
 
-#if defined(FEAT_GUI_GTK) || defined(PROTO)
+#if defined(FEAT_GUI_GTK) || defined(FEAT_SPELL) || defined(PROTO)
 /*
  * Return TRUE if string "s" is a valid utf-8 string.
  * When "end" is NULL stop at the first NUL.
diff --git a/src/spellfile.c b/src/spellfile.c
index b9451ec..5171572 100644
--- a/src/spellfile.c
+++ b/src/spellfile.c
@@ -4366,6 +4366,10 @@ store_word(
     int		res = OK;
     char_u	*p;
 
+    // Avoid adding illegal bytes to the word tree.
+    if (enc_utf8 && !utf_valid_string(word, NULL))
+       return FAIL;
+
     (void)spell_casefold(word, len, foldword, MAXWLEN);
     for (p = pfxlist; res == OK; ++p)
     {
@@ -6167,6 +6171,12 @@ spell_add_word(
     int		i;
     char_u	*spf;
 
+    if (enc_utf8 && !utf_valid_string(word, NULL))
+    {
+	emsg(_(e_illegal_character_in_word));
+	return;
+    }
+
     if (idx == 0)	    // use internal wordlist
     {
 	if (int_wordlist == NULL)
diff --git a/src/testdir/test_spellfile.vim b/src/testdir/test_spellfile.vim
index 53eca84..1382c02 100644
--- a/src/testdir/test_spellfile.vim
+++ b/src/testdir/test_spellfile.vim
@@ -170,3 +170,9 @@ func Test_spell_normal()
   set spellfile=
   bw!
 endfunc
+
+" Invalid bytes may cause trouble when creating the word list.
+func Test_check_for_valid_word()
+  call assert_fails("spellgood! 0^B\xac", 'E1280:')
+endfunc
+
-- 
1.8.3.1

