Skip to content

Harden the OpenQASM 2.0 parser against malformed input - #92

Open
mizuta-c5 wants to merge 1 commit into
softwareQinc:mainfrom
mizuta-c5:harden-openqasm-parser
Open

mizuta-c5 wants to merge 1 commit into
softwareQinc:mainfrom
mizuta-c5:harden-openqasm-parser

Conversation

@mizuta-c5

Copy link
Copy Markdown

Harden the OpenQASM 2.0 parser against malformed input

Summary

Malformed OpenQASM input reachable via parse_string (hence pystaq.parse_str/staq CLI) can abort or hang the process. This PR closes five such cases; valid input is unchanged.

Cases

Input Before Cause
integer literal > INT_MAX abort() uncaught std::out_of_range from std::stoi
real literal out of float range (1e99999999) abort() uncaught std::out_of_range from std::stof
deeply nested (((…))) SIGSEGV unbounded recursion in parse_exp/parse_atom
unterminated string at EOF infinite loop lex_string loop omits the EOF check
wrong token where an id/int is expected (qreg 5[2];) abort() std::bad_variant_access from as_string()/as_int()

Cases 1, 2 and 5 raise exceptions other than ParseError (a ParseError-only handler still aborts); cases 3 and 4 bypass exception handling entirely.

Changes

File Change
lexer.hpp wrap std::stoi/std::stof in try/catch (std::out_of_range) → Token::Kind::error; add && buf_->peek() != EOF to the lex_string loop
parser.hpp RAII depth guard (MAX_EXPR_DEPTH = 1000) on expression recursion; overflow raises ParseError
token.hpp as_int/as_real/as_string made total via std::get_if, returning a default on mismatch; parser error_ flag still yields ParseError
CHANGES.md one line under # Pre-release

Testing

  • The five inputs now return ParseError or parse cleanly — no abort or hang.
  • All 82 sample .qasm files parse identically before and after.

Guard the qasmtools recursive-descent parser against malformed input reachable
through the public entry point: catch out-of-range numeric literals, bound
expression recursion depth, guard EOF in string lexing, and replace
exception-throwing variant access with safe accessors. No behavioral change on
valid input (all bundled .qasm samples parse identically).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JdMbZBMa3kMKd2QTRoqnff
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant