ref: 7e46551105c8bc3b8b4b2b9bc02b36d494dce031
parent: 2db536693e12b92e7f636958973328105dd0ea5e
author: Roberto E. Vargas Caballero <k0ga@shike2.com>
date: Tue Oct 14 07:10:05 EDT 2014
Generate unexpected in primary() The parser was returning NULL when it was no able of parsing a expression, and this was used in for statements for empty expressions, but it generate segmentation faults in some cases. It is better check when the expression can be NULL because is faster (we don't have to call the recursive functions of expr()), and it is more secure because we don't have to check against empty expressions in all the places where it is called.
--- a/cc1/expr.c
+++ b/cc1/expr.c
@@ -435,8 +435,7 @@
expect(')');
break;
default:
- np = NULL;
- break;
+ unexpected();
}
return np;
}
--- a/cc1/stmt.c
+++ b/cc1/stmt.c
@@ -96,12 +96,12 @@
expect(FOR);
expect('(');
- einit = expr();
+ einit = (yytoken != ';') ? expr() : NULL;
expect(';');
- econd = expr();
+ econd = (yytoken != ';') ? expr() : NULL;
expect(';');
- einc = expr();
- expect(')');
+ einc = (yytoken != ')') ? expr() : NULL;
+ expect(';');
emitexp(einit);
emitjump(cond, NULL);
@@ -139,7 +139,7 @@
Type *tp = curfun->type->type;
expect(RETURN);
- np = eval(expr());
+ np = (yytoken != ';') ? eval(expr()) : NULL;
expect(';');
if (!np) {
if (tp != voidtype)
@@ -215,8 +215,7 @@
expect(SWITCH);
expect ('(');
- if ((cond = expr()) == NULL)
- unexpected();
+ cond = expr();
if ((cond = convert(cond, inttype, 0)) == NULL)
error("incorrect type in switch statement");
expect (')');
@@ -246,8 +245,7 @@
expect(CASE);
if (!lswitch)
error("case label not within a switch statement");
- if ((np = expr()) == NULL)
- unexpected();
+ np = expr();
if ((np = convert(np, inttype, 0)) == NULL)
error("incorrect type in case statement");
expect(':');
--
⑨