From b2e552399bb0f6ed8bb1fc70b4a52934513d7cf8 Mon Sep 17 00:00:00 2001
From: Mattias Andrée <maandree@kth.se>
Date: Tue, 2 Jun 2020 21:29:15 +0200
Subject: Break trigraph sequences in trace output
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Signed-off-by: Mattias Andrée <maandree@kth.se>
---
 memory.c | 23 +++++++++++++++++++----
 1 file changed, 19 insertions(+), 4 deletions(-)

diff --git a/memory.c b/memory.c
index 6262c61..b6abe3e 100644
--- a/memory.c
+++ b/memory.c
@@ -126,6 +126,13 @@ found:
 }
 
 
+static int
+istrigraphfinal(char c)
+{
+	return c == '=' || c == '(' || c == '/' || c == ')' || c == '\'' || c == '<' || c == '!' || c == '>' || c == '-';
+}
+
+
 char *
 escape_memory(char *str, size_t m)
 {
@@ -133,7 +140,8 @@ escape_memory(char *str, size_t m)
 	size_t size = 0;
 	size_t len = 0;
 	size_t n = 0;
-	int need_new_string = 0;
+	int need_new_string_hex = 0;
+	int trigraph_state = 0;
 	if (!str) {
 		str = strdup("NULL");
 		if (!str)
@@ -180,17 +188,24 @@ escape_memory(char *str, size_t m)
 				add_char(&ret, &size, &len, 'x');
 				add_char(&ret, &size, &len, "0123456789abcdef"[(int)*(unsigned char *)s >> 4]);
 				add_char(&ret, &size, &len, "0123456789abcdef"[(int)*(unsigned char *)s & 15]);
-				need_new_string = 1;
+				need_new_string_hex = 1;
 				continue;
 			}
 		} else {
-			if (need_new_string && isxdigit(*s)) {
+			if ((need_new_string_hex && isxdigit(*s)) ||
+			    (trigraph_state == 2 && istrigraphfinal(*s))) {
 				add_char(&ret, &size, &len, '"');
 				add_char(&ret, &size, &len, '"');
+			} else if (*s == '?') {
+				trigraph_state += trigraph_state < 2;
+				add_char(&ret, &size, &len, *s);
+				need_new_string_hex = 0;
+				continue;
 			}
 			add_char(&ret, &size, &len, *s);
 		}
-		need_new_string = 0;
+		trigraph_state = 0;
+		need_new_string_hex = 0;
 	}
 	add_char(&ret, &size, &len, '"');
 	add_char(&ret, &size, &len, '\0');
-- 
cgit v1.2.3-70-g09d2