diff --git a/src/pg_query.c b/src/pg_query.c index 90e9f0bb..6eefbd3d 100644 --- a/src/pg_query.c +++ b/src/pg_query.c @@ -21,6 +21,11 @@ #include #endif +#if defined(__EMSCRIPTEN__) +/* For emscripten_stack_get_end() */ +#include +#endif + #if defined(_WIN32) /* For GetCurrentThreadStackLimits(); port/win32.h already sets _WIN32_WINNT. */ #include @@ -28,6 +33,17 @@ #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; @@ -169,6 +185,9 @@ static char *get_lowest_stackaddr(void) pg_query_lowest_stackaddr = (char *) low; } +#elif defined(__EMSCRIPTEN__) + /* WebAssembly's stack is a region in linear memory that grows down */ + pg_query_lowest_stackaddr = (char *) emscripten_stack_get_end(); #elif defined(HAVE_PTHREAD) && defined(__linux__) { pthread_attr_t attr; @@ -253,9 +272,9 @@ static void set_max_stack_depth(void) if (new_limit <= 100) return; - /* Clamp at 2MB, like Postgres auto-detection logic. */ - if (new_limit > 2048) - new_limit = 2048; + /* 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; max_stack_depth = (int) new_limit; assign_max_stack_depth((int) new_limit, NULL);