[binutils-gdb] [gdb] Improve selftest c_ctrl_unctrl

Tom de Vries via Gdb-cvs <[email protected]>
Newsgroups gmane.comp.gdb.cvs
Message-ID <[email protected]>
https://sourceware.org/git/gitweb.cgi?p=binutils-gdb.git;h=4308969628943757f972e766c70352c4828cb4d2

commit 4308969628943757f972e766c70352c4828cb4d2
Author: Tom de Vries <[email protected]>
Date:   Fri Apr 24 15:15:26 2026 +0200

    [gdb] Improve selftest c_ctrl_unctrl
    
    Improve selftest c_ctrl_unctrl by exercising all valid inputs of c_iscntrl.
    
    Tested on x86_64-linux.
    
    Suggested-By: Tom Tromey <[email protected]> [1]
    
    [1] https://sourceware.org/pipermail/gdb-patches/2026-March/226231.html

Diff:
---
 gdb/utils.c | 24 +++++++++++++++++++++---
 1 file changed, 21 insertions(+), 3 deletions(-)

diff --git a/gdb/utils.c b/gdb/utils.c
index f5f19301460..a7e91ce686b 100644
--- a/gdb/utils.c
+++ b/gdb/utils.c
@@ -3795,12 +3795,30 @@ test_c_ctrl_unctrl ()
   SELF_CHECK (c_ctrl ('?') == 0x7f);
   SELF_CHECK (c_unctrl (0x7f) == '?');
 
-  /* Consistency check.  */
-  for (unsigned int i = 0; i < 0x100; i++)
+  /* Consistency check.
+
+     The ctype.h function iscntrl has an int parameter, and defined behavior
+     for inputs [0, 255] and EOF.  Consequently, iscntrl has undefined
+     behavior when called with a negative signed char argument (with the
+     possible exception of EOF, which is a negative int constant).  That
+     extends to chars on platforms where char == signed char.  Consequently,
+     to write portable code, iscntrl char and signed char arguments need to be
+     cast to unsigned char.
+
+     The c-ctype.h variant c_iscntrl sidesteps this problem by having defined
+     behavior for inputs [-128, 255] and not bothering about EOF.
+
+     The functions c_ctrl/c_unctrl sidestep this issue by using parameter
+     type unsigned char instead of int.
+
+     So, testing input values [0..255] tests all relevant behavior of
+     c_ctrl/c_unctrl.  However, we designed these functions to be compatible
+     with c_iscntrl, so we test for all valid inputs of that function.  */
+  for (int i = -128; i < 256; i++)
     {
       unsigned char ch = i;
       unsigned char unctrl_ch = c_unctrl (ch);
-      if (!c_iscntrl (ch))
+      if (!c_iscntrl (i))
 	{
 	  SELF_CHECK (unctrl_ch == ch);
 	  continue;
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.