From ffc9e59691a3c5653dc7cf1a7ad7e6723a999e7e Mon Sep 17 00:00:00 2001 From: Zsolt Parragi Date: Tue, 24 Nov 2026 17:19:09 +0000 Subject: [PATCH v1] Prevent stack overflow in exprLocation(). exprLocation() recurses down to the leftmost token of an expression without checking the stack depth. The grammar calls it on raw parse trees, whose depth is not bounded by the parser stack: a chain of a left-associative operator such as 1+1+...+1 is reduced as it is read. A statement like (SELECT 1 ORDER BY 1) ORDER BY 1+1+...+1 with a million terms therefore crashed the backend while computing the error position for "multiple ORDER BY clauses not allowed". Parse analysis and raw_expression_tree_walker() already check the stack depth on such trees. Add a check_stack_depth() call, so that this fails with "stack depth limit exceeded" instead. --- src/backend/nodes/nodeFuncs.c | 4 ++++ src/test/regress/expected/errors.out | 14 ++++++++++++++ src/test/regress/sql/errors.sql | 10 ++++++++++ 3 files changed, 28 insertions(+) diff --git a/src/backend/nodes/nodeFuncs.c b/src/backend/nodes/nodeFuncs.c index 678b9a046ce..ab2e6c6a8f5 100644 --- a/src/backend/nodes/nodeFuncs.c +++ b/src/backend/nodes/nodeFuncs.c @@ -1398,6 +1398,10 @@ exprLocation(const Node *expr) if (expr == NULL) return -1; + + /* Guard against stack overflow due to overly complex expressions */ + check_stack_depth(); + switch (nodeTag(expr)) { case T_RangeVar: diff --git a/src/test/regress/expected/errors.out b/src/test/regress/expected/errors.out index 8c527474daf..96060745716 100644 --- a/src/test/regress/expected/errors.out +++ b/src/test/regress/expected/errors.out @@ -445,3 +445,17 @@ NULL); ERROR: syntax error at or near "NUL" LINE 16: ...L, id2 TEXT NOT NULL PRIMARY KEY, id3 INTEGER NOT NUL, id4 I... ^ +-- +-- Check that the error position of a deeply nested expression can be +-- computed without overrunning the stack. +-- +(SELECT 1 ORDER BY 1) ORDER BY 1+1; +ERROR: multiple ORDER BY clauses not allowed +LINE 1: (SELECT 1 ORDER BY 1) ORDER BY 1+1; + ^ +SELECT '(SELECT 1 ORDER BY 1) ORDER BY ' || repeat('1+', 10000) || '1' AS deep_query \gset +SET max_stack_depth = '100kB'; +:deep_query; +ERROR: stack depth limit exceeded +HINT: Increase the configuration parameter "max_stack_depth" (currently 100kB), after ensuring the platform's stack depth limit is adequate. +RESET max_stack_depth; diff --git a/src/test/regress/sql/errors.sql b/src/test/regress/sql/errors.sql index 52474e858d8..a0ae97294ec 100644 --- a/src/test/regress/sql/errors.sql +++ b/src/test/regress/sql/errors.sql @@ -368,3 +368,13 @@ INT4 UNIQUE NOT NULL); + +-- +-- Check that the error position of a deeply nested expression can be +-- computed without overrunning the stack. +-- +(SELECT 1 ORDER BY 1) ORDER BY 1+1; +SELECT '(SELECT 1 ORDER BY 1) ORDER BY ' || repeat('1+', 10000) || '1' AS deep_query \gset +SET max_stack_depth = '100kB'; +:deep_query; +RESET max_stack_depth; -- 2.56.1