Skip to content

Commit be78590

Browse files
Port the standalone build's exception recovery boundary from #111971
The module aborted on any query the parser rejects by throwing rather than by returning `false` - `SELECT sum(x) OVER (ROWS BETWEEN UNBOUNDED FOLLOWING AND CURRENT ROW)`, for one - because `-fignore-exceptions` leaves nothing to catch. `__cxa_throw` now jumps back to a `setjmp` boundary armed by `ch_check` and `ch_format`, which report the message as a parse failure; the module stays usable afterwards, which the test now checks. Recovery is gated on the thrown type being exactly `DB::Exception`; anything else still stops the module. This costs about 570 bytes and `-lsetjmp`, against the 262 KB and the exception-handling proposal that `-fwasm-exceptions` would cost. `longjmp` runs no destructors, so such a query leaks what the parser allocated below the boundary - documented at `__cxa_throw`. Ported from `parser-standalone-build` (ebca121, 905c264, 6c4bdae), which #112067 supersedes; flagged in #112067 (comment)
1 parent 6894733 commit be78590

5 files changed

Lines changed: 131 additions & 20 deletions

File tree

‎utils/wasm-parser/README.md‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,12 @@ described below; `ch_features` reports which of them a given module was built wi
3131

3232
Nothing here needs the WebAssembly exception-handling proposal. `tryParseQuery` reports a syntax
3333
error by returning null rather than by throwing, and no code in `src/Parsers` catches anything, so
34-
the build passes `-fignore-exceptions` and a `throw` that does escape aborts.
34+
the build passes `-fignore-exceptions`. The handful of parser checks that still report an invalid
35+
query by throwing - `Frame start cannot be UNBOUNDED FOLLOWING`, for one - reach the same place
36+
through a `setjmp` boundary that `wasm_runtime.cpp` jumps to instead of aborting. Recovery covers
37+
`DB::Exception` and nothing else: anything else arriving there - a `std::bad_alloc` from
38+
`operator new`, say - is an object of an unrelated type that cannot be read, so its type name is
39+
reported and the module stops.
3540

3641
## What it costs
3742

‎utils/wasm-parser/build.sh‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,8 @@ CXXFLAGS=(
7676
-DCLICKHOUSE_PARSER_MINIMAL_BUILD
7777
-DFMT_USE_LOCALE=0
7878
-fignore-exceptions
79+
# `setjmp`/`longjmp` is the error boundary around the parser - see wasm_runtime.cpp
80+
-mllvm -wasm-enable-sjlj
7981
-fno-asynchronous-unwind-tables
8082
# Link-time optimization, plus removal of virtual functions that nothing calls through a vtable.
8183
# `-fvirtual-function-elimination` needs full LTO, which is why the server build (ThinLTO) cannot
@@ -199,7 +201,7 @@ echo "Linking..."
199201
"$CXX" "${CXXFLAGS[@]}" \
200202
-Wl,--no-entry -mexec-model=reactor -Wl,--strip-all \
201203
"${EXPORTS[@]/#/-Wl,}" \
202-
"$OUT"/obj/*.o -lwasi-emulated-signal -lwasi-emulated-mman \
204+
"$OUT"/obj/*.o -lsetjmp -lwasi-emulated-signal -lwasi-emulated-mman \
203205
-o "$OUT/parser.wasm"
204206

205207
printf '%s: %s bytes (%s gzipped)\n' "$OUT/parser.wasm" \

‎utils/wasm-parser/test.mjs‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,20 @@ const cases = [
4444
"SYSTEM DROP REPLICA 'r' FROM ZKPATH '/clickhouse/tables/x//'",
4545
'SELECT 1 +', // expected to fail
4646
'SELCT 1', // expected to fail
47+
// Reported by throwing from the parser, which has no unwinding here: it must come back as an
48+
// error, and the module must stay usable afterwards - see __cxa_throw in wasm_runtime.cpp.
49+
'SELECT sum(x) OVER (ROWS BETWEEN UNBOUNDED FOLLOWING AND CURRENT ROW) FROM t',
50+
'SELECT sum(x) OVER (ROWS BETWEEN CURRENT ROW AND UNBOUNDED PRECEDING) FROM t',
51+
'SELECT 1 + 2', // the parse after a throw must still work
4752
];
4853

54+
const expectedToFail = new Set([
55+
'SELECT 1 +',
56+
'SELCT 1',
57+
'SELECT sum(x) OVER (ROWS BETWEEN UNBOUNDED FOLLOWING AND CURRENT ROW) FROM t',
58+
'SELECT sum(x) OVER (ROWS BETWEEN CURRENT ROW AND UNBOUNDED PRECEDING) FROM t',
59+
]);
60+
4961
/// Only a build with DCL accepts these.
5062
const dclCases = [
5163
"CREATE USER u IDENTIFIED WITH sha256_password BY 'p' HOST IP '192.168.0.0/16'",
@@ -57,7 +69,7 @@ cases.push(...dclCases);
5769
let pass = 0;
5870
for (const sql of cases) {
5971
const r = format(sql, 1);
60-
const expectFail = sql === 'SELECT 1 +' || sql === 'SELCT 1' || (!hasDcl && dclCases.includes(sql));
72+
const expectFail = expectedToFail.has(sql) || (!hasDcl && dclCases.includes(sql));
6173
const good = expectFail ? !r.ok : r.ok;
6274
pass += good ? 1 : 0;
6375
console.log(`${good ? 'ok ' : 'FAIL'} ${r.ok ? '' : '[error] '}${r.out.replace(/\n/g, ' ').slice(0, 110)}`);

‎utils/wasm-parser/wasm_parser.cpp‎

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,19 @@
1818
#include <Parsers/ParserQuery.h>
1919
#include <Parsers/parseQuery.h>
2020

21+
#include <csetjmp>
2122
#include <cstdint>
2223
#include <string>
2324
#include <new>
2425

26+
extern "C"
27+
{
28+
/// The error boundary; defined in `wasm_runtime.cpp`.
29+
jmp_buf * chParserRecoveryPoint();
30+
void chParserArmRecovery(bool armed);
31+
const char * chParserRecoveryMessage();
32+
}
33+
2534
namespace
2635
{
2736

@@ -35,9 +44,10 @@ constexpr size_t MAX_QUERY_SIZE = 1u << 20;
3544
constexpr size_t MAX_PARSER_DEPTH = 1000;
3645
constexpr size_t MAX_PARSER_BACKTRACKS = 1000000;
3746

38-
/// `tryParseQuery` reports a syntax error by returning null and filling in the message; it does not
39-
/// throw, and nothing in `src/Parsers` catches. So there is nothing to catch here either, which is
40-
/// what lets this build with `-fno-exceptions`.
47+
/// `tryParseQuery` reports a syntax error by returning null and filling in the message, and
48+
/// nothing in `src/Parsers` catches. A few checks in the parser still report an invalid query by
49+
/// throwing, and this build has no unwinding, so `wasm_runtime.cpp` turns such a throw into a jump
50+
/// back to the `setjmp` boundary the caller armed - see the comment on `__cxa_throw` there.
4151
DB::ASTPtr parse(const char * query, uint32_t size, std::string & error)
4252
{
4353
const char * end = query + size;
@@ -85,30 +95,50 @@ void ch_free(uint8_t * ptr)
8595

8696
int ch_check(const char * query, uint32_t size)
8797
{
98+
if (setjmp(*chParserRecoveryPoint()) != 0)
99+
{
100+
result() = chParserRecoveryMessage();
101+
return 0;
102+
}
103+
chParserArmRecovery(true);
104+
88105
std::string error;
89106
if (!parse(query, size, error))
90107
{
108+
chParserArmRecovery(false);
91109
result() = std::move(error);
92110
return 0;
93111
}
94112

113+
chParserArmRecovery(false);
95114
result().clear();
96115
return 1;
97116
}
98117

99118
#if !defined(CLICKHOUSE_PARSER_NO_FORMATTING)
100119
int ch_format(const char * query, uint32_t size, int one_line)
101120
{
121+
if (setjmp(*chParserRecoveryPoint()) != 0)
122+
{
123+
result() = chParserRecoveryMessage();
124+
return 0;
125+
}
126+
chParserArmRecovery(true);
127+
102128
std::string error;
103129
DB::ASTPtr ast = parse(query, size, error);
104130

105131
if (!ast)
106132
{
133+
chParserArmRecovery(false);
107134
result() = std::move(error);
108135
return 0;
109136
}
110137

138+
/// Formatting throws for an AST the parser accepted but cannot print, so it stays inside the
139+
/// boundary too.
111140
result() = one_line ? ast->formatWithSecretsOneLine() : ast->formatWithSecretsMultiLine();
141+
chParserArmRecovery(false);
112142
return 1;
113143
}
114144
#endif

‎utils/wasm-parser/wasm_runtime.cpp‎

Lines changed: 76 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,11 @@
1717
#include <Common/CurrentMemoryTracker.h>
1818
#include <Core/Settings.h>
1919

20+
#include <csetjmp>
2021
#include <cstddef>
2122
#include <cstdio>
2223
#include <cstdlib>
24+
#include <cstring>
2325
#include <exception>
2426
#include <string>
2527
#include <typeinfo>
@@ -282,16 +284,60 @@ const SettingFieldTimezone & Settings::operator[](SettingsTimezone) const
282284
/// Exceptions.
283285
///
284286
/// The build uses `-fignore-exceptions`: `throw`, `try` and `catch` still compile, but no landing
285-
/// pads or unwind tables are emitted, so nothing can be caught. That is sound here because an
286-
/// exception can only mean a bug or a resource limit - a syntax error is reported by
287-
/// `tryParseQuery` returning null, and `src/Parsers` contains no `catch` at all, which a style
288-
/// check enforces. Defining `__cxa_throw` here keeps libc++abi's exception machinery out of the
289-
/// bundle entirely; the exception object is constructed and then we stop.
287+
/// pads or unwind tables are emitted, so nothing can be caught, and defining `__cxa_throw` here
288+
/// keeps libc++abi's exception machinery out of the bundle entirely.
289+
///
290+
/// A syntax error does not come this way - `tryParseQuery` returns null and fills in the message,
291+
/// and `src/Parsers` contains no `catch` at all, which a style check enforces. But a handful of
292+
/// checks in the parser still report an invalid query by throwing (`Frame start cannot be
293+
/// UNBOUNDED FOLLOWING`, for one), and stopping the module on an ordinary user mistake is not
294+
/// acceptable. So `ch_check` and `ch_format` arm a `setjmp` boundary and a throw returns to it,
295+
/// with the message, as a parse failure.
296+
///
297+
/// The unwinding this replaces would have run destructors; `longjmp` does not, so a throw leaks
298+
/// whatever the parser allocated below the boundary. The alternative is `-fwasm-exceptions`, which
299+
/// costs 262 KB and an engine implementing the exception-handling proposal - too much to pay for
300+
/// tidiness on a path that a browser hits only on an invalid query.
301+
///
302+
/// Recovery is for `DB::Exception` and nothing else. The object arriving at `__cxa_throw` is
303+
/// untyped, so its dynamic type has to be established from the `type_info` argument before it can
304+
/// be read as anything; a `std::bad_alloc` from `operator new` or a `Poco` exception is an
305+
/// unrelated object, and reading it through a `Poco::Exception` pointer would be undefined. For
306+
/// those only the type name can be reported, and the module stops. The comparison is exact rather
307+
/// than a `dynamic_cast` - there is no RTTI hierarchy walk available here - so a hypothetical class
308+
/// derived from `DB::Exception` also lands in the second case, which is the safe direction.
290309
/// ---------------------------------------------------------------------------------------------
291310

311+
namespace
312+
{
313+
314+
jmp_buf recovery_point;
315+
bool recovery_armed = false;
316+
317+
/// Not a `std::string`: filling this in must not allocate, or a throw from the allocation would
318+
/// re-enter `__cxa_throw`.
319+
char recovery_message[1024];
320+
321+
}
322+
292323
extern "C"
293324
{
294325

326+
jmp_buf * chParserRecoveryPoint()
327+
{
328+
return &recovery_point;
329+
}
330+
331+
void chParserArmRecovery(bool armed)
332+
{
333+
recovery_armed = armed;
334+
}
335+
336+
const char * chParserRecoveryMessage()
337+
{
338+
return recovery_message;
339+
}
340+
295341
void * __cxa_allocate_exception(size_t size) noexcept
296342
{
297343
/// The exception object is constructed in place here, so the storage has to be aligned for any
@@ -306,17 +352,33 @@ void __cxa_free_exception(void *) noexcept
306352

307353
[[noreturn]] void __cxa_throw(void * thrown, void * type_info, void (*)(void *))
308354
{
309-
/// Only `DB::Exception` may be read as such: the thrown object is untyped here, and everything
310-
/// else - `std::bad_alloc` from `operator new`, a `Poco` exception from a `Poco::Net` address
311-
/// parser - would be a reinterpretation of an unrelated object. For those, the type name is all
312-
/// that can be reported safely. This is not a `dynamic_cast`, so a hypothetical class derived
313-
/// from `DB::Exception` also falls into the second case rather than into undefined behavior.
314355
const auto * thrown_type = static_cast<const std::type_info *>(type_info);
315-
const char * message = thrown_type && *thrown_type == typeid(DB::Exception)
316-
? static_cast<const DB::Exception *>(thrown)->what()
317-
: (thrown_type ? thrown_type->name() : "unknown exception");
318356

319-
std::fprintf(stderr, "ClickHouse parser: unrecoverable error: %s\n", message);
357+
if (thrown_type && *thrown_type == typeid(DB::Exception))
358+
{
359+
/// `DB::Exception` derives from `Poco::Exception`, whose `what()` is the message.
360+
const char * message = static_cast<const DB::Exception *>(thrown)->what();
361+
362+
if (recovery_armed)
363+
{
364+
/// Disarm first: this is the only path that can be re-entered.
365+
recovery_armed = false;
366+
367+
size_t length = std::strlen(message);
368+
if (length > sizeof(recovery_message) - 1)
369+
length = sizeof(recovery_message) - 1;
370+
std::memcpy(recovery_message, message, length);
371+
recovery_message[length] = 0;
372+
373+
longjmp(recovery_point, 1);
374+
}
375+
376+
std::fprintf(stderr, "ClickHouse parser: unrecoverable error: %s\n", message);
377+
std::abort();
378+
}
379+
380+
/// The object cannot be read, so the type name is all there is to report.
381+
std::fprintf(stderr, "ClickHouse parser: unrecoverable error of type %s\n", thrown_type ? thrown_type->name() : "unknown");
320382
std::abort();
321383
}
322384

0 commit comments

Comments
 (0)