From 393cd7f8076692836c20c8f2723228ec8738c06c Mon Sep 17 00:00:00 2001 From: Alexey Andreev Date: Mon, 19 Feb 2024 20:35:21 +0100 Subject: [PATCH] c: don't generate while(condition) loops due to UB in C spec See https://www.iso-9899.info/n1570.html#6.8.5p6 Fix #885 --- .../backend/c/generate/CodeGenerationVisitor.java | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/core/src/main/java/org/teavm/backend/c/generate/CodeGenerationVisitor.java b/core/src/main/java/org/teavm/backend/c/generate/CodeGenerationVisitor.java index aacb58a46..d8d34e7e8 100644 --- a/core/src/main/java/org/teavm/backend/c/generate/CodeGenerationVisitor.java +++ b/core/src/main/java/org/teavm/backend/c/generate/CodeGenerationVisitor.java @@ -1245,13 +1245,15 @@ public class CodeGenerationVisitor implements ExprVisitor, StatementVisitor { int statementId = registerIdentifiedStatement(statement); - writer.print("while ("); + writer.println("while (1) {").indent(); + + // This can't be moved to 'while', since C11 standard allows removing infinite loops + // See https://www.iso-9899.info/n1570.html#6.8.5p6 if (statement.getCondition() != null) { + writer.print("if (!"); statement.getCondition().acceptVisitor(this); - } else { - writer.print("1"); + writer.println(") break;"); } - writer.println(") {").indent(); boolean oldEnd = end; for (Statement part : statement.getBody()) {