Skip to content

Compiler crash/FPE in optimizer constant folding for floating-point % expression #443

Description

@damseleng

Summary

I found a reproducible compiler crash in Gravity's optimizer constant-folding path.

A small Gravity source input containing a floating-point remainder expression causes the compiler to abort with a floating point exception during compilation.

Affected versions tested

I confirmed the issue on both current master and the latest release:

master:
  commit: 3744550945bec341c5c88afa4ed2fad94eb150ca
  non-ASan result: Floating point exception, exit code 136

latest release 0.9.7:
  commit: c66b6902684c75f948c8ee4f8c0c6489362583ee
  non-ASan result: Floating point exception, exit code 136

Reproducer

PoC source:

1%0.5

Run:

./gravity -c gravity_mod_float_divzero.gravity

Observed result

The compiler aborts with a floating point exception.

Under UBSan, the issue is reported as:

src/compiler/gravity_optimizer.c:340:42: runtime error: division by zero

Root cause

The optimizer appears to constant-fold floating-point % expressions by checking only whether the right-hand side is exactly 0.0.

For a value such as 0.5, the check passes because d2 != 0.0, but the code later casts the value to int64_t and performs integer %.

As a result:

(int64_t)0.5 == 0

and the optimizer evaluates an integer modulo operation with divisor zero, causing the compiler to crash.

Expected result

The compiler should not crash while compiling this input.

The optimizer should either:

  • use the same floating-point remainder semantics as the runtime, or
  • avoid folding this expression when the floating-point divisor would become zero after integer conversion.

Suggested fix direction

A local test fix changed the optimizer's handling of floating-point remainder expressions to use runtime-like remainder() / remainderf() behavior instead of casting to integer and applying %.

With that local change, the PoC compiles without crashing in both ASan/UBSan and non-ASan builds.

I also ran a short post-fix compiler fuzzing pass for 301 seconds / 85,422 runs and did not observe additional crashes.

Reproduction package

I have a reproduction package containing the minimized PoC, UBSan/non-ASan logs, report, and suggested fix diff:

submission_gravity_optimizer_divzero_public_minimal.zip
SHA-256: 550EE94E0E398D9E89D02C4D5CC8BFCED93221C15E6C395ADE26DE50FCDA1E64

I can provide the package if useful.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions