From 83823ad34de0bcd909bc367b7af072d6e176fca9 Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Thu, 26 Nov 2026 04:43:49 +0000 Subject: [PATCH 1/4] test: parse deeply nested PL/pgSQL in the WASM depth test --- .github/workflows/ci.yml | 3 +++ test/wasm_depth.c | 55 ++++++++++++++++++++++++++++++++++++++-- 2 files changed, 56 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fddb2e35..67930ed8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -97,6 +97,9 @@ jobs: emcc -O3 -sENVIRONMENT=node -sSTACK_SIZE=33554432 -sINITIAL_MEMORY=41943040 \ -sALLOW_MEMORY_GROWTH=1 -I. test/wasm_depth.c libpg_query.a -o test/wasm_depth.js node test/wasm_depth.js + emcc -O3 -sENVIRONMENT=node -sSTACK_SIZE=1048576 -sINITIAL_MEMORY=41943040 \ + -sALLOW_MEMORY_GROWTH=1 -I. test/wasm_depth.c libpg_query.a -o test/wasm_depth_small.js + node test/wasm_depth_small.js overflow build_macos: runs-on: macos-latest steps: diff --git a/test/wasm_depth.c b/test/wasm_depth.c index 090e5d68..9e4f7102 100644 --- a/test/wasm_depth.c +++ b/test/wasm_depth.c @@ -49,16 +49,67 @@ static bool check_depth(const char *name, const char *open, int depth, return ok; } -int main(void) +/* depth nested PL/pgSQL blocks, e.g. "IF true THEN " ... "NULL;" ... " END IF;" */ +static bool check_plpgsql_depth(const char *name, const char *open, const char *body, + const char *close, int depth) +{ + const char prefix[] = "CREATE FUNCTION f() RETURNS void LANGUAGE plpgsql AS $$ BEGIN "; + const char suffix[] = " END $$"; + size_t open_len = strlen(open), body_len = strlen(body), close_len = strlen(close); + char *query = malloc(sizeof(prefix) + depth * (open_len + close_len) + body_len + sizeof(suffix)); + if (query == NULL) + { + fprintf(stderr, "FAIL %s: could not allocate query\n", name); + return false; + } + + char *p = query; + memcpy(p, prefix, sizeof(prefix) - 1); + p += sizeof(prefix) - 1; + for (int i = 0; i < depth; i++, p += open_len) + memcpy(p, open, open_len); + memcpy(p, body, body_len); + p += body_len; + for (int i = 0; i < depth; i++, p += close_len) + memcpy(p, close, close_len); + memcpy(p, suffix, sizeof(suffix)); + + PgQueryPlpgsqlParseResult result = pg_query_parse_plpgsql(query); + bool ok = result.error == NULL && result.plpgsql_funcs != NULL; + if (ok) + printf("PASS %s: parsed successfully\n", name); + else + fprintf(stderr, "FAIL %s: expected a parse tree, got %s\n", name, + result.error ? result.error->message : "no parse tree"); + + pg_query_free_plpgsql_parse_result(result); + free(query); + return ok; +} + +/* + * Without arguments, run with the WebAssembly stack libpg-query-node links + * (32MB). With "overflow", run with a 1MB stack, small enough that the stack + * depth check fires before the host engine's native stack runs out. + */ +int main(int argc, char **argv) { int status = EXIT_SUCCESS; + if (argc > 1 && strcmp(argv[1], "overflow") == 0) + { + if (!check_depth("100000 chained terms", "1+", 99999, false, true)) + status = EXIT_FAILURE; + return status; + } if (!check_depth("2000 chained terms", "1+", 1999, false, false)) status = EXIT_FAILURE; if (!check_depth("1000 nested subqueries", "(SELECT ", 1000, true, false)) status = EXIT_FAILURE; if (!check_depth("2000 nested function calls", "f(", 2000, true, false)) status = EXIT_FAILURE; - if (!check_depth("100000 chained terms", "1+", 99999, false, true)) + if (!check_plpgsql_depth("1000 nested IF blocks", "IF true THEN ", "NULL;", " END IF;", 1000)) + status = EXIT_FAILURE; + if (!check_plpgsql_depth("3000 nested BEGIN blocks", "BEGIN ", "NULL;", " END;", 3000)) status = EXIT_FAILURE; return status; } From f975bb56d6b93b9ce23135da66cee81308ec3a98 Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Thu, 26 Nov 2026 04:45:51 +0000 Subject: [PATCH 2/4] Use the whole WebAssembly stack for the stack depth limit --- src/pg_query.c | 23 +++++++++-------------- 1 file changed, 9 insertions(+), 14 deletions(-) diff --git a/src/pg_query.c b/src/pg_query.c index 6eefbd3d..0e1cfc31 100644 --- a/src/pg_query.c +++ b/src/pg_query.c @@ -33,17 +33,6 @@ #include -#if defined(__EMSCRIPTEN__) -/* - * WebAssembly code also runs on the host engine's native stack (about 1MB in - * Node and browsers), where its frames are larger than on the WebAssembly - * stack, so a larger limit overflows the native stack before it is reached. - */ -#define PG_QUERY_MAX_STACK_DEPTH_KB 512 -#else -#define PG_QUERY_MAX_STACK_DEPTH_KB 2048 -#endif - const char* progname = "pg_query"; __thread sig_atomic_t pg_query_initialized = 0; @@ -272,9 +261,15 @@ static void set_max_stack_depth(void) if (new_limit <= 100) return; - /* Clamp at 2MB (512kB in WebAssembly), like Postgres auto-detection logic. */ - if (new_limit > PG_QUERY_MAX_STACK_DEPTH_KB) - new_limit = PG_QUERY_MAX_STACK_DEPTH_KB; +#if !defined(__EMSCRIPTEN__) + /* + * Clamp at 2MB, like Postgres auto-detection logic. WebAssembly uses its + * whole stack, whose size is set when linking: the host engine's native + * stack usually runs out first there, which the embedder has to handle. + */ + if (new_limit > 2048) + new_limit = 2048; +#endif max_stack_depth = (int) new_limit; assign_max_stack_depth((int) new_limit, NULL); From b8f59459df61b1f887dd3e637d09490527001b03 Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Thu, 26 Nov 2026 05:43:16 +0000 Subject: [PATCH 3/4] test: normalize deeply chained terms in the WASM depth test --- test/wasm_depth.c | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/test/wasm_depth.c b/test/wasm_depth.c index 9e4f7102..0f696b07 100644 --- a/test/wasm_depth.c +++ b/test/wasm_depth.c @@ -87,6 +87,42 @@ static bool check_plpgsql_depth(const char *name, const char *open, const char * return ok; } +/* depth chained terms through pg_query_normalize, e.g. "SELECT 1+1+1" */ +static bool check_normalize_depth(const char *name, int depth) +{ + const char prefix[] = "SELECT 1"; + char *query = malloc(sizeof(prefix) + (depth - 1) * 2); + if (query == NULL) + { + fprintf(stderr, "FAIL %s: could not allocate query\n", name); + return false; + } + + char *p = query; + memcpy(p, prefix, sizeof(prefix) - 1); + p += sizeof(prefix) - 1; + for (int i = 1; i < depth; i++, p += 2) + memcpy(p, "+1", 2); + *p = '\0'; + + PgQueryNormalizeResult result = pg_query_normalize(query); + int params = 0; + if (result.normalized_query != NULL) + for (const char *c = result.normalized_query; *c; c++) + params += *c == '$'; + bool ok = result.error == NULL && params == depth; + if (ok) + printf("PASS %s: normalized successfully\n", name); + else if (result.error) + fprintf(stderr, "FAIL %s: expected a normalized query, got %s\n", name, result.error->message); + else + fprintf(stderr, "FAIL %s: expected %d parameters, got %d\n", name, depth, params); + + pg_query_free_normalize_result(result); + free(query); + return ok; +} + /* * Without arguments, run with the WebAssembly stack libpg-query-node links * (32MB). With "overflow", run with a 1MB stack, small enough that the stack @@ -101,6 +137,12 @@ int main(int argc, char **argv) status = EXIT_FAILURE; return status; } + /* + * First, while the host engine has not optimized anything yet: its native + * stack then holds the fewest levels. + */ + if (!check_normalize_depth("normalize 3000 chained terms", 3000)) + status = EXIT_FAILURE; if (!check_depth("2000 chained terms", "1+", 1999, false, false)) status = EXIT_FAILURE; if (!check_depth("1000 nested subqueries", "(SELECT ", 1000, true, false)) From 18457636e47930e5aedaf915087616ca7dd14056 Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Thu, 26 Nov 2026 05:47:39 +0000 Subject: [PATCH 4/4] Normalize nested expressions without a PG_TRY block per level --- src/pg_query_normalize.c | 114 +++++++++++++++++++++++++++------------ 1 file changed, 79 insertions(+), 35 deletions(-) diff --git a/src/pg_query_normalize.c b/src/pg_query_normalize.c index 3b2472e4..ebaaf49c 100644 --- a/src/pg_query_normalize.c +++ b/src/pg_query_normalize.c @@ -347,11 +347,55 @@ static void RecordConstLocation(pgssConstLocations *jstate, int location) } } -static bool const_record_walker(Node *node, pgssConstLocations *jstate) +static bool const_record_walker(Node *node, pgssConstLocations *jstate); + +/* + * Walks a node of a type raw_expression_tree_walker() may not know about. + * + * This is its own function, rather than part of const_record_walker, because + * WebAssembly builds route every call made by a function that contains a + * PG_TRY block through the host engine, which uses up a lot of its native + * stack for each level of a deeply nested expression. + */ +static pg_noinline bool const_record_walker_ignore_errors(Node *node, pgssConstLocations *jstate) { - bool result; + volatile bool result = false; MemoryContext normalize_context = CurrentMemoryContext; + /* + * Note we must not return from inside PG_TRY, since that skips + * PG_END_TRY and leaves PG_exception_stack pointing at this + * frame after it is gone. + */ + PG_TRY(); + { + result = raw_expression_tree_walker(node, const_record_walker, (void*) jstate); + } + PG_CATCH(); + { + ErrorData *edata; + + MemoryContextSwitchTo(normalize_context); + edata = CopyErrorData(); + + /* + * The walker raises for node types it doesn't know, which we + * ignore. But if we ran out of stack, the rest of the tree + * was not walked, and swallowing that would return a partially + * normalized query as if it was complete - pass it on instead. + */ + if (edata->sqlerrcode == ERRCODE_STATEMENT_TOO_COMPLEX) + PG_RE_THROW(); + + /* edata is released together with the per-call memory context */ + FlushErrorState(); + } + PG_END_TRY(); + return result; +} + +static bool const_record_walker(Node *node, pgssConstLocations *jstate) +{ if (node == NULL) return false; /* @@ -588,40 +632,40 @@ static bool const_record_walker(Node *node, pgssConstLocations *jstate) if (jstate->normalize_utility_only) return false; return raw_expression_tree_walker(node, const_record_walker, (void*) jstate); } + case T_List: + case T_A_Expr: + case T_BoolExpr: + case T_SubLink: + case T_FuncCall: + case T_NamedArgExpr: + case T_ResTarget: + case T_TypeCast: + case T_CollateClause: + case T_ColumnRef: + case T_A_Indirection: + case T_A_Indices: + case T_A_ArrayExpr: + case T_RowExpr: + case T_CaseExpr: + case T_CoalesceExpr: + case T_MinMaxExpr: + case T_NullTest: + case T_BooleanTest: + case T_JoinExpr: + case T_RangeSubselect: + case T_RangeFunction: + case T_RangeVar: + case T_SortBy: + case T_WithClause: + case T_CommonTableExpr: + /* + * raw_expression_tree_walker() handles these node types, which + * make up most of a deeply nested expression, so they don't need + * const_record_walker_ignore_errors() and its PG_TRY block. + */ + return raw_expression_tree_walker(node, const_record_walker, (void*) jstate); default: - { - /* - * Note we must not return from inside PG_TRY, since that skips - * PG_END_TRY and leaves PG_exception_stack pointing at this - * frame after it is gone. - */ - result = false; - PG_TRY(); - { - result = raw_expression_tree_walker(node, const_record_walker, (void*) jstate); - } - PG_CATCH(); - { - ErrorData *edata; - - MemoryContextSwitchTo(normalize_context); - edata = CopyErrorData(); - - /* - * The walker raises for node types it doesn't know, which we - * ignore. But if we ran out of stack, the rest of the tree - * was not walked, and swallowing that would return a partially - * normalized query as if it was complete - pass it on instead. - */ - if (edata->sqlerrcode == ERRCODE_STATEMENT_TOO_COMPLEX) - PG_RE_THROW(); - - /* edata is released together with the per-call memory context */ - FlushErrorState(); - } - PG_END_TRY(); - return result; - } + return const_record_walker_ignore_errors(node, jstate); } return false;