git: 9front

Download patch

ref: 1815cc52e202fc77263e25e4f26e1d89e87aed84
parent: 7f40ebaeb5056bb749a84048a795dcb65d9e478f
author: cinap_lenrek <cinap_lenrek@felloff.net>
date: Sat Apr 25 18:16:44 EDT 2020

cc: simplify macexpand() and off-by-one error

the caller of macexpand() needs one more byte in
the buffer to append peekc.

make macexpand() actually check for buffer overflow.

just use strdup() to duplicate include file name
instead of the hunk dance.

move GETC() macro in cc.h

--- a/sys/src/cmd/cc/cc.h
+++ b/sys/src/cmd/cc/cc.h
@@ -143,6 +143,8 @@
 	int	c;
 } fi;
 
+#define	GETC()	((--fi.c < 0)? filbuf(): (*fi.p++ & 0xff))
+
 struct	Io
 {
 	Io*	link;
--- a/sys/src/cmd/cc/lex.c
+++ b/sys/src/cmd/cc/lex.c
@@ -430,7 +430,6 @@
 #define	EOF	(-1)
 #define	IGN	(-2)
 #define	ESC	(1<<20)
-#define	GETC()	((--fi.c < 0)? filbuf(): (*fi.p++ & 0xff))
 
 enum
 {
@@ -756,7 +755,7 @@
 	if(s->macro) {
 		newio();
 		cp = ionext->b;
-		macexpand(s, cp, sizeof(ionext->b));
+		macexpand(s, cp, sizeof(ionext->b)-1);
 		pushio();
 		ionext->link = iostack;
 		iostack = ionext;
--- a/sys/src/cmd/cc/lexbody
+++ b/sys/src/cmd/cc/lexbody
@@ -238,7 +238,7 @@
 		if(s->macro) {
 			newio();
 			cp = ionext->b;
-			macexpand(s, cp, sizeof(ionext->b));
+			macexpand(s, cp, sizeof(ionext->b)-1);
 			pushio();
 			ionext->link = iostack;
 			iostack = ionext;
--- a/sys/src/cmd/cc/macbody
+++ b/sys/src/cmd/cc/macbody
@@ -350,7 +350,7 @@
 		}
 		base = allocn(base, len, 1);
 		base[len++] = c;
-		c = ((--fi.c < 0)? filbuf(): (*fi.p++ & 0xff));
+		c = GETC();
 		if(c == '\n')
 			lineno++;
 		if(c == -1) {
@@ -387,7 +387,10 @@
 	char *arg[NARG], *cp, *ob, *eb, *ecp, dots;
 
 	if(*s->macro == 0) {
+		b[blen-1] = 0;
 		strncpy(b, s->macro+1, blen);
+		if(b[blen-1] != '\0')
+			goto toobig;
 		if(debug['m'])
 			print("#expand %s %s\n", s->name, b);
 		return;
@@ -573,14 +576,13 @@
 	if(c != '\n')
 		goto bad;
 	f = -1;
-	c = 0;
 	for(i=0; i<ninclude; i++) {
 		if(i == 0 && c0 == '>')
 			continue;
-		c = snprint(symb, NSYMB, "%s/%s", include[i], str)+1;
-		if(strncmp(symb, "./", 2) == 0){
+		c = snprint(symb, NSYMB, "%s/%s", include[i], str);;
+		while(strncmp(symb, "./", 2) == 0){
 			c -= 2;
-			memmove(symb, symb+2, c);
+			memmove(symb, symb+2, c+1);
 		}
 		f = open(symb, 0);
 		if(f >= 0)
@@ -587,18 +589,10 @@
 			break;
 	}
 	if(f < 0)
-		c = snprint(symb, NSYMB, "%s", str)+1;
-	while(c & 3)
-		c++;
-	while(nhunk < c)
-		gethunk();
-	hp = hunk;
-	memmove(hunk, symb, c);
-	nhunk -= c;
-	hunk += c;
+		snprint(symb, NSYMB, "%s", str);
 	newio();
 	pushio();
-	newfile(hp, f);
+	newfile(strdup(symb), f);
 	return;
 
 bad:
--