postgres.git / summary / log / commit / refs
commit daafcbd1143f104a9feb493b60c68b9a764dfb97
Author: Tom Lane <tgl@sss.pgh.pa.us>
Commit: Noah Misch <noah@leadboat.com>
Date: Mon Nov 09 14:20:30 2026 +0000
First released in: 14.25, 15.20, 16.16, 17.12, 18.7, 19.0
Fix PL/Perl to cope with errors thrown from tied structures.
An error thrown from a tied array, hash, or scalar may occur while
PL/Perl is trying to return a function value, in which case we are
outside the call_sv() execution loop that would normally handle
trapping of Perl errors. That is problematic: if Perl doesn't think
it is inside an eval-like context, it will bleat on stderr and then
exit(); while if it does think that, it will longjmp out to some outer
level of Perl execution, which wreaks havoc. We need to keep Perl's
jmp_buf stack in sync with Postgres', so that we never have a situation
where one of those stack pointers points above the function level the
other stack was just used to jump out to.
The core idea of this fix is to replace PG_TRY blocks within PL/Perl
with "PG_PERL_TRY" blocks, which have fundamentally the same semantics
as PG_TRY, but establish new jmp_buf levels within both stacks and pop
both correctly at exit. If a Perl error is caught using Perl's stack,
we'll convert it to a Postgres error using logic similar to what
PL/Perl uses for the purpose elsewhere.
This simple core idea has some complications though. One big one
is that since PG_PERL_TRY adjusts the state of the current Perl
interpreter, we must make sure that we don't switch interpreters
partway through the block. Which the old code did freely.
To fix that without adding more TRY blocks than necessary, refactor
the contract between plperl_call_handler and its sub-handlers
(plperl_func_handler et al) so that we look up the target function and
switch to the associated interpreter before we enter the sub-handler.
I also spent a deal of effort on tightening the error-condition
guarantees for select_perl_context and plperl_init_interp, as per the
changes to their header comments. As they stood, it was really hard
to say anything about what state would be left behind after a failure
during Perl interpreter creation, which cascaded into not being able
to promise anything about what would happen in their callers.
Within PG_PERL_TRY, there are more problems. Aside from just pushing
a new jmp_buf stack level (handled by JMPENV_PUSH/JMPENV_POP), we must
see to it that if control does reach Perl_die then it will choose to
longjmp() rather than summarily exit(). At least in Perl 5.40, there
are two gating tests: PL_in_eval must be nonzero (preferably with the
EVAL_INEVAL bit set), and S_dopoptoeval must find a CXt_EVAL context
on the PERL_CONTEXT stack. We could hack PL_in_eval directly, but
there's no direct way to manipulate the context stack. The solution
used here is to execute OP_ENTERTRY and then (if a longjmp didn't
happen) OP_LEAVETRY. That requires manually saving/restoring PL_op,
as well as ERRSV, but otherwise seems to work fairly well.
Another interesting bit is that if possible, we create only one jmp_buf
struct and link it into both error stacks. It'd be cleaner to keep
the two mechanisms entirely separate, but that would require two
sigsetjmp calls in close proximity, which turns out to break clang's
optimizer quite thoroughly. We do get the small benefit of saving the
cycles that would go into a second sigsetjmp call. A complication is
that we need to be able to figure out whether a caught longjmp was
triggered by Perl or Postgres. We do that by adding some state in
elog.c so that we can tell whether the topmost error data is complete
or not. If it isn't, then the error was thrown by Perl. (An example
where this distinction matters is that the sv2cstr calls used in
plperl.c's own ereports could throw Perl errors, at a point where we
are still filling in a Postgres error.) Ideally this state would be
carried by a new flag in ErrorData, but to avoid an ABI break in
stable branches, hide it inside elog.c for now.
However, we can't use that trick on MinGW-64, because there we use
gcc's __builtin_setjmp() while Perl uses MinGW's plain setjmp().
So in that case, resort to managing the jmp_buf stacks separately.
Reported-by: Ngoc Trần <anbas1342@gmail.com>
Reported-by: Anthropic OSS program
Author: Tom Lane <tgl@sss.pgh.pa.us>
Backpatch-through: 14
Security: CVE-2026-116326
src/backend/utils/error/elog.c | 22 ++
src/include/c.h | 1 +
src/include/utils/elog.h | 4 +
src/pl/plperl/expected/plperl_tied.out | 43 ++++
src/pl/plperl/plperl.c | 399 +++++++++++++++++++--------------
src/pl/plperl/plperl.h | 283 +++++++++++++++++++++++
src/pl/plperl/sql/plperl_tied.sql | 31 +++
7 files changed, 615 insertions(+), 168 deletions(-)
diff --git a/src/backend/utils/error/elog.c b/src/backend/utils/error/elog.c
index b9d2c96b97a..e215ed053ff 100644
--- a/src/backend/utils/error/elog.c
+++ b/src/backend/utils/error/elog.c
@@ -155,6 +155,9 @@ static HANDLE backtrace_process = NULL;
static ErrorData errordata[ERRORDATA_STACK_SIZE];
+/* These flags should migrate into ErrorData, but for now keep them here */
+static bool errordata_complete[ERRORDATA_STACK_SIZE];
+
static int errordata_stack_depth = -1; /* index of topmost active frame */
static int recursion_depth = 0; /* to detect actual recursion */
@@ -521,6 +524,9 @@ errfinish(const char *filename, int lineno, const char *funcname)
econtext = econtext->previous)
econtext->callback(econtext->arg);
+ /* The data about this error is now fully collected */
+ errordata_complete[errordata_stack_depth] = true;
+
/*
* If ERROR (not more nor less) we pass it off to the current handler.
* Printing it and popping the stack is the responsibility of the handler.
@@ -786,6 +792,7 @@ get_error_stack_entry(void)
/* Initialize error frame to all zeroes/NULLs */
edata = &errordata[errordata_stack_depth];
memset(edata, 0, sizeof(ErrorData));
+ errordata_complete[errordata_stack_depth] = false;
/* Save errno immediately to ensure error parameter eval can't change it */
edata->saved_errno = errno;
@@ -2189,6 +2196,9 @@ ReThrowError(ErrorData *edata)
/* Reset the assoc_context to be ErrorContext */
newedata->assoc_context = ErrorContext;
+ /* Mark the entry finished, assuming that it was so before throwing */
+ errordata_complete[errordata_stack_depth] = true;
+
recursion_depth--;
PG_RE_THROW();
}
@@ -2300,6 +2310,18 @@ GetErrorContextStack(void)
}
+/*
+ * HaveCompleteError --- do we have a complete error that's being reported?
+ */
+bool
+HaveCompleteError(void)
+{
+ if (errordata_stack_depth >= 0)
+ return errordata_complete[errordata_stack_depth];
+ return false;
+}
+
+
/*
* Initialization of error output file
*/
diff --git a/src/include/c.h b/src/include/c.h
index 944c851b3c3..4bbb0071289 100644
--- a/src/include/c.h
+++ b/src/include/c.h
@@ -1626,6 +1626,7 @@ typedef struct pg_signal_info
* setjmp. We now support the case only on Windows. However, it seems
* that MinGW-64 has some longstanding issues in its setjmp support,
* so on that toolchain we cheat and use gcc's builtins.
+ * If you change this, see also PG_PERL_TRY in plperl.h.
*/
#ifdef WIN32
#ifdef __MINGW64__
diff --git a/src/include/utils/elog.h b/src/include/utils/elog.h
index 6ae376ba001..bc38d154ed4 100644
--- a/src/include/utils/elog.h
+++ b/src/include/utils/elog.h
@@ -383,6 +383,9 @@ extern PGDLLIMPORT ErrorContextCallback *error_context_stack;
* statements are required. The optional suffix may contain any character
* that's allowed in a variable name. The suffix, if specified, must be the
* same within each component macro of the given PG_TRY() statement.
+ *
+ * If you modify these macros, check whether similar modifications are
+ * needed in plperl's PG_PERL_TRY and friends.
*----------
*/
#define PG_TRY(...) \
@@ -475,6 +478,7 @@ extern void ThrowErrorData(ErrorData *edata);
pg_noreturn extern void pg_re_throw(void);
extern char *GetErrorContextStack(void);
+extern bool HaveCompleteError(void);
/* Hook for intercepting messages before they are sent to the server log */
typedef void (*emit_log_hook_type) (ErrorData *edata);
diff --git a/src/pl/plperl/expected/plperl_tied.out b/src/pl/plperl/expected/plperl_tied.out
index 6d85dd855f2..4105f12063d 100644
--- a/src/pl/plperl/expected/plperl_tied.out
+++ b/src/pl/plperl/expected/plperl_tied.out
@@ -130,3 +130,46 @@ SELECT i, v FROM tied_trigger_test;
1 | from_tie
(1 row)
+-- Verify that we can cope with errors thrown within get magic.
+DO $$
+{
+ package PLPerlTiedHash;
+ sub TIEHASH { bless {}, $_[0] }
+ sub STORE { $_[0]{$_[1]} = $_[2] }
+ sub FETCH { die("tied hash fetch failure"); $_[0]{$_[1]} }
+ sub FIRSTKEY { my $a = keys %{$_[0]}; each %{$_[0]} }
+ sub NEXTKEY { each %{$_[0]} }
+
+ package PLPerlTiedArray;
+ sub TIEARRAY { bless [], $_[0] }
+ sub STORE { $_[0][$_[1]] = $_[2] }
+ sub FETCH { die("tied array fetch failure"); $_[0][$_[1]] }
+ sub FETCHSIZE { scalar @{$_[0]} }
+
+ package PLPerlTiedScalar;
+ sub TIESCALAR { my $s; bless \$s, $_[0] }
+ sub STORE { ${$_[0]} = $_[1] }
+ sub FETCH { die("tied scalar fetch failure"); ${$_[0]} }
+}
+$$ LANGUAGE plperl;
+SELECT * FROM tied_setof();
+ERROR: tied array fetch failure at line 13.
+CONTEXT: PL/Perl function "tied_setof"
+SELECT tied_scalar();
+ERROR: tied scalar fetch failure at line 19.
+CONTEXT: PL/Perl function "tied_scalar"
+SELECT tied_composite();
+ERROR: tied hash fetch failure at line 6.
+CONTEXT: PL/Perl function "tied_composite"
+SELECT tied_int_array();
+ERROR: tied array fetch failure at line 13.
+CONTEXT: PL/Perl function "tied_int_array"
+SELECT * FROM tied_scalar_setof();
+ERROR: tied scalar fetch failure at line 19.
+CONTEXT: PL/Perl function "tied_scalar_setof"
+SELECT tied_scalar_int_array();
+ERROR: tied scalar fetch failure at line 19.
+CONTEXT: PL/Perl function "tied_scalar_int_array"
+INSERT INTO tied_trigger_test (i, v) VALUES (2, 'orig');
+ERROR: tied scalar fetch failure at line 19.
+CONTEXT: PL/Perl function "tied_modify"
diff --git a/src/pl/plperl/plperl.c b/src/pl/plperl/plperl.c
index d62f5b46eca..8a48743fb2b 100644
--- a/src/pl/plperl/plperl.c
+++ b/src/pl/plperl/plperl.c
@@ -252,9 +252,9 @@ static void plperl_destroy_interp(PerlInterpreter **interp);
static void plperl_fini(int code, Datum arg);
static void set_interp_require(bool trusted);
-static Datum plperl_func_handler(PG_FUNCTION_ARGS);
-static Datum plperl_trigger_handler(PG_FUNCTION_ARGS);
-static void plperl_event_trigger_handler(PG_FUNCTION_ARGS);
+static Datum plperl_func_handler(plperl_proc_desc *prodesc, PG_FUNCTION_ARGS);
+static Datum plperl_trigger_handler(plperl_proc_desc *prodesc, PG_FUNCTION_ARGS);
+static void plperl_event_trigger_handler(plperl_proc_desc *prodesc, PG_FUNCTION_ARGS);
static void free_plperl_function(plperl_proc_desc *prodesc);
@@ -333,10 +333,10 @@ _PG_init(void)
/*
* Be sure we do initialization only once.
*
- * If initialization fails due to, e.g., plperl_init_interp() throwing an
- * exception, then we'll return here on the next usage and the user will
- * get a rather cryptic: ERROR: attempt to redefine parameter
- * "plperl.use_strict"
+ * If initialization fails, we'll return here on the next usage and the
+ * user will get a rather cryptic: ERROR: attempt to redefine parameter
+ * "plperl.use_strict". We minimize the risk of that by not treating
+ * plperl_init_interp() as part of required initialization.
*/
static bool inited = false;
HASHCTL hash_ctl;
@@ -428,12 +428,20 @@ _PG_init(void)
*/
PLPERL_SET_OPMASK(plperl_opmask);
+ /* Once the hash tables are made, we can arrange for cleanup */
+ on_proc_exit(plperl_fini, 0);
+
+ /*
+ * We can now consider initialization complete. If plperl_init_interp
+ * fails, we'll leave plperl_held_interp NULL; but we can recover from
+ * that later (if MULTIPLICITY is set, which it is on most builds).
+ */
+ inited = true;
+
/*
* Create the first Perl interpreter, but only partially initialize it.
*/
plperl_held_interp = plperl_init_interp();
-
- inited = true;
}
@@ -499,6 +507,11 @@ plperl_fini(int code, Datum arg)
/*
* Select and activate an appropriate Perl interpreter.
+ *
+ * On success, the selected interpreter is Perl's active interpreter and is
+ * referenced by plperl_active_interp. On failure, we'll throw a Postgres
+ * error and preserve Perl's interpreter setting; plperl_active_interp won't
+ * change either.
*/
static void
select_perl_context(bool trusted)
@@ -507,6 +520,7 @@ select_perl_context(bool trusted)
plperl_interp_desc *interp_desc;
bool found;
PerlInterpreter *interp = NULL;
+ void *old_perl_context = PERL_GET_CONTEXT;
/* Find or create the interpreter hashtable entry for this userid */
if (trusted)
@@ -555,39 +569,16 @@ select_perl_context(bool trusted)
interp = plperl_held_interp;
/*
- * Reset the plperl_held_interp pointer first; if we fail during init
- * we don't want to try again with the partially-initialized interp.
+ * Reset the plperl_held_interp pointer now; if we fail during init we
+ * don't want to try again with the partially-initialized interp.
*/
plperl_held_interp = NULL;
-
- if (trusted)
- plperl_trusted_init();
- else
- plperl_untrusted_init();
-
- /* successfully initialized, so arrange for cleanup */
- on_proc_exit(plperl_fini, 0);
}
else
{
#ifdef MULTIPLICITY
-
- /*
- * plperl_init_interp will change Perl's idea of the active
- * interpreter. Reset plperl_active_interp temporarily, so that if we
- * hit an error partway through here, we'll make sure to switch back
- * to a non-broken interpreter before running any other Perl
- * functions.
- */
- plperl_active_interp = NULL;
-
- /* Now build the new interpreter */
+ /* Build the new interpreter */
interp = plperl_init_interp();
-
- if (trusted)
- plperl_trusted_init();
- else
- plperl_untrusted_init();
#else
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
@@ -595,27 +586,50 @@ select_perl_context(bool trusted)
#endif
}
- set_interp_require(trusted);
-
/*
- * Since the timing of first use of PL/Perl can't be predicted, any
- * database interaction during initialization is problematic. Including,
- * but not limited to, security definer issues. So we only enable access
- * to the database AFTER on_*_init code has run. See
- * http://archives.postgresql.org/pgsql-hackers/2010-01/msg02669.php
+ * Now we have an active Perl interpreter. If any error occurs while
+ * finishing its initialization, we need to restore Perl's previous
+ * interpreter setting, just as in plperl_init_interp(). Note that we'll
+ * then leak the partially-initialized interpreter; not clear if it's
+ * worth trying to clean it up.
*/
{
dTHX;
- newXS("PostgreSQL::InServer::SPI::bootstrap",
- boot_PostgreSQL__InServer__SPI, __FILE__);
+ PG_PERL_TRY();
+ {
+ /* Finish initialization of the new interpreter */
+ if (trusted)
+ plperl_trusted_init();
+ else
+ plperl_untrusted_init();
- eval_pv("PostgreSQL::InServer::SPI::bootstrap()", FALSE);
- if (SvTRUE(ERRSV))
- ereport(ERROR,
- (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
- errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
- errcontext("while executing PostgreSQL::InServer::SPI::bootstrap")));
+ set_interp_require(trusted);
+
+ /*
+ * Since the timing of first use of PL/Perl can't be predicted,
+ * any database interaction during initialization is problematic.
+ * Including, but not limited to, security definer issues. So we
+ * only enable access to the database AFTER on_*_init code has
+ * run. See
+ * http://archives.postgresql.org/pgsql-hackers/2010-01/msg02669.php
+ */
+ newXS("PostgreSQL::InServer::SPI::bootstrap",
+ boot_PostgreSQL__InServer__SPI, __FILE__);
+
+ eval_pv("PostgreSQL::InServer::SPI::bootstrap()", FALSE);
+ if (SvTRUE(ERRSV))
+ ereport(ERROR,
+ (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
+ errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
+ errcontext("while executing PostgreSQL::InServer::SPI::bootstrap")));
+ }
+ PG_PERL_CATCH();
+ {
+ PERL_SET_CONTEXT(old_perl_context);
+ PG_RE_THROW();
+ }
+ PG_PERL_END_TRY();
}
/* Fully initialized, so mark the hashtable entry valid */
@@ -630,6 +644,8 @@ select_perl_context(bool trusted)
*
* A call with NULL does nothing. This is so that "restoring" to a previously
* null state of plperl_active_interp doesn't result in useless thrashing.
+ *
+ * We assume this cannot fail.
*/
static void
activate_interpreter(plperl_interp_desc *interp_desc)
@@ -647,6 +663,10 @@ activate_interpreter(plperl_interp_desc *interp_desc)
/*
* Create a new Perl interpreter.
*
+ * On success, the new interpreter is Perl's active interpreter. On failure,
+ * we'll throw a Postgres error and preserve Perl's interpreter setting.
+ * Either way, this doesn't change plperl_active_interp.
+ *
* We initialize the interpreter as far as we can without knowing whether
* it will become a trusted or untrusted interpreter; in particular, the
* plperl.on_init code will get executed. Later, either plperl_trusted_init
@@ -656,7 +676,7 @@ static PerlInterpreter *
plperl_init_interp(void)
{
PerlInterpreter *plperl;
-
+ void *old_perl_context = PERL_GET_CONTEXT;
static char *embedding[3 + 2] = {
"", "-e", PLC_PERLBOOT
};
@@ -756,17 +776,25 @@ plperl_init_interp(void)
if (!plperl)
elog(ERROR, "could not allocate Perl interpreter");
+ /* Establish the new interpreter as Perl's active interpreter */
PERL_SET_CONTEXT(plperl);
- perl_construct(plperl);
/*
- * Run END blocks in perl_destruct instead of perl_run. Note that dTHX
- * loads up a pointer to the current interpreter, so we have to postpone
- * it to here rather than put it at the function head.
+ * Use a PG_TRY block to ensure that PERL_SET_CONTEXT() gets undone on
+ * failure. Ideally we'd use PG_PERL_TRY, but that doesn't quite work
+ * because perl_construct() overwrites PL_top_env. So instead we must
+ * trust that these Perl functions won't longjmp. Also note that we can't
+ * set up dTHX any earlier than here, because it gets its pointer to the
+ * current interpreter from PERL_GET_CONTEXT.
*/
+ PG_TRY();
{
dTHX;
+ /* Finish constructing the interpreter */
+ perl_construct(plperl);
+
+ /* Run END blocks in perl_destruct instead of perl_run */
PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
/*
@@ -815,6 +843,19 @@ plperl_init_interp(void)
PLPERL_RESTORE_LOCALE(LC_TIME, save_time);
#endif
}
+ PG_CATCH();
+ {
+ PERL_SET_CONTEXT(old_perl_context);
+#ifdef PLPERL_RESTORE_LOCALE
+ PLPERL_RESTORE_LOCALE(LC_COLLATE, save_collate);
+ PLPERL_RESTORE_LOCALE(LC_CTYPE, save_ctype);
+ PLPERL_RESTORE_LOCALE(LC_MONETARY, save_monetary);
+ PLPERL_RESTORE_LOCALE(LC_NUMERIC, save_numeric);
+ PLPERL_RESTORE_LOCALE(LC_TIME, save_time);
+#endif
+ PG_RE_THROW();
+ }
+ PG_END_TRY();
return plperl;
}
@@ -1858,16 +1899,61 @@ plperl_call_handler(PG_FUNCTION_ARGS)
PG_TRY();
{
+ plperl_proc_desc *prodesc;
+ bool is_trigger = false;
+ bool is_event_trigger = false;
+ ErrorContextCallback pl_error_context;
+
current_call_data = &this_call_data;
+
if (CALLED_AS_TRIGGER(fcinfo))
- retval = plperl_trigger_handler(fcinfo);
+ is_trigger = true;
else if (CALLED_AS_EVENT_TRIGGER(fcinfo))
+ is_event_trigger = true;
+
+ /* Find and compile the correct function */
+ prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid,
+ is_trigger, is_event_trigger);
+ this_call_data.prodesc = prodesc;
+ increment_prodesc_refcount(prodesc);
+
+ /* Now we can select the correct interpreter */
+ activate_interpreter(prodesc->interp);
+
+ /* Set a callback for error reporting */
+ pl_error_context.callback = plperl_exec_callback;
+ pl_error_context.previous = error_context_stack;
+ pl_error_context.arg = prodesc->proname;
+ error_context_stack = &pl_error_context;
+
+ /*
+ * Trap any Perl error thrown within the execution handlers, and
+ * convert to a Postgres error. We can't set this up till we have the
+ * correct interpreter, so it requires an additional level of TRY.
+ */
{
- plperl_event_trigger_handler(fcinfo);
- retval = (Datum) 0;
+ dTHX;
+
+ PG_PERL_TRY(2);
+ {
+ if (is_trigger)
+ retval = plperl_trigger_handler(prodesc, fcinfo);
+ else if (is_event_trigger)
+ {
+ plperl_event_trigger_handler(prodesc, fcinfo);
+ retval = (Datum) 0;
+ }
+ else
+ retval = plperl_func_handler(prodesc, fcinfo);
+ }
+ PG_PERL_FINALLY(2);
+ {
+ }
+ PG_PERL_END_TRY(2);
}
- else
- retval = plperl_func_handler(fcinfo);
+
+ /* Restore the previous error callback */
+ error_context_stack = pl_error_context.previous;
}
PG_FINALLY();
{
@@ -1937,36 +2023,42 @@ plperl_inline_handler(PG_FUNCTION_ARGS)
this_call_data.prodesc = &desc;
/* we do not bother with refcounting the fake prodesc */
- PG_TRY();
+ /* Select the correct Perl interpreter */
+ select_perl_context(desc.lanpltrusted);
+
+ /* Use PG_PERL_TRY to ensure the previous interpreter gets restored */
{
- SV *perlret;
+ dTHX;
- current_call_data = &this_call_data;
+ PG_PERL_TRY();
+ {
+ SV *perlret;
- SPI_connect_ext(codeblock->atomic ? 0 : SPI_OPT_NONATOMIC);
+ current_call_data = &this_call_data;
- select_perl_context(desc.lanpltrusted);
+ SPI_connect_ext(codeblock->atomic ? 0 : SPI_OPT_NONATOMIC);
- plperl_create_sub(&desc, codeblock->source_text, 0);
+ plperl_create_sub(&desc, codeblock->source_text, 0);
- if (!desc.reference) /* can this happen? */
- elog(ERROR, "could not create internal procedure for anonymous code block");
+ if (!desc.reference) /* can this happen? */
+ elog(ERROR, "could not create internal procedure for anonymous code block");
- perlret = plperl_call_perl_func(&desc, fake_fcinfo);
+ perlret = plperl_call_perl_func(&desc, fake_fcinfo);
- SvREFCNT_dec_current(perlret);
+ SvREFCNT_dec_current(perlret);
- if (SPI_finish() != SPI_OK_FINISH)
- elog(ERROR, "SPI_finish() failed");
- }
- PG_FINALLY();
- {
- if (desc.reference)
- SvREFCNT_dec_current(desc.reference);
- current_call_data = save_call_data;
- activate_interpreter(oldinterp);
+ if (SPI_finish() != SPI_OK_FINISH)
+ elog(ERROR, "SPI_finish() failed");
+ }
+ PG_PERL_FINALLY();
+ {
+ if (desc.reference)
+ SvREFCNT_dec_current(desc.reference);
+ current_call_data = save_call_data;
+ activate_interpreter(oldinterp);
+ }
+ PG_PERL_END_TRY();
}
- PG_END_TRY();
error_context_stack = pl_error_context.previous;
@@ -2394,14 +2486,12 @@ plperl_call_perl_event_trigger_func(plperl_proc_desc *desc,
}
static Datum
-plperl_func_handler(PG_FUNCTION_ARGS)
+plperl_func_handler(plperl_proc_desc *prodesc, PG_FUNCTION_ARGS)
{
bool nonatomic;
- plperl_proc_desc *prodesc;
SV *perlret;
Datum retval = 0;
ReturnSetInfo *rsi;
- ErrorContextCallback pl_error_context;
nonatomic = fcinfo->context &&
IsA(fcinfo->context, CallContext) &&
@@ -2409,16 +2499,6 @@ plperl_func_handler(PG_FUNCTION_ARGS)
SPI_connect_ext(nonatomic ? SPI_OPT_NONATOMIC : 0);
- prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, false, false);
- current_call_data->prodesc = prodesc;
- increment_prodesc_refcount(prodesc);
-
- /* Set a callback for error reporting */
- pl_error_context.callback = plperl_exec_callback;
- pl_error_context.previous = error_context_stack;
- pl_error_context.arg = prodesc->proname;
- error_context_stack = &pl_error_context;
-
rsi = (ReturnSetInfo *) fcinfo->resultinfo;
if (prodesc->fn_retisset)
@@ -2435,8 +2515,6 @@ plperl_func_handler(PG_FUNCTION_ARGS)
errmsg("materialize mode required, but it is not allowed in this context")));
}
- activate_interpreter(prodesc->interp);
-
perlret = plperl_call_perl_func(prodesc, fcinfo);
/************************************************************
@@ -2504,9 +2582,6 @@ plperl_func_handler(PG_FUNCTION_ARGS)
rsi->isDone = ExprEndResult;
}
- /* Restore the previous error callback */
- error_context_stack = pl_error_context.previous;
-
SvREFCNT_dec_current(perlret);
return retval;
@@ -2514,15 +2589,13 @@ plperl_func_handler(PG_FUNCTION_ARGS)
static Datum
-plperl_trigger_handler(PG_FUNCTION_ARGS)
+plperl_trigger_handler(plperl_proc_desc *prodesc, PG_FUNCTION_ARGS)
{
dTHX;
- plperl_proc_desc *prodesc;
SV *perlret;
Datum retval;
SV *svTD;
HV *hvTD;
- ErrorContextCallback pl_error_context;
TriggerData *tdata;
int rc PG_USED_FOR_ASSERTS_ONLY;
@@ -2534,19 +2607,6 @@ plperl_trigger_handler(PG_FUNCTION_ARGS)
rc = SPI_register_trigger_data(tdata);
Assert(rc >= 0);
- /* Find or compile the function */
- prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, true, false);
- current_call_data->prodesc = prodesc;
- increment_prodesc_refcount(prodesc);
-
- /* Set a callback for error reporting */
- pl_error_context.callback = plperl_exec_callback;
- pl_error_context.previous = error_context_stack;
- pl_error_context.arg = prodesc->proname;
- error_context_stack = &pl_error_context;
-
- activate_interpreter(prodesc->interp);
-
svTD = plperl_trigger_build_args(fcinfo);
perlret = plperl_call_perl_trigger_func(prodesc, fcinfo, svTD);
hvTD = (HV *) SvRV(svTD);
@@ -2617,9 +2677,6 @@ plperl_trigger_handler(PG_FUNCTION_ARGS)
pfree(tmp);
}
- /* Restore the previous error callback */
- error_context_stack = pl_error_context.previous;
-
SvREFCNT_dec_current(svTD);
if (perlret)
SvREFCNT_dec_current(perlret);
@@ -2629,37 +2686,19 @@ plperl_trigger_handler(PG_FUNCTION_ARGS)
static void
-plperl_event_trigger_handler(PG_FUNCTION_ARGS)
+plperl_event_trigger_handler(plperl_proc_desc *prodesc, PG_FUNCTION_ARGS)
{
- plperl_proc_desc *prodesc;
SV *svTD;
- ErrorContextCallback pl_error_context;
/* Connect to SPI manager */
SPI_connect();
- /* Find or compile the function */
- prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, false, true);
- current_call_data->prodesc = prodesc;
- increment_prodesc_refcount(prodesc);
-
- /* Set a callback for error reporting */
- pl_error_context.callback = plperl_exec_callback;
- pl_error_context.previous = error_context_stack;
- pl_error_context.arg = prodesc->proname;
- error_context_stack = &pl_error_context;
-
- activate_interpreter(prodesc->interp);
-
svTD = plperl_event_trigger_build_args(fcinfo);
plperl_call_perl_event_trigger_func(prodesc, fcinfo, svTD);
if (SPI_finish() != SPI_OK_FINISH)
elog(ERROR, "SPI_finish() failed");
- /* Restore the previous error callback */
- error_context_stack = pl_error_context.previous;
-
SvREFCNT_dec_current(svTD);
}
@@ -2711,6 +2750,11 @@ free_plperl_function(plperl_proc_desc *prodesc)
}
+/*
+ * Find or create a plperl_proc_desc structure for the given function.
+ *
+ * We expect this not to allow Perl to throw an error out to callers.
+ */
static plperl_proc_desc *
compile_plperl_function(Oid fn_oid, bool is_trigger, bool is_event_trigger)
{
@@ -2940,9 +2984,24 @@ compile_plperl_function(Oid fn_oid, bool is_trigger, bool is_event_trigger)
prodesc->interp = plperl_active_interp;
- plperl_create_sub(prodesc, proc_source, fn_oid);
+ /*
+ * We must ensure we have an active TRY block in the target
+ * interpreter (in case a Perl error is thrown in plperl_create_sub),
+ * and that we switch back to the caller's interpreter before exiting.
+ */
+ {
+ dTHX;
- activate_interpreter(oldinterp);
+ PG_PERL_TRY(2);
+ {
+ plperl_create_sub(prodesc, proc_source, fn_oid);
+ }
+ PG_PERL_FINALLY(2);
+ {
+ activate_interpreter(oldinterp);
+ }
+ PG_PERL_END_TRY(2);
+ }
pfree(proc_source);
@@ -2975,9 +3034,6 @@ compile_plperl_function(Oid fn_oid, bool is_trigger, bool is_event_trigger)
else if (proc_cxt)
MemoryContextDelete(proc_cxt);
- /* Be sure to restore the previous interpreter, too, for luck */
- activate_interpreter(oldinterp);
-
PG_RE_THROW();
}
PG_END_TRY();
@@ -3132,6 +3188,7 @@ check_spi_usage_allowed(void)
HV *
plperl_spi_exec(char *query, int limit)
{
+ dTHX;
HV *ret_hv;
/*
@@ -3147,7 +3204,7 @@ plperl_spi_exec(char *query, int limit)
/* Want to run inside function's memory context */
MemoryContextSwitchTo(oldcontext);
- PG_TRY();
+ PG_PERL_TRY();
{
int spi_rv;
@@ -3163,7 +3220,7 @@ plperl_spi_exec(char *query, int limit)
MemoryContextSwitchTo(oldcontext);
CurrentResourceOwner = oldowner;
}
- PG_CATCH();
+ PG_PERL_CATCH();
{
ErrorData *edata;
@@ -3183,7 +3240,7 @@ plperl_spi_exec(char *query, int limit)
/* Can't get here, but keep compiler quiet */
return NULL;
}
- PG_END_TRY();
+ PG_PERL_END_TRY();
return ret_hv;
}
@@ -3244,15 +3301,16 @@ plperl_spi_execute_fetch_result(SPITupleTable *tuptable, uint64 processed,
void
plperl_return_next(SV *sv)
{
+ dTHX;
MemoryContext oldcontext = CurrentMemoryContext;
check_spi_usage_allowed();
- PG_TRY();
+ PG_PERL_TRY();
{
plperl_return_next_internal(sv);
}
- PG_CATCH();
+ PG_PERL_CATCH();
{
ErrorData *edata;
@@ -3264,7 +3322,7 @@ plperl_return_next(SV *sv)
/* Punt the error to Perl */
croak_cstr(edata->message);
}
- PG_END_TRY();
+ PG_PERL_END_TRY();
}
/*
@@ -3405,6 +3463,7 @@ plperl_return_next_internal(SV *sv)
SV *
plperl_spi_query(char *query)
{
+ dTHX;
SV *cursor;
/*
@@ -3420,7 +3479,7 @@ plperl_spi_query(char *query)
/* Want to run inside function's memory context */
MemoryContextSwitchTo(oldcontext);
- PG_TRY();
+ PG_PERL_TRY();
{
SPIPlanPtr plan;
Portal portal;
@@ -3448,7 +3507,7 @@ plperl_spi_query(char *query)
MemoryContextSwitchTo(oldcontext);
CurrentResourceOwner = oldowner;
}
- PG_CATCH();
+ PG_PERL_CATCH();
{
ErrorData *edata;
@@ -3468,7 +3527,7 @@ plperl_spi_query(char *query)
/* Can't get here, but keep compiler quiet */
return NULL;
}
- PG_END_TRY();
+ PG_PERL_END_TRY();
return cursor;
}
@@ -3477,6 +3536,7 @@ plperl_spi_query(char *query)
SV *
plperl_spi_fetchrow(char *cursor)
{
+ dTHX;
SV *row;
/*
@@ -3492,9 +3552,8 @@ plperl_spi_fetchrow(char *cursor)
/* Want to run inside function's memory context */
MemoryContextSwitchTo(oldcontext);
- PG_TRY();
+ PG_PERL_TRY();
{
- dTHX;
Portal p = SPI_cursor_find(cursor);
if (!p)
@@ -3524,7 +3583,7 @@ plperl_spi_fetchrow(char *cursor)
MemoryContextSwitchTo(oldcontext);
CurrentResourceOwner = oldowner;
}
- PG_CATCH();
+ PG_PERL_CATCH();
{
ErrorData *edata;
@@ -3544,7 +3603,7 @@ plperl_spi_fetchrow(char *cursor)
/* Can't get here, but keep compiler quiet */
return NULL;
}
- PG_END_TRY();
+ PG_PERL_END_TRY();
return row;
}
@@ -3568,6 +3627,7 @@ plperl_spi_cursor_close(char *cursor)
SV *
plperl_spi_prepare(char *query, int argc, SV **argv)
{
+ dTHX;
volatile SPIPlanPtr plan = NULL;
volatile MemoryContext plan_cxt = NULL;
plperl_query_desc *volatile qdesc = NULL;
@@ -3583,7 +3643,7 @@ plperl_spi_prepare(char *query, int argc, SV **argv)
BeginInternalSubTransaction(NULL);
MemoryContextSwitchTo(oldcontext);
- PG_TRY();
+ PG_PERL_TRY();
{
CHECK_FOR_INTERRUPTS();
@@ -3675,7 +3735,7 @@ plperl_spi_prepare(char *query, int argc, SV **argv)
MemoryContextSwitchTo(oldcontext);
CurrentResourceOwner = oldowner;
}
- PG_CATCH();
+ PG_PERL_CATCH();
{
ErrorData *edata;
@@ -3705,7 +3765,7 @@ plperl_spi_prepare(char *query, int argc, SV **argv)
/* Can't get here, but keep compiler quiet */
return NULL;
}
- PG_END_TRY();
+ PG_PERL_END_TRY();
/************************************************************
* Return the query's hash key to the caller.
@@ -3716,6 +3776,7 @@ plperl_spi_prepare(char *query, int argc, SV **argv)
HV *
plperl_spi_exec_prepared(char *query, HV *attr, int argc, SV **argv)
{
+ dTHX;
HV *ret_hv;
SV **sv;
int i,
@@ -3739,10 +3800,8 @@ plperl_spi_exec_prepared(char *query, HV *attr, int argc, SV **argv)
/* Want to run inside function's memory context */
MemoryContextSwitchTo(oldcontext);
- PG_TRY();
+ PG_PERL_TRY();
{
- dTHX;
-
/************************************************************
* Fetch the saved plan descriptor, see if it's o.k.
************************************************************/
@@ -3815,7 +3874,7 @@ plperl_spi_exec_prepared(char *query, HV *attr, int argc, SV **argv)
MemoryContextSwitchTo(oldcontext);
CurrentResourceOwner = oldowner;
}
- PG_CATCH();
+ PG_PERL_CATCH();
{
ErrorData *edata;
@@ -3835,7 +3894,7 @@ plperl_spi_exec_prepared(char *query, HV *attr, int argc, SV **argv)
/* Can't get here, but keep compiler quiet */
return NULL;
}
- PG_END_TRY();
+ PG_PERL_END_TRY();
return ret_hv;
}
@@ -3843,6 +3902,7 @@ plperl_spi_exec_prepared(char *query, HV *attr, int argc, SV **argv)
SV *
plperl_spi_query_prepared(char *query, int argc, SV **argv)
{
+ dTHX;
int i;
char *nulls;
Datum *argvalues;
@@ -3864,7 +3924,7 @@ plperl_spi_query_prepared(char *query, int argc, SV **argv)
/* Want to run inside function's memory context */
MemoryContextSwitchTo(oldcontext);
- PG_TRY();
+ PG_PERL_TRY();
{
/************************************************************
* Fetch the saved plan descriptor, see if it's o.k.
@@ -3933,7 +3993,7 @@ plperl_spi_query_prepared(char *query, int argc, SV **argv)
MemoryContextSwitchTo(oldcontext);
CurrentResourceOwner = oldowner;
}
- PG_CATCH();
+ PG_PERL_CATCH();
{
ErrorData *edata;
@@ -3953,7 +4013,7 @@ plperl_spi_query_prepared(char *query, int argc, SV **argv)
/* Can't get here, but keep compiler quiet */
return NULL;
}
- PG_END_TRY();
+ PG_PERL_END_TRY();
return cursor;
}
@@ -3996,6 +4056,7 @@ plperl_spi_commit(void)
check_spi_usage_allowed();
+ /* Shouldn't need PG_PERL_TRY here; no Perl functions called within TRY */
PG_TRY();
{
SPI_commit();
@@ -4022,6 +4083,7 @@ plperl_spi_rollback(void)
check_spi_usage_allowed();
+ /* Shouldn't need PG_PERL_TRY here; no Perl functions called within TRY */
PG_TRY();
{
SPI_rollback();
@@ -4055,6 +4117,7 @@ plperl_spi_rollback(void)
void
plperl_util_elog(int level, SV *msg)
{
+ dTHX;
MemoryContext oldcontext = CurrentMemoryContext;
char *volatile cmsg = NULL;
@@ -4063,13 +4126,13 @@ plperl_util_elog(int level, SV *msg)
* safe to allow even in the contexts that that function rejects.
*/
- PG_TRY();
+ PG_PERL_TRY();
{
cmsg = sv2cstr(msg);
elog(level, "%s", cmsg);
pfree(cmsg);
}
- PG_CATCH();
+ PG_PERL_CATCH();
{
ErrorData *edata;
@@ -4084,7 +4147,7 @@ plperl_util_elog(int level, SV *msg)
/* Punt the error to Perl */
croak_cstr(edata->message);
}
- PG_END_TRY();
+ PG_PERL_END_TRY();
}
/*
diff --git a/src/pl/plperl/plperl.h b/src/pl/plperl/plperl.h
index 9e899b8b2e2..8f4219bd55c 100644
--- a/src/pl/plperl/plperl.h
+++ b/src/pl/plperl/plperl.h
@@ -268,4 +268,287 @@ croak_cstr(const char *str)
#endif /* croak_sv */
}
+/*
+ * These macros provide a version of the PG_TRY facility that can catch
+ * Perl's longjmps as well as our own. Use these, not plain PG_TRY, in any
+ * code that can invoke Perl functions, to ensure that the two jmp_buf stacks
+ * remain consistent. Without this, any Perl function that is called directly
+ * (rather than via a runops loop such as call_sv's) will wreak havoc if it
+ * throws an error.
+ *
+ * These must be invoked within the scope of a dTHX declaration. That
+ * declaration controls which interpreter we manipulate the jmp_buf stack of.
+ *
+ * Like PG_TRY, we accept a __VA_ARGS__ string to append to local variable
+ * names, but that's of limited use since we can't modify the "cur_env" name
+ * declared by dJMPENV; so you can't nest these without drawing compiler
+ * warnings about shadowed variables. However, it is helpful in some places
+ * to nest PG_PERL_TRY within PG_TRY, so we make sure not to conflict with
+ * the names that PG_TRY declares. (Beware of nesting them too closely,
+ * for fear of breaking clang. It does seem to work so long as there's a
+ * nontrivial amount of code in between.)
+ *
+ * Since nothing in life is easy, we need two implementations of this idea.
+ * They are equivalent from the outside.
+ */
+
+#if !(defined(WIN32) && defined(__MINGW64__))
+
+/*
+ * This is our preferred implementation, which we use everywhere but MinGW-64.
+ * It depends on the assumption that Perl is built with the same sigsetjmp()
+ * infrastructure that we are.
+ *
+ * A key design choice here is to use just one sigsetjmp() call and link
+ * that jmp_buf structure into both jmp_buf stacks. That requires being more
+ * intimate with both error mechanisms than one could wish, but using two
+ * sigsetjmp() calls is expensive, and more importantly it completely breaks
+ * clang's optimizer, so much so that clang generates buggy code even at -O0.
+ * To provide at least a fig-leaf of separation from Perl innards, we use
+ * JMPENV_PUSH/JMPENV_POP to manipulate their jmp_buf stack and modify our
+ * own stack by hand. (Thus, these macros look a good deal like elog.h's.)
+ * The main trick to using a single jmp_buf is how to tell whether a caught
+ * longjmp was raised by our code or Perl's. We handle that by detecting
+ * whether elog.c has a complete error report that's not been popped.
+ * If so, we assume the already-stacked Postgres error is what to report.
+ * If not, the error is Perl's, so we convert their error to a Postgres one.
+ */
+#define PG_PERL_TRY(...) \
+ do { \
+ dJMPENV; \
+ OP *_pp_save_op = PL_op; \
+ volatile bool _pp_leavetry_needed = true; \
+ int _pp_ret_; \
+ sigjmp_buf *_save_exception_stack##__VA_ARGS__ = PG_exception_stack; \
+ ErrorContextCallback *_save_context_stack##__VA_ARGS__ = error_context_stack; \
+ bool _do_rethrow##__VA_ARGS__ = false; \
+ bool _cleanup_needed##__VA_ARGS__ = true; \
+ JMPENV_PUSH(_pp_ret_); \
+ if (_pp_ret_ == 0) \
+ { \
+ PG_exception_stack = &cur_env.je_buf; \
+ plperl_do_entertry(aTHX)
+
+#define PG_PERL_CATCH(...) \
+ } \
+ else \
+ { \
+ /* Is the thrown error ours, or Perl's? */ \
+ if (!HaveCompleteError()) \
+ { \
+ /* Perl's, so assume we don't need LEAVETRY any more */ \
+ _pp_leavetry_needed = false; \
+ /* Reset our error stacks to ensure they're not dangling */ \
+ PG_exception_stack = &cur_env.je_buf; \
+ error_context_stack = _save_context_stack##__VA_ARGS__; \
+ /* This'll longjmp back here, but now with an error stacked */ \
+ PG_PERL_REPORT_LONGJMP(_pp_ret_); \
+ } \
+ PG_PERL_POP_STACKS(__VA_ARGS__)
+
+#define PG_PERL_FINALLY(...) \
+ } \
+ else \
+ { \
+ /* Is the thrown error ours, or Perl's? */ \
+ if (!HaveCompleteError()) \
+ { \
+ /* Perl's, so assume we don't need LEAVETRY any more */ \
+ _pp_leavetry_needed = false; \
+ /* Reset our error stacks to ensure they're not dangling */ \
+ PG_exception_stack = &cur_env.je_buf; \
+ error_context_stack = _save_context_stack##__VA_ARGS__; \
+ /* This'll longjmp back here, but now with an error stacked */ \
+ PG_PERL_REPORT_LONGJMP(_pp_ret_); \
+ } \
+ _do_rethrow##__VA_ARGS__ = true; \
+ } \
+ { \
+ PG_PERL_POP_STACKS(__VA_ARGS__)
+
+#define PG_PERL_END_TRY(...) \
+ } \
+ if (_do_rethrow##__VA_ARGS__) \
+ PG_RE_THROW(); \
+ if (_cleanup_needed##__VA_ARGS__) \
+ { \
+ PG_PERL_POP_STACKS(__VA_ARGS__); \
+ } \
+ } while (0)
+
+/*
+ * This helper macro is split out just to reduce code duplication.
+ * It pops both jmp_buf stacks and does some other end-of-block cleanup.
+ *
+ * Unlike the case in PG_TRY and friends, we must do this only once,
+ * so we need an explicit _cleanup_needed flag to avoid doing it twice
+ * during successful exit from a FINALLY block.
+ */
+#define PG_PERL_POP_STACKS(...) \
+ _cleanup_needed##__VA_ARGS__ = false; \
+ JMPENV_POP; \
+ PG_exception_stack = _save_exception_stack##__VA_ARGS__; \
+ error_context_stack = _save_context_stack##__VA_ARGS__; \
+ if (_pp_leavetry_needed) \
+ plperl_do_leavetry(aTHX); \
+ PL_op = _pp_save_op
+
+#else /* defined(WIN32) && defined(__MINGW64__) */
+
+/*
+ * We use this implementation on MinGW-64, where we use __builtin_setjmp()
+ * (see c.h), but Perl is content with MinGW's setjmp(). Of necessity, we
+ * maintain the two jmp_buf stacks separately and pay the price of two setjmp
+ * calls per level.
+ *
+ * Here, the forced updates of PL_top_env are needed to prevent an assertion
+ * failure in JMPENV_POP when what we are catching is a Postgres longjmp that
+ * has exited past the stack level of some Perl JMPENV_PUSH.
+ */
+#define PG_PERL_TRY(...) \
+ do { \
+ dJMPENV; \
+ OP *_pp_save_op = PL_op; \
+ volatile bool _pp_leavetry_needed = true; \
+ PG_TRY(__VA_ARGS__); \
+ { \
+ int _pp_ret_; \
+ JMPENV_PUSH(_pp_ret_); \
+ if (_pp_ret_ == 0) \
+ { \
+ plperl_do_entertry(aTHX);
+
+#define PG_PERL_CATCH(...) \
+ } \
+ else \
+ { \
+ _pp_leavetry_needed = false; \
+ PG_PERL_REPORT_LONGJMP(_pp_ret_); \
+ } \
+ PL_top_env = &cur_env; \
+ JMPENV_POP; \
+ if (_pp_leavetry_needed) \
+ plperl_do_leavetry(aTHX); \
+ PL_op = _pp_save_op; \
+ } \
+ PG_CATCH(__VA_ARGS__); \
+ { \
+ PL_top_env = &cur_env; \
+ JMPENV_POP; \
+ if (_pp_leavetry_needed) \
+ plperl_do_leavetry(aTHX); \
+ PL_op = _pp_save_op; \
+ {
+
+#define PG_PERL_FINALLY(...) \
+ } \
+ else \
+ { \
+ _pp_leavetry_needed = false; \
+ PG_PERL_REPORT_LONGJMP(_pp_ret_); \
+ } \
+ } \
+ PG_FINALLY(__VA_ARGS__); \
+ { \
+ PL_top_env = &cur_env; \
+ JMPENV_POP; \
+ if (_pp_leavetry_needed) \
+ plperl_do_leavetry(aTHX); \
+ PL_op = _pp_save_op; \
+ {
+
+#define PG_PERL_END_TRY(...) \
+ } \
+ } \
+ PG_END_TRY(__VA_ARGS__); \
+ } while (0)
+
+#endif /* !(defined(WIN32) && defined(__MINGW64__)) */
+
+/*
+ * This helper macro is split out just to reduce code duplication.
+ * It converts an error thrown by Perl into a Postgres ereport.
+ *
+ * Since we're still within the scope of PG_PERL_TRY's JMPENV_PUSH,
+ * any error thrown by the Perl functions used herein will most likely
+ * result in an infinite loop. You'd have to work at it to break Perl
+ * that badly, so we don't try to prevent this; but just in case,
+ * provide a way to break out of the loop.
+ */
+#define PG_PERL_REPORT_LONGJMP(_pp_ret_) \
+ do { \
+ SV *errsv; \
+ CHECK_FOR_INTERRUPTS(); \
+ errsv = ERRSV; \
+ if (SvTRUE(errsv)) \
+ ereport(ERROR, \
+ (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION), \
+ errmsg_internal("%s", strip_trailing_ws(sv2cstr(errsv))))); \
+ else \
+ elog(ERROR, "unexpected Perl longjmp, code %d", _pp_ret_); \
+ } while (0)
+
+/*
+ * Helper function: invoke OP_ENTERTRY to push a CXt_EVAL context
+ *
+ * This hackery with ENTERTRY/LEAVETRY ensures that Perl will longjmp rather
+ * than exiting, even if we're not presently inside an eval{}. We explicitly
+ * save/restore PL_op rather than trying to get ENTERTRY/LEAVETRY to do that.
+ *
+ * A side-effect of OP_ENTERTRY that we do *not* want is CLEAR_ERRSV.
+ * Hack around that by hiding the entry-time ERRSV in a local.
+ */
+static inline void
+plperl_do_entertry(pTHX)
+{
+ SV *old_errsv = GvSV(PL_errgv);
+ LOGOP et_op;
+ OP child_op;
+
+ /* Replace ERRSV with a dummy SV, which ENTERTRY will clear */
+ GvSV(PL_errgv) = newSV(0);
+
+ /* We had better have disabled CATCH_GET, else this does the wrong thing */
+ Assert(!CATCH_GET);
+ memset(&et_op, 0, sizeof(et_op));
+ et_op.op_flags = OPf_WANT_VOID;
+ /* We need a child OP, just to avoid a null-pointer dereference */
+ memset(&child_op, 0, sizeof(child_op));
+ et_op.op_other = &child_op;
+ PL_op = (OP *) &et_op;
+ (void) (PL_ppaddr[OP_ENTERTRY]) (aTHX);
+
+ /* Release the dummy SV's one and only refcnt */
+ SvREFCNT_dec(GvSV(PL_errgv));
+ /* ... and put back the old ERRSV value */
+ GvSV(PL_errgv) = old_errsv;
+}
+
+/*
+ * Helper function: invoke OP_LEAVETRY to pop that context again
+ *
+ * Just to make things difficult, we must skip this if Perl threw a
+ * longjmp, because die_unwind() would have popped the context.
+ *
+ * As above, don't let it change ERRSV.
+ */
+static inline void
+plperl_do_leavetry(pTHX)
+{
+ SV *old_errsv = GvSV(PL_errgv);
+ OP lt_op;
+
+ /* Replace ERRSV with a dummy SV, which LEAVETRY will clear */
+ GvSV(PL_errgv) = newSV(0);
+
+ memset(<_op, 0, sizeof(lt_op));
+ PL_op = <_op;
+ (void) (PL_ppaddr[OP_LEAVETRY]) (aTHX);
+
+ /* Release the dummy SV's one and only refcnt */
+ SvREFCNT_dec(GvSV(PL_errgv));
+ /* ... and put back the old ERRSV value */
+ GvSV(PL_errgv) = old_errsv;
+}
+
#endif /* PL_PERL_H */
diff --git a/src/pl/plperl/sql/plperl_tied.sql b/src/pl/plperl/sql/plperl_tied.sql
index 5f546cc72c3..61887286985 100644
--- a/src/pl/plperl/sql/plperl_tied.sql
+++ b/src/pl/plperl/sql/plperl_tied.sql
@@ -111,3 +111,34 @@ FOR EACH ROW EXECUTE PROCEDURE tied_modify();
INSERT INTO tied_trigger_test (i, v) VALUES (1, 'orig');
SELECT i, v FROM tied_trigger_test;
+
+-- Verify that we can cope with errors thrown within get magic.
+DO $$
+{
+ package PLPerlTiedHash;
+ sub TIEHASH { bless {}, $_[0] }
+ sub STORE { $_[0]{$_[1]} = $_[2] }
+ sub FETCH { die("tied hash fetch failure"); $_[0]{$_[1]} }
+ sub FIRSTKEY { my $a = keys %{$_[0]}; each %{$_[0]} }
+ sub NEXTKEY { each %{$_[0]} }
+
+ package PLPerlTiedArray;
+ sub TIEARRAY { bless [], $_[0] }
+ sub STORE { $_[0][$_[1]] = $_[2] }
+ sub FETCH { die("tied array fetch failure"); $_[0][$_[1]] }
+ sub FETCHSIZE { scalar @{$_[0]} }
+
+ package PLPerlTiedScalar;
+ sub TIESCALAR { my $s; bless \$s, $_[0] }
+ sub STORE { ${$_[0]} = $_[1] }
+ sub FETCH { die("tied scalar fetch failure"); ${$_[0]} }
+}
+$$ LANGUAGE plperl;
+
+SELECT * FROM tied_setof();
+SELECT tied_scalar();
+SELECT tied_composite();
+SELECT tied_int_array();
+SELECT * FROM tied_scalar_setof();
+SELECT tied_scalar_int_array();
+INSERT INTO tied_trigger_test (i, v) VALUES (2, 'orig');
[parent: bc1fa1003f63]