1 /**********************************************************************
2  * plperl.c - perl as a procedural language for PostgreSQL
3  *
4  *	  src/pl/plperl/plperl.c
5  *
6  **********************************************************************/
7 
8 #include "postgres.h"
9 
10 /* Defined by Perl */
11 #undef _
12 
13 /* system stuff */
14 #include <ctype.h>
15 #include <fcntl.h>
16 #include <limits.h>
17 #include <unistd.h>
18 
19 /* postgreSQL stuff */
20 #include "access/htup_details.h"
21 #include "access/xact.h"
22 #include "catalog/pg_language.h"
23 #include "catalog/pg_proc.h"
24 #include "catalog/pg_type.h"
25 #include "commands/event_trigger.h"
26 #include "commands/trigger.h"
27 #include "executor/spi.h"
28 #include "funcapi.h"
29 #include "mb/pg_wchar.h"
30 #include "miscadmin.h"
31 #include "nodes/makefuncs.h"
32 #include "parser/parse_type.h"
33 #include "storage/ipc.h"
34 #include "tcop/tcopprot.h"
35 #include "utils/builtins.h"
36 #include "utils/fmgroids.h"
37 #include "utils/guc.h"
38 #include "utils/hsearch.h"
39 #include "utils/lsyscache.h"
40 #include "utils/memutils.h"
41 #include "utils/rel.h"
42 #include "utils/syscache.h"
43 #include "utils/typcache.h"
44 
45 /* define our text domain for translations */
46 #undef TEXTDOMAIN
47 #define TEXTDOMAIN PG_TEXTDOMAIN("plperl")
48 
49 /* perl stuff */
50 #include "plperl.h"
51 #include "plperl_helpers.h"
52 
53 /* string literal macros defining chunks of perl code */
54 #include "perlchunks.h"
55 /* defines PLPERL_SET_OPMASK */
56 #include "plperl_opmask.h"
57 
58 EXTERN_C void boot_DynaLoader(pTHX_ CV *cv);
59 EXTERN_C void boot_PostgreSQL__InServer__Util(pTHX_ CV *cv);
60 EXTERN_C void boot_PostgreSQL__InServer__SPI(pTHX_ CV *cv);
61 
62 PG_MODULE_MAGIC;
63 
64 /**********************************************************************
65  * Information associated with a Perl interpreter.  We have one interpreter
66  * that is used for all plperlu (untrusted) functions.  For plperl (trusted)
67  * functions, there is a separate interpreter for each effective SQL userid.
68  * (This is needed to ensure that an unprivileged user can't inject Perl code
69  * that'll be executed with the privileges of some other SQL user.)
70  *
71  * The plperl_interp_desc structs are kept in a Postgres hash table indexed
72  * by userid OID, with OID 0 used for the single untrusted interpreter.
73  * Once created, an interpreter is kept for the life of the process.
74  *
75  * We start out by creating a "held" interpreter, which we initialize
76  * only as far as we can do without deciding if it will be trusted or
77  * untrusted.  Later, when we first need to run a plperl or plperlu
78  * function, we complete the initialization appropriately and move the
79  * PerlInterpreter pointer into the plperl_interp_hash hashtable.  If after
80  * that we need more interpreters, we create them as needed if we can, or
81  * fail if the Perl build doesn't support multiple interpreters.
82  *
83  * The reason for all the dancing about with a held interpreter is to make
84  * it possible for people to preload a lot of Perl code at postmaster startup
85  * (using plperl.on_init) and then use that code in backends.  Of course this
86  * will only work for the first interpreter created in any backend, but it's
87  * still useful with that restriction.
88  **********************************************************************/
89 typedef struct plperl_interp_desc
90 {
91 	Oid			user_id;		/* Hash key (must be first!) */
92 	PerlInterpreter *interp;	/* The interpreter */
93 	HTAB	   *query_hash;		/* plperl_query_entry structs */
94 } plperl_interp_desc;
95 
96 
97 /**********************************************************************
98  * The information we cache about loaded procedures
99  *
100  * The fn_refcount field counts the struct's reference from the hash table
101  * shown below, plus one reference for each function call level that is using
102  * the struct.  We can release the struct, and the associated Perl sub, when
103  * the fn_refcount goes to zero.  Releasing the struct itself is done by
104  * deleting the fn_cxt, which also gets rid of all subsidiary data.
105  **********************************************************************/
106 typedef struct plperl_proc_desc
107 {
108 	char	   *proname;		/* user name of procedure */
109 	MemoryContext fn_cxt;		/* memory context for this procedure */
110 	unsigned long fn_refcount;	/* number of active references */
111 	TransactionId fn_xmin;		/* xmin/TID of procedure's pg_proc tuple */
112 	ItemPointerData fn_tid;
113 	SV		   *reference;		/* CODE reference for Perl sub */
114 	plperl_interp_desc *interp; /* interpreter it's created in */
115 	bool		fn_readonly;	/* is function readonly (not volatile)? */
116 	Oid			lang_oid;
117 	List	   *trftypes;
118 	bool		lanpltrusted;	/* is it plperl, rather than plperlu? */
119 	bool		fn_retistuple;	/* true, if function returns tuple */
120 	bool		fn_retisset;	/* true, if function returns set */
121 	bool		fn_retisarray;	/* true if function returns array */
122 	/* Conversion info for function's result type: */
123 	Oid			result_oid;		/* Oid of result type */
124 	FmgrInfo	result_in_func; /* I/O function and arg for result type */
125 	Oid			result_typioparam;
126 	/* Per-argument info for function's argument types: */
127 	int			nargs;
128 	FmgrInfo   *arg_out_func;	/* output fns for arg types */
129 	bool	   *arg_is_rowtype; /* is each arg composite? */
130 	Oid		   *arg_arraytype;	/* InvalidOid if not an array */
131 } plperl_proc_desc;
132 
133 #define increment_prodesc_refcount(prodesc)  \
134 	((prodesc)->fn_refcount++)
135 #define decrement_prodesc_refcount(prodesc)  \
136 	do { \
137 		Assert((prodesc)->fn_refcount > 0); \
138 		if (--((prodesc)->fn_refcount) == 0) \
139 			free_plperl_function(prodesc); \
140 	} while(0)
141 
142 /**********************************************************************
143  * For speedy lookup, we maintain a hash table mapping from
144  * function OID + trigger flag + user OID to plperl_proc_desc pointers.
145  * The reason the plperl_proc_desc struct isn't directly part of the hash
146  * entry is to simplify recovery from errors during compile_plperl_function.
147  *
148  * Note: if the same function is called by multiple userIDs within a session,
149  * there will be a separate plperl_proc_desc entry for each userID in the case
150  * of plperl functions, but only one entry for plperlu functions, because we
151  * set user_id = 0 for that case.  If the user redeclares the same function
152  * from plperl to plperlu or vice versa, there might be multiple
153  * plperl_proc_ptr entries in the hashtable, but only one is valid.
154  **********************************************************************/
155 typedef struct plperl_proc_key
156 {
157 	Oid			proc_id;		/* Function OID */
158 
159 	/*
160 	 * is_trigger is really a bool, but declare as Oid to ensure this struct
161 	 * contains no padding
162 	 */
163 	Oid			is_trigger;		/* is it a trigger function? */
164 	Oid			user_id;		/* User calling the function, or 0 */
165 } plperl_proc_key;
166 
167 typedef struct plperl_proc_ptr
168 {
169 	plperl_proc_key proc_key;	/* Hash key (must be first!) */
170 	plperl_proc_desc *proc_ptr;
171 } plperl_proc_ptr;
172 
173 /*
174  * The information we cache for the duration of a single call to a
175  * function.
176  */
177 typedef struct plperl_call_data
178 {
179 	plperl_proc_desc *prodesc;
180 	FunctionCallInfo fcinfo;
181 	/* remaining fields are used only in a function returning set: */
182 	Tuplestorestate *tuple_store;
183 	TupleDesc	ret_tdesc;
184 	Oid			cdomain_oid;	/* 0 unless returning domain-over-composite */
185 	void	   *cdomain_info;
186 	MemoryContext tmp_cxt;
187 } plperl_call_data;
188 
189 /**********************************************************************
190  * The information we cache about prepared and saved plans
191  **********************************************************************/
192 typedef struct plperl_query_desc
193 {
194 	char		qname[24];
195 	MemoryContext plan_cxt;		/* context holding this struct */
196 	SPIPlanPtr	plan;
197 	int			nargs;
198 	Oid		   *argtypes;
199 	FmgrInfo   *arginfuncs;
200 	Oid		   *argtypioparams;
201 } plperl_query_desc;
202 
203 /* hash table entry for query desc	*/
204 
205 typedef struct plperl_query_entry
206 {
207 	char		query_name[NAMEDATALEN];
208 	plperl_query_desc *query_data;
209 } plperl_query_entry;
210 
211 /**********************************************************************
212  * Information for PostgreSQL - Perl array conversion.
213  **********************************************************************/
214 typedef struct plperl_array_info
215 {
216 	int			ndims;
217 	bool		elem_is_rowtype;	/* 't' if element type is a rowtype */
218 	Datum	   *elements;
219 	bool	   *nulls;
220 	int		   *nelems;
221 	FmgrInfo	proc;
222 	FmgrInfo	transform_proc;
223 } plperl_array_info;
224 
225 /**********************************************************************
226  * Global data
227  **********************************************************************/
228 
229 static HTAB *plperl_interp_hash = NULL;
230 static HTAB *plperl_proc_hash = NULL;
231 static plperl_interp_desc *plperl_active_interp = NULL;
232 
233 /* If we have an unassigned "held" interpreter, it's stored here */
234 static PerlInterpreter *plperl_held_interp = NULL;
235 
236 /* GUC variables */
237 static bool plperl_use_strict = false;
238 static char *plperl_on_init = NULL;
239 static char *plperl_on_plperl_init = NULL;
240 static char *plperl_on_plperlu_init = NULL;
241 
242 static bool plperl_ending = false;
243 static OP  *(*pp_require_orig) (pTHX) = NULL;
244 static char plperl_opmask[MAXO];
245 
246 /* this is saved and restored by plperl_call_handler */
247 static plperl_call_data *current_call_data = NULL;
248 
249 /**********************************************************************
250  * Forward declarations
251  **********************************************************************/
252 void		_PG_init(void);
253 
254 static PerlInterpreter *plperl_init_interp(void);
255 static void plperl_destroy_interp(PerlInterpreter **);
256 static void plperl_fini(int code, Datum arg);
257 static void set_interp_require(bool trusted);
258 
259 static Datum plperl_func_handler(PG_FUNCTION_ARGS);
260 static Datum plperl_trigger_handler(PG_FUNCTION_ARGS);
261 static void plperl_event_trigger_handler(PG_FUNCTION_ARGS);
262 
263 static void free_plperl_function(plperl_proc_desc *prodesc);
264 
265 static plperl_proc_desc *compile_plperl_function(Oid fn_oid,
266 						bool is_trigger,
267 						bool is_event_trigger);
268 
269 static SV  *plperl_hash_from_tuple(HeapTuple tuple, TupleDesc tupdesc);
270 static SV  *plperl_hash_from_datum(Datum attr);
271 static SV  *plperl_ref_from_pg_array(Datum arg, Oid typid);
272 static SV  *split_array(plperl_array_info *info, int first, int last, int nest);
273 static SV  *make_array_ref(plperl_array_info *info, int first, int last);
274 static SV  *get_perl_array_ref(SV *sv);
275 static Datum plperl_sv_to_datum(SV *sv, Oid typid, int32 typmod,
276 				   FunctionCallInfo fcinfo,
277 				   FmgrInfo *finfo, Oid typioparam,
278 				   bool *isnull);
279 static void _sv_to_datum_finfo(Oid typid, FmgrInfo *finfo, Oid *typioparam);
280 static Datum plperl_array_to_datum(SV *src, Oid typid, int32 typmod);
281 static void array_to_datum_internal(AV *av, ArrayBuildState *astate,
282 						int *ndims, int *dims, int cur_depth,
283 						Oid arraytypid, Oid elemtypid, int32 typmod,
284 						FmgrInfo *finfo, Oid typioparam);
285 static Datum plperl_hash_to_datum(SV *src, TupleDesc td);
286 
287 static void plperl_init_shared_libs(pTHX);
288 static void plperl_trusted_init(void);
289 static void plperl_untrusted_init(void);
290 static HV  *plperl_spi_execute_fetch_result(SPITupleTable *, uint64, int);
291 static void plperl_return_next_internal(SV *sv);
292 static char *hek2cstr(HE *he);
293 static SV **hv_store_string(HV *hv, const char *key, SV *val);
294 static SV **hv_fetch_string(HV *hv, const char *key);
295 static void plperl_create_sub(plperl_proc_desc *desc, const char *s, Oid fn_oid);
296 static SV  *plperl_call_perl_func(plperl_proc_desc *desc,
297 					  FunctionCallInfo fcinfo);
298 static void plperl_compile_callback(void *arg);
299 static void plperl_exec_callback(void *arg);
300 static void plperl_inline_callback(void *arg);
301 static char *strip_trailing_ws(const char *msg);
302 static OP  *pp_require_safe(pTHX);
303 static void activate_interpreter(plperl_interp_desc *interp_desc);
304 
305 #ifdef WIN32
306 static char *setlocale_perl(int category, char *locale);
307 #endif
308 
309 /*
310  * Decrement the refcount of the given SV within the active Perl interpreter
311  *
312  * This is handy because it reloads the active-interpreter pointer, saving
313  * some notation in callers that switch the active interpreter.
314  */
315 static inline void
SvREFCNT_dec_current(SV * sv)316 SvREFCNT_dec_current(SV *sv)
317 {
318 	dTHX;
319 
320 	SvREFCNT_dec(sv);
321 }
322 
323 /*
324  * convert a HE (hash entry) key to a cstr in the current database encoding
325  */
326 static char *
hek2cstr(HE * he)327 hek2cstr(HE *he)
328 {
329 	dTHX;
330 	char	   *ret;
331 	SV		   *sv;
332 
333 	/*
334 	 * HeSVKEY_force will return a temporary mortal SV*, so we need to make
335 	 * sure to free it with ENTER/SAVE/FREE/LEAVE
336 	 */
337 	ENTER;
338 	SAVETMPS;
339 
340 	/*-------------------------
341 	 * Unfortunately,  while HeUTF8 is true for most things > 256, for values
342 	 * 128..255 it's not, but perl will treat them as unicode code points if
343 	 * the utf8 flag is not set ( see The "Unicode Bug" in perldoc perlunicode
344 	 * for more)
345 	 *
346 	 * So if we did the expected:
347 	 *	  if (HeUTF8(he))
348 	 *		  utf_u2e(key...);
349 	 *	  else // must be ascii
350 	 *		  return HePV(he);
351 	 * we won't match columns with codepoints from 128..255
352 	 *
353 	 * For a more concrete example given a column with the name of the unicode
354 	 * codepoint U+00ae (registered sign) and a UTF8 database and the perl
355 	 * return_next { "\N{U+00ae}=>'text } would always fail as heUTF8 returns
356 	 * 0 and HePV() would give us a char * with 1 byte contains the decimal
357 	 * value 174
358 	 *
359 	 * Perl has the brains to know when it should utf8 encode 174 properly, so
360 	 * here we force it into an SV so that perl will figure it out and do the
361 	 * right thing
362 	 *-------------------------
363 	 */
364 
365 	sv = HeSVKEY_force(he);
366 	if (HeUTF8(he))
367 		SvUTF8_on(sv);
368 	ret = sv2cstr(sv);
369 
370 	/* free sv */
371 	FREETMPS;
372 	LEAVE;
373 
374 	return ret;
375 }
376 
377 
378 /*
379  * _PG_init()			- library load-time initialization
380  *
381  * DO NOT make this static nor change its name!
382  */
383 void
_PG_init(void)384 _PG_init(void)
385 {
386 	/*
387 	 * Be sure we do initialization only once.
388 	 *
389 	 * If initialization fails due to, e.g., plperl_init_interp() throwing an
390 	 * exception, then we'll return here on the next usage and the user will
391 	 * get a rather cryptic: ERROR:  attempt to redefine parameter
392 	 * "plperl.use_strict"
393 	 */
394 	static bool inited = false;
395 	HASHCTL		hash_ctl;
396 
397 	if (inited)
398 		return;
399 
400 	/*
401 	 * Support localized messages.
402 	 */
403 	pg_bindtextdomain(TEXTDOMAIN);
404 
405 	/*
406 	 * Initialize plperl's GUCs.
407 	 */
408 	DefineCustomBoolVariable("plperl.use_strict",
409 							 gettext_noop("If true, trusted and untrusted Perl code will be compiled in strict mode."),
410 							 NULL,
411 							 &plperl_use_strict,
412 							 false,
413 							 PGC_USERSET, 0,
414 							 NULL, NULL, NULL);
415 
416 	/*
417 	 * plperl.on_init is marked PGC_SIGHUP to support the idea that it might
418 	 * be executed in the postmaster (if plperl is loaded into the postmaster
419 	 * via shared_preload_libraries).  This isn't really right either way,
420 	 * though.
421 	 */
422 	DefineCustomStringVariable("plperl.on_init",
423 							   gettext_noop("Perl initialization code to execute when a Perl interpreter is initialized."),
424 							   NULL,
425 							   &plperl_on_init,
426 							   NULL,
427 							   PGC_SIGHUP, 0,
428 							   NULL, NULL, NULL);
429 
430 	/*
431 	 * plperl.on_plperl_init is marked PGC_SUSET to avoid issues whereby a
432 	 * user who might not even have USAGE privilege on the plperl language
433 	 * could nonetheless use SET plperl.on_plperl_init='...' to influence the
434 	 * behaviour of any existing plperl function that they can execute (which
435 	 * might be SECURITY DEFINER, leading to a privilege escalation).  See
436 	 * http://archives.postgresql.org/pgsql-hackers/2010-02/msg00281.php and
437 	 * the overall thread.
438 	 *
439 	 * Note that because plperl.use_strict is USERSET, a nefarious user could
440 	 * set it to be applied against other people's functions.  This is judged
441 	 * OK since the worst result would be an error.  Your code oughta pass
442 	 * use_strict anyway ;-)
443 	 */
444 	DefineCustomStringVariable("plperl.on_plperl_init",
445 							   gettext_noop("Perl initialization code to execute once when plperl is first used."),
446 							   NULL,
447 							   &plperl_on_plperl_init,
448 							   NULL,
449 							   PGC_SUSET, 0,
450 							   NULL, NULL, NULL);
451 
452 	DefineCustomStringVariable("plperl.on_plperlu_init",
453 							   gettext_noop("Perl initialization code to execute once when plperlu is first used."),
454 							   NULL,
455 							   &plperl_on_plperlu_init,
456 							   NULL,
457 							   PGC_SUSET, 0,
458 							   NULL, NULL, NULL);
459 
460 	EmitWarningsOnPlaceholders("plperl");
461 
462 	/*
463 	 * Create hash tables.
464 	 */
465 	memset(&hash_ctl, 0, sizeof(hash_ctl));
466 	hash_ctl.keysize = sizeof(Oid);
467 	hash_ctl.entrysize = sizeof(plperl_interp_desc);
468 	plperl_interp_hash = hash_create("PL/Perl interpreters",
469 									 8,
470 									 &hash_ctl,
471 									 HASH_ELEM | HASH_BLOBS);
472 
473 	memset(&hash_ctl, 0, sizeof(hash_ctl));
474 	hash_ctl.keysize = sizeof(plperl_proc_key);
475 	hash_ctl.entrysize = sizeof(plperl_proc_ptr);
476 	plperl_proc_hash = hash_create("PL/Perl procedures",
477 								   32,
478 								   &hash_ctl,
479 								   HASH_ELEM | HASH_BLOBS);
480 
481 	/*
482 	 * Save the default opmask.
483 	 */
484 	PLPERL_SET_OPMASK(plperl_opmask);
485 
486 	/*
487 	 * Create the first Perl interpreter, but only partially initialize it.
488 	 */
489 	plperl_held_interp = plperl_init_interp();
490 
491 	inited = true;
492 }
493 
494 
495 static void
set_interp_require(bool trusted)496 set_interp_require(bool trusted)
497 {
498 	if (trusted)
499 	{
500 		PL_ppaddr[OP_REQUIRE] = pp_require_safe;
501 		PL_ppaddr[OP_DOFILE] = pp_require_safe;
502 	}
503 	else
504 	{
505 		PL_ppaddr[OP_REQUIRE] = pp_require_orig;
506 		PL_ppaddr[OP_DOFILE] = pp_require_orig;
507 	}
508 }
509 
510 /*
511  * Cleanup perl interpreters, including running END blocks.
512  * Does not fully undo the actions of _PG_init() nor make it callable again.
513  */
514 static void
plperl_fini(int code,Datum arg)515 plperl_fini(int code, Datum arg)
516 {
517 	HASH_SEQ_STATUS hash_seq;
518 	plperl_interp_desc *interp_desc;
519 
520 	elog(DEBUG3, "plperl_fini");
521 
522 	/*
523 	 * Indicate that perl is terminating. Disables use of spi_* functions when
524 	 * running END/DESTROY code. See check_spi_usage_allowed(). Could be
525 	 * enabled in future, with care, using a transaction
526 	 * http://archives.postgresql.org/pgsql-hackers/2010-01/msg02743.php
527 	 */
528 	plperl_ending = true;
529 
530 	/* Only perform perl cleanup if we're exiting cleanly */
531 	if (code)
532 	{
533 		elog(DEBUG3, "plperl_fini: skipped");
534 		return;
535 	}
536 
537 	/* Zap the "held" interpreter, if we still have it */
538 	plperl_destroy_interp(&plperl_held_interp);
539 
540 	/* Zap any fully-initialized interpreters */
541 	hash_seq_init(&hash_seq, plperl_interp_hash);
542 	while ((interp_desc = hash_seq_search(&hash_seq)) != NULL)
543 	{
544 		if (interp_desc->interp)
545 		{
546 			activate_interpreter(interp_desc);
547 			plperl_destroy_interp(&interp_desc->interp);
548 		}
549 	}
550 
551 	elog(DEBUG3, "plperl_fini: done");
552 }
553 
554 
555 /*
556  * Select and activate an appropriate Perl interpreter.
557  */
558 static void
select_perl_context(bool trusted)559 select_perl_context(bool trusted)
560 {
561 	Oid			user_id;
562 	plperl_interp_desc *interp_desc;
563 	bool		found;
564 	PerlInterpreter *interp = NULL;
565 
566 	/* Find or create the interpreter hashtable entry for this userid */
567 	if (trusted)
568 		user_id = GetUserId();
569 	else
570 		user_id = InvalidOid;
571 
572 	interp_desc = hash_search(plperl_interp_hash, &user_id,
573 							  HASH_ENTER,
574 							  &found);
575 	if (!found)
576 	{
577 		/* Initialize newly-created hashtable entry */
578 		interp_desc->interp = NULL;
579 		interp_desc->query_hash = NULL;
580 	}
581 
582 	/* Make sure we have a query_hash for this interpreter */
583 	if (interp_desc->query_hash == NULL)
584 	{
585 		HASHCTL		hash_ctl;
586 
587 		memset(&hash_ctl, 0, sizeof(hash_ctl));
588 		hash_ctl.keysize = NAMEDATALEN;
589 		hash_ctl.entrysize = sizeof(plperl_query_entry);
590 		interp_desc->query_hash = hash_create("PL/Perl queries",
591 											  32,
592 											  &hash_ctl,
593 											  HASH_ELEM);
594 	}
595 
596 	/*
597 	 * Quick exit if already have an interpreter
598 	 */
599 	if (interp_desc->interp)
600 	{
601 		activate_interpreter(interp_desc);
602 		return;
603 	}
604 
605 	/*
606 	 * adopt held interp if free, else create new one if possible
607 	 */
608 	if (plperl_held_interp != NULL)
609 	{
610 		/* first actual use of a perl interpreter */
611 		interp = plperl_held_interp;
612 
613 		/*
614 		 * Reset the plperl_held_interp pointer first; if we fail during init
615 		 * we don't want to try again with the partially-initialized interp.
616 		 */
617 		plperl_held_interp = NULL;
618 
619 		if (trusted)
620 			plperl_trusted_init();
621 		else
622 			plperl_untrusted_init();
623 
624 		/* successfully initialized, so arrange for cleanup */
625 		on_proc_exit(plperl_fini, 0);
626 	}
627 	else
628 	{
629 #ifdef MULTIPLICITY
630 
631 		/*
632 		 * plperl_init_interp will change Perl's idea of the active
633 		 * interpreter.  Reset plperl_active_interp temporarily, so that if we
634 		 * hit an error partway through here, we'll make sure to switch back
635 		 * to a non-broken interpreter before running any other Perl
636 		 * functions.
637 		 */
638 		plperl_active_interp = NULL;
639 
640 		/* Now build the new interpreter */
641 		interp = plperl_init_interp();
642 
643 		if (trusted)
644 			plperl_trusted_init();
645 		else
646 			plperl_untrusted_init();
647 #else
648 		ereport(ERROR,
649 				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
650 				 errmsg("cannot allocate multiple Perl interpreters on this platform")));
651 #endif
652 	}
653 
654 	set_interp_require(trusted);
655 
656 	/*
657 	 * Since the timing of first use of PL/Perl can't be predicted, any
658 	 * database interaction during initialization is problematic. Including,
659 	 * but not limited to, security definer issues. So we only enable access
660 	 * to the database AFTER on_*_init code has run. See
661 	 * http://archives.postgresql.org/pgsql-hackers/2010-01/msg02669.php
662 	 */
663 	{
664 		dTHX;
665 
666 		newXS("PostgreSQL::InServer::SPI::bootstrap",
667 			  boot_PostgreSQL__InServer__SPI, __FILE__);
668 
669 		eval_pv("PostgreSQL::InServer::SPI::bootstrap()", FALSE);
670 		if (SvTRUE(ERRSV))
671 			ereport(ERROR,
672 					(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
673 					 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
674 					 errcontext("while executing PostgreSQL::InServer::SPI::bootstrap")));
675 	}
676 
677 	/* Fully initialized, so mark the hashtable entry valid */
678 	interp_desc->interp = interp;
679 
680 	/* And mark this as the active interpreter */
681 	plperl_active_interp = interp_desc;
682 }
683 
684 /*
685  * Make the specified interpreter the active one
686  *
687  * A call with NULL does nothing.  This is so that "restoring" to a previously
688  * null state of plperl_active_interp doesn't result in useless thrashing.
689  */
690 static void
activate_interpreter(plperl_interp_desc * interp_desc)691 activate_interpreter(plperl_interp_desc *interp_desc)
692 {
693 	if (interp_desc && plperl_active_interp != interp_desc)
694 	{
695 		Assert(interp_desc->interp);
696 		PERL_SET_CONTEXT(interp_desc->interp);
697 		/* trusted iff user_id isn't InvalidOid */
698 		set_interp_require(OidIsValid(interp_desc->user_id));
699 		plperl_active_interp = interp_desc;
700 	}
701 }
702 
703 /*
704  * Create a new Perl interpreter.
705  *
706  * We initialize the interpreter as far as we can without knowing whether
707  * it will become a trusted or untrusted interpreter; in particular, the
708  * plperl.on_init code will get executed.  Later, either plperl_trusted_init
709  * or plperl_untrusted_init must be called to complete the initialization.
710  */
711 static PerlInterpreter *
plperl_init_interp(void)712 plperl_init_interp(void)
713 {
714 	PerlInterpreter *plperl;
715 
716 	static char *embedding[3 + 2] = {
717 		"", "-e", PLC_PERLBOOT
718 	};
719 	int			nargs = 3;
720 
721 #ifdef WIN32
722 
723 	/*
724 	 * The perl library on startup does horrible things like call
725 	 * setlocale(LC_ALL,""). We have protected against that on most platforms
726 	 * by setting the environment appropriately. However, on Windows,
727 	 * setlocale() does not consult the environment, so we need to save the
728 	 * existing locale settings before perl has a chance to mangle them and
729 	 * restore them after its dirty deeds are done.
730 	 *
731 	 * MSDN ref:
732 	 * http://msdn.microsoft.com/library/en-us/vclib/html/_crt_locale.asp
733 	 *
734 	 * It appears that we only need to do this on interpreter startup, and
735 	 * subsequent calls to the interpreter don't mess with the locale
736 	 * settings.
737 	 *
738 	 * We restore them using setlocale_perl(), defined below, so that Perl
739 	 * doesn't have a different idea of the locale from Postgres.
740 	 *
741 	 */
742 
743 	char	   *loc;
744 	char	   *save_collate,
745 			   *save_ctype,
746 			   *save_monetary,
747 			   *save_numeric,
748 			   *save_time;
749 
750 	loc = setlocale(LC_COLLATE, NULL);
751 	save_collate = loc ? pstrdup(loc) : NULL;
752 	loc = setlocale(LC_CTYPE, NULL);
753 	save_ctype = loc ? pstrdup(loc) : NULL;
754 	loc = setlocale(LC_MONETARY, NULL);
755 	save_monetary = loc ? pstrdup(loc) : NULL;
756 	loc = setlocale(LC_NUMERIC, NULL);
757 	save_numeric = loc ? pstrdup(loc) : NULL;
758 	loc = setlocale(LC_TIME, NULL);
759 	save_time = loc ? pstrdup(loc) : NULL;
760 
761 #define PLPERL_RESTORE_LOCALE(name, saved) \
762 	STMT_START { \
763 		if (saved != NULL) { setlocale_perl(name, saved); pfree(saved); } \
764 	} STMT_END
765 #endif							/* WIN32 */
766 
767 	if (plperl_on_init && *plperl_on_init)
768 	{
769 		embedding[nargs++] = "-e";
770 		embedding[nargs++] = plperl_on_init;
771 	}
772 
773 	/*
774 	 * The perl API docs state that PERL_SYS_INIT3 should be called before
775 	 * allocating interpreters. Unfortunately, on some platforms this fails in
776 	 * the Perl_do_taint() routine, which is called when the platform is using
777 	 * the system's malloc() instead of perl's own. Other platforms, notably
778 	 * Windows, fail if PERL_SYS_INIT3 is not called. So we call it if it's
779 	 * available, unless perl is using the system malloc(), which is true when
780 	 * MYMALLOC is set.
781 	 */
782 #if defined(PERL_SYS_INIT3) && !defined(MYMALLOC)
783 	{
784 		static int	perl_sys_init_done;
785 
786 		/* only call this the first time through, as per perlembed man page */
787 		if (!perl_sys_init_done)
788 		{
789 			char	   *dummy_env[1] = {NULL};
790 
791 			PERL_SYS_INIT3(&nargs, (char ***) &embedding, (char ***) &dummy_env);
792 
793 			/*
794 			 * For unclear reasons, PERL_SYS_INIT3 sets the SIGFPE handler to
795 			 * SIG_IGN.  Aside from being extremely unfriendly behavior for a
796 			 * library, this is dumb on the grounds that the results of a
797 			 * SIGFPE in this state are undefined according to POSIX, and in
798 			 * fact you get a forced process kill at least on Linux.  Hence,
799 			 * restore the SIGFPE handler to the backend's standard setting.
800 			 * (See Perl bug 114574 for more information.)
801 			 */
802 			pqsignal(SIGFPE, FloatExceptionHandler);
803 
804 			perl_sys_init_done = 1;
805 			/* quiet warning if PERL_SYS_INIT3 doesn't use the third argument */
806 			dummy_env[0] = NULL;
807 		}
808 	}
809 #endif
810 
811 	plperl = perl_alloc();
812 	if (!plperl)
813 		elog(ERROR, "could not allocate Perl interpreter");
814 
815 	PERL_SET_CONTEXT(plperl);
816 	perl_construct(plperl);
817 
818 	/*
819 	 * Run END blocks in perl_destruct instead of perl_run.  Note that dTHX
820 	 * loads up a pointer to the current interpreter, so we have to postpone
821 	 * it to here rather than put it at the function head.
822 	 */
823 	{
824 		dTHX;
825 
826 		PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
827 
828 		/*
829 		 * Record the original function for the 'require' and 'dofile'
830 		 * opcodes.  (They share the same implementation.)  Ensure it's used
831 		 * for new interpreters.
832 		 */
833 		if (!pp_require_orig)
834 			pp_require_orig = PL_ppaddr[OP_REQUIRE];
835 		else
836 		{
837 			PL_ppaddr[OP_REQUIRE] = pp_require_orig;
838 			PL_ppaddr[OP_DOFILE] = pp_require_orig;
839 		}
840 
841 #ifdef PLPERL_ENABLE_OPMASK_EARLY
842 
843 		/*
844 		 * For regression testing to prove that the PLC_PERLBOOT and
845 		 * PLC_TRUSTED code doesn't even compile any unsafe ops.  In future
846 		 * there may be a valid need for them to do so, in which case this
847 		 * could be softened (perhaps moved to plperl_trusted_init()) or
848 		 * removed.
849 		 */
850 		PL_op_mask = plperl_opmask;
851 #endif
852 
853 		if (perl_parse(plperl, plperl_init_shared_libs,
854 					   nargs, embedding, NULL) != 0)
855 			ereport(ERROR,
856 					(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
857 					 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
858 					 errcontext("while parsing Perl initialization")));
859 
860 		if (perl_run(plperl) != 0)
861 			ereport(ERROR,
862 					(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
863 					 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
864 					 errcontext("while running Perl initialization")));
865 
866 #ifdef PLPERL_RESTORE_LOCALE
867 		PLPERL_RESTORE_LOCALE(LC_COLLATE, save_collate);
868 		PLPERL_RESTORE_LOCALE(LC_CTYPE, save_ctype);
869 		PLPERL_RESTORE_LOCALE(LC_MONETARY, save_monetary);
870 		PLPERL_RESTORE_LOCALE(LC_NUMERIC, save_numeric);
871 		PLPERL_RESTORE_LOCALE(LC_TIME, save_time);
872 #endif
873 	}
874 
875 	return plperl;
876 }
877 
878 
879 /*
880  * Our safe implementation of the require opcode.
881  * This is safe because it's completely unable to load any code.
882  * If the requested file/module has already been loaded it'll return true.
883  * If not, it'll die.
884  * So now "use Foo;" will work iff Foo has already been loaded.
885  */
886 static OP  *
pp_require_safe(pTHX)887 pp_require_safe(pTHX)
888 {
889 	dVAR;
890 	dSP;
891 	SV		   *sv,
892 			  **svp;
893 	char	   *name;
894 	STRLEN		len;
895 
896 	sv = POPs;
897 	name = SvPV(sv, len);
898 	if (!(name && len > 0 && *name))
899 		RETPUSHNO;
900 
901 	svp = hv_fetch(GvHVn(PL_incgv), name, len, 0);
902 	if (svp && *svp != &PL_sv_undef)
903 		RETPUSHYES;
904 
905 	DIE(aTHX_ "Unable to load %s into plperl", name);
906 
907 	/*
908 	 * In most Perl versions, DIE() expands to a return statement, so the next
909 	 * line is not necessary.  But in versions between but not including
910 	 * 5.11.1 and 5.13.3 it does not, so the next line is necessary to avoid a
911 	 * "control reaches end of non-void function" warning from gcc.  Other
912 	 * compilers such as Solaris Studio will, however, issue a "statement not
913 	 * reached" warning instead.
914 	 */
915 	return NULL;
916 }
917 
918 
919 /*
920  * Destroy one Perl interpreter ... actually we just run END blocks.
921  *
922  * Caller must have ensured this interpreter is the active one.
923  */
924 static void
plperl_destroy_interp(PerlInterpreter ** interp)925 plperl_destroy_interp(PerlInterpreter **interp)
926 {
927 	if (interp && *interp)
928 	{
929 		/*
930 		 * Only a very minimal destruction is performed: - just call END
931 		 * blocks.
932 		 *
933 		 * We could call perl_destruct() but we'd need to audit its actions
934 		 * very carefully and work-around any that impact us. (Calling
935 		 * sv_clean_objs() isn't an option because it's not part of perl's
936 		 * public API so isn't portably available.) Meanwhile END blocks can
937 		 * be used to perform manual cleanup.
938 		 */
939 		dTHX;
940 
941 		/* Run END blocks - based on perl's perl_destruct() */
942 		if (PL_exit_flags & PERL_EXIT_DESTRUCT_END)
943 		{
944 			dJMPENV;
945 			int			x = 0;
946 
947 			JMPENV_PUSH(x);
948 			PERL_UNUSED_VAR(x);
949 			if (PL_endav && !PL_minus_c)
950 				call_list(PL_scopestack_ix, PL_endav);
951 			JMPENV_POP;
952 		}
953 		LEAVE;
954 		FREETMPS;
955 
956 		*interp = NULL;
957 	}
958 }
959 
960 /*
961  * Initialize the current Perl interpreter as a trusted interp
962  */
963 static void
plperl_trusted_init(void)964 plperl_trusted_init(void)
965 {
966 	dTHX;
967 	HV		   *stash;
968 	SV		   *sv;
969 	char	   *key;
970 	I32			klen;
971 
972 	/* use original require while we set up */
973 	PL_ppaddr[OP_REQUIRE] = pp_require_orig;
974 	PL_ppaddr[OP_DOFILE] = pp_require_orig;
975 
976 	eval_pv(PLC_TRUSTED, FALSE);
977 	if (SvTRUE(ERRSV))
978 		ereport(ERROR,
979 				(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
980 				 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
981 				 errcontext("while executing PLC_TRUSTED")));
982 
983 	/*
984 	 * Force loading of utf8 module now to prevent errors that can arise from
985 	 * the regex code later trying to load utf8 modules. See
986 	 * http://rt.perl.org/rt3/Ticket/Display.html?id=47576
987 	 */
988 	eval_pv("my $a=chr(0x100); return $a =~ /\\xa9/i", FALSE);
989 	if (SvTRUE(ERRSV))
990 		ereport(ERROR,
991 				(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
992 				 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
993 				 errcontext("while executing utf8fix")));
994 
995 	/*
996 	 * Lock down the interpreter
997 	 */
998 
999 	/* switch to the safe require/dofile opcode for future code */
1000 	PL_ppaddr[OP_REQUIRE] = pp_require_safe;
1001 	PL_ppaddr[OP_DOFILE] = pp_require_safe;
1002 
1003 	/*
1004 	 * prevent (any more) unsafe opcodes being compiled PL_op_mask is per
1005 	 * interpreter, so this only needs to be set once
1006 	 */
1007 	PL_op_mask = plperl_opmask;
1008 
1009 	/* delete the DynaLoader:: namespace so extensions can't be loaded */
1010 	stash = gv_stashpv("DynaLoader", GV_ADDWARN);
1011 	hv_iterinit(stash);
1012 	while ((sv = hv_iternextsv(stash, &key, &klen)))
1013 	{
1014 		if (!isGV_with_GP(sv) || !GvCV(sv))
1015 			continue;
1016 		SvREFCNT_dec(GvCV(sv)); /* free the CV */
1017 		GvCV_set(sv, NULL);		/* prevent call via GV */
1018 	}
1019 	hv_clear(stash);
1020 
1021 	/* invalidate assorted caches */
1022 	++PL_sub_generation;
1023 	hv_clear(PL_stashcache);
1024 
1025 	/*
1026 	 * Execute plperl.on_plperl_init in the locked-down interpreter
1027 	 */
1028 	if (plperl_on_plperl_init && *plperl_on_plperl_init)
1029 	{
1030 		eval_pv(plperl_on_plperl_init, FALSE);
1031 		/* XXX need to find a way to determine a better errcode here */
1032 		if (SvTRUE(ERRSV))
1033 			ereport(ERROR,
1034 					(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
1035 					 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
1036 					 errcontext("while executing plperl.on_plperl_init")));
1037 	}
1038 }
1039 
1040 
1041 /*
1042  * Initialize the current Perl interpreter as an untrusted interp
1043  */
1044 static void
plperl_untrusted_init(void)1045 plperl_untrusted_init(void)
1046 {
1047 	dTHX;
1048 
1049 	/*
1050 	 * Nothing to do except execute plperl.on_plperlu_init
1051 	 */
1052 	if (plperl_on_plperlu_init && *plperl_on_plperlu_init)
1053 	{
1054 		eval_pv(plperl_on_plperlu_init, FALSE);
1055 		if (SvTRUE(ERRSV))
1056 			ereport(ERROR,
1057 					(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
1058 					 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
1059 					 errcontext("while executing plperl.on_plperlu_init")));
1060 	}
1061 }
1062 
1063 
1064 /*
1065  * Perl likes to put a newline after its error messages; clean up such
1066  */
1067 static char *
strip_trailing_ws(const char * msg)1068 strip_trailing_ws(const char *msg)
1069 {
1070 	char	   *res = pstrdup(msg);
1071 	int			len = strlen(res);
1072 
1073 	while (len > 0 && isspace((unsigned char) res[len - 1]))
1074 		res[--len] = '\0';
1075 	return res;
1076 }
1077 
1078 
1079 /* Build a tuple from a hash. */
1080 
1081 static HeapTuple
plperl_build_tuple_result(HV * perlhash,TupleDesc td)1082 plperl_build_tuple_result(HV *perlhash, TupleDesc td)
1083 {
1084 	dTHX;
1085 	Datum	   *values;
1086 	bool	   *nulls;
1087 	HE		   *he;
1088 	HeapTuple	tup;
1089 
1090 	values = palloc0(sizeof(Datum) * td->natts);
1091 	nulls = palloc(sizeof(bool) * td->natts);
1092 	memset(nulls, true, sizeof(bool) * td->natts);
1093 
1094 	hv_iterinit(perlhash);
1095 	while ((he = hv_iternext(perlhash)))
1096 	{
1097 		SV		   *val = HeVAL(he);
1098 		char	   *key = hek2cstr(he);
1099 		int			attn = SPI_fnumber(td, key);
1100 		Form_pg_attribute attr = TupleDescAttr(td, attn - 1);
1101 
1102 		if (attn == SPI_ERROR_NOATTRIBUTE)
1103 			ereport(ERROR,
1104 					(errcode(ERRCODE_UNDEFINED_COLUMN),
1105 					 errmsg("Perl hash contains nonexistent column \"%s\"",
1106 							key)));
1107 		if (attn <= 0)
1108 			ereport(ERROR,
1109 					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1110 					 errmsg("cannot set system attribute \"%s\"",
1111 							key)));
1112 
1113 		values[attn - 1] = plperl_sv_to_datum(val,
1114 											  attr->atttypid,
1115 											  attr->atttypmod,
1116 											  NULL,
1117 											  NULL,
1118 											  InvalidOid,
1119 											  &nulls[attn - 1]);
1120 
1121 		pfree(key);
1122 	}
1123 	hv_iterinit(perlhash);
1124 
1125 	tup = heap_form_tuple(td, values, nulls);
1126 	pfree(values);
1127 	pfree(nulls);
1128 	return tup;
1129 }
1130 
1131 /* convert a hash reference to a datum */
1132 static Datum
plperl_hash_to_datum(SV * src,TupleDesc td)1133 plperl_hash_to_datum(SV *src, TupleDesc td)
1134 {
1135 	HeapTuple	tup = plperl_build_tuple_result((HV *) SvRV(src), td);
1136 
1137 	return HeapTupleGetDatum(tup);
1138 }
1139 
1140 /*
1141  * if we are an array ref return the reference. this is special in that if we
1142  * are a PostgreSQL::InServer::ARRAY object we will return the 'magic' array.
1143  */
1144 static SV  *
get_perl_array_ref(SV * sv)1145 get_perl_array_ref(SV *sv)
1146 {
1147 	dTHX;
1148 
1149 	if (SvOK(sv) && SvROK(sv))
1150 	{
1151 		if (SvTYPE(SvRV(sv)) == SVt_PVAV)
1152 			return sv;
1153 		else if (sv_isa(sv, "PostgreSQL::InServer::ARRAY"))
1154 		{
1155 			HV		   *hv = (HV *) SvRV(sv);
1156 			SV		  **sav = hv_fetch_string(hv, "array");
1157 
1158 			if (*sav && SvOK(*sav) && SvROK(*sav) &&
1159 				SvTYPE(SvRV(*sav)) == SVt_PVAV)
1160 				return *sav;
1161 
1162 			elog(ERROR, "could not get array reference from PostgreSQL::InServer::ARRAY object");
1163 		}
1164 	}
1165 	return NULL;
1166 }
1167 
1168 /*
1169  * helper function for plperl_array_to_datum, recurses for multi-D arrays
1170  */
1171 static void
array_to_datum_internal(AV * av,ArrayBuildState * astate,int * ndims,int * dims,int cur_depth,Oid arraytypid,Oid elemtypid,int32 typmod,FmgrInfo * finfo,Oid typioparam)1172 array_to_datum_internal(AV *av, ArrayBuildState *astate,
1173 						int *ndims, int *dims, int cur_depth,
1174 						Oid arraytypid, Oid elemtypid, int32 typmod,
1175 						FmgrInfo *finfo, Oid typioparam)
1176 {
1177 	dTHX;
1178 	int			i;
1179 	int			len = av_len(av) + 1;
1180 
1181 	for (i = 0; i < len; i++)
1182 	{
1183 		/* fetch the array element */
1184 		SV		  **svp = av_fetch(av, i, FALSE);
1185 
1186 		/* see if this element is an array, if so get that */
1187 		SV		   *sav = svp ? get_perl_array_ref(*svp) : NULL;
1188 
1189 		/* multi-dimensional array? */
1190 		if (sav)
1191 		{
1192 			AV		   *nav = (AV *) SvRV(sav);
1193 
1194 			/* dimensionality checks */
1195 			if (cur_depth + 1 > MAXDIM)
1196 				ereport(ERROR,
1197 						(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1198 						 errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
1199 								cur_depth + 1, MAXDIM)));
1200 
1201 			/* set size when at first element in this level, else compare */
1202 			if (i == 0 && *ndims == cur_depth)
1203 			{
1204 				dims[*ndims] = av_len(nav) + 1;
1205 				(*ndims)++;
1206 			}
1207 			else if (av_len(nav) + 1 != dims[cur_depth])
1208 				ereport(ERROR,
1209 						(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1210 						 errmsg("multidimensional arrays must have array expressions with matching dimensions")));
1211 
1212 			/* recurse to fetch elements of this sub-array */
1213 			array_to_datum_internal(nav, astate,
1214 									ndims, dims, cur_depth + 1,
1215 									arraytypid, elemtypid, typmod,
1216 									finfo, typioparam);
1217 		}
1218 		else
1219 		{
1220 			Datum		dat;
1221 			bool		isnull;
1222 
1223 			/* scalar after some sub-arrays at same level? */
1224 			if (*ndims != cur_depth)
1225 				ereport(ERROR,
1226 						(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1227 						 errmsg("multidimensional arrays must have array expressions with matching dimensions")));
1228 
1229 			dat = plperl_sv_to_datum(svp ? *svp : NULL,
1230 									 elemtypid,
1231 									 typmod,
1232 									 NULL,
1233 									 finfo,
1234 									 typioparam,
1235 									 &isnull);
1236 
1237 			(void) accumArrayResult(astate, dat, isnull,
1238 									elemtypid, CurrentMemoryContext);
1239 		}
1240 	}
1241 }
1242 
1243 /*
1244  * convert perl array ref to a datum
1245  */
1246 static Datum
plperl_array_to_datum(SV * src,Oid typid,int32 typmod)1247 plperl_array_to_datum(SV *src, Oid typid, int32 typmod)
1248 {
1249 	dTHX;
1250 	ArrayBuildState *astate;
1251 	Oid			elemtypid;
1252 	FmgrInfo	finfo;
1253 	Oid			typioparam;
1254 	int			dims[MAXDIM];
1255 	int			lbs[MAXDIM];
1256 	int			ndims = 1;
1257 	int			i;
1258 
1259 	elemtypid = get_element_type(typid);
1260 	if (!elemtypid)
1261 		ereport(ERROR,
1262 				(errcode(ERRCODE_DATATYPE_MISMATCH),
1263 				 errmsg("cannot convert Perl array to non-array type %s",
1264 						format_type_be(typid))));
1265 
1266 	astate = initArrayResult(elemtypid, CurrentMemoryContext, true);
1267 
1268 	_sv_to_datum_finfo(elemtypid, &finfo, &typioparam);
1269 
1270 	memset(dims, 0, sizeof(dims));
1271 	dims[0] = av_len((AV *) SvRV(src)) + 1;
1272 
1273 	array_to_datum_internal((AV *) SvRV(src), astate,
1274 							&ndims, dims, 1,
1275 							typid, elemtypid, typmod,
1276 							&finfo, typioparam);
1277 
1278 	/* ensure we get zero-D array for no inputs, as per PG convention */
1279 	if (dims[0] <= 0)
1280 		ndims = 0;
1281 
1282 	for (i = 0; i < ndims; i++)
1283 		lbs[i] = 1;
1284 
1285 	return makeMdArrayResult(astate, ndims, dims, lbs,
1286 							 CurrentMemoryContext, true);
1287 }
1288 
1289 /* Get the information needed to convert data to the specified PG type */
1290 static void
_sv_to_datum_finfo(Oid typid,FmgrInfo * finfo,Oid * typioparam)1291 _sv_to_datum_finfo(Oid typid, FmgrInfo *finfo, Oid *typioparam)
1292 {
1293 	Oid			typinput;
1294 
1295 	/* XXX would be better to cache these lookups */
1296 	getTypeInputInfo(typid,
1297 					 &typinput, typioparam);
1298 	fmgr_info(typinput, finfo);
1299 }
1300 
1301 /*
1302  * convert Perl SV to PG datum of type typid, typmod typmod
1303  *
1304  * Pass the PL/Perl function's fcinfo when attempting to convert to the
1305  * function's result type; otherwise pass NULL.  This is used when we need to
1306  * resolve the actual result type of a function returning RECORD.
1307  *
1308  * finfo and typioparam should be the results of _sv_to_datum_finfo for the
1309  * given typid, or NULL/InvalidOid to let this function do the lookups.
1310  *
1311  * *isnull is an output parameter.
1312  */
1313 static Datum
plperl_sv_to_datum(SV * sv,Oid typid,int32 typmod,FunctionCallInfo fcinfo,FmgrInfo * finfo,Oid typioparam,bool * isnull)1314 plperl_sv_to_datum(SV *sv, Oid typid, int32 typmod,
1315 				   FunctionCallInfo fcinfo,
1316 				   FmgrInfo *finfo, Oid typioparam,
1317 				   bool *isnull)
1318 {
1319 	FmgrInfo	tmp;
1320 	Oid			funcid;
1321 
1322 	/* we might recurse */
1323 	check_stack_depth();
1324 
1325 	*isnull = false;
1326 
1327 	/*
1328 	 * Return NULL if result is undef, or if we're in a function returning
1329 	 * VOID.  In the latter case, we should pay no attention to the last Perl
1330 	 * statement's result, and this is a convenient means to ensure that.
1331 	 */
1332 	if (!sv || !SvOK(sv) || typid == VOIDOID)
1333 	{
1334 		/* look up type info if they did not pass it */
1335 		if (!finfo)
1336 		{
1337 			_sv_to_datum_finfo(typid, &tmp, &typioparam);
1338 			finfo = &tmp;
1339 		}
1340 		*isnull = true;
1341 		/* must call typinput in case it wants to reject NULL */
1342 		return InputFunctionCall(finfo, NULL, typioparam, typmod);
1343 	}
1344 	else if ((funcid = get_transform_tosql(typid, current_call_data->prodesc->lang_oid, current_call_data->prodesc->trftypes)))
1345 		return OidFunctionCall1(funcid, PointerGetDatum(sv));
1346 	else if (SvROK(sv))
1347 	{
1348 		/* handle references */
1349 		SV		   *sav = get_perl_array_ref(sv);
1350 
1351 		if (sav)
1352 		{
1353 			/* handle an arrayref */
1354 			return plperl_array_to_datum(sav, typid, typmod);
1355 		}
1356 		else if (SvTYPE(SvRV(sv)) == SVt_PVHV)
1357 		{
1358 			/* handle a hashref */
1359 			Datum		ret;
1360 			TupleDesc	td;
1361 			bool		isdomain;
1362 
1363 			if (!type_is_rowtype(typid))
1364 				ereport(ERROR,
1365 						(errcode(ERRCODE_DATATYPE_MISMATCH),
1366 						 errmsg("cannot convert Perl hash to non-composite type %s",
1367 								format_type_be(typid))));
1368 
1369 			td = lookup_rowtype_tupdesc_domain(typid, typmod, true);
1370 			if (td != NULL)
1371 			{
1372 				/* Did we look through a domain? */
1373 				isdomain = (typid != td->tdtypeid);
1374 			}
1375 			else
1376 			{
1377 				/* Must be RECORD, try to resolve based on call info */
1378 				TypeFuncClass funcclass;
1379 
1380 				if (fcinfo)
1381 					funcclass = get_call_result_type(fcinfo, &typid, &td);
1382 				else
1383 					funcclass = TYPEFUNC_OTHER;
1384 				if (funcclass != TYPEFUNC_COMPOSITE &&
1385 					funcclass != TYPEFUNC_COMPOSITE_DOMAIN)
1386 					ereport(ERROR,
1387 							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1388 							 errmsg("function returning record called in context "
1389 									"that cannot accept type record")));
1390 				Assert(td);
1391 				isdomain = (funcclass == TYPEFUNC_COMPOSITE_DOMAIN);
1392 			}
1393 
1394 			ret = plperl_hash_to_datum(sv, td);
1395 
1396 			if (isdomain)
1397 				domain_check(ret, false, typid, NULL, NULL);
1398 
1399 			/* Release on the result of get_call_result_type is harmless */
1400 			ReleaseTupleDesc(td);
1401 
1402 			return ret;
1403 		}
1404 
1405 		/*
1406 		 * If it's a reference to something else, such as a scalar, just
1407 		 * recursively look through the reference.
1408 		 */
1409 		return plperl_sv_to_datum(SvRV(sv), typid, typmod,
1410 								  fcinfo, finfo, typioparam,
1411 								  isnull);
1412 	}
1413 	else
1414 	{
1415 		/* handle a string/number */
1416 		Datum		ret;
1417 		char	   *str = sv2cstr(sv);
1418 
1419 		/* did not pass in any typeinfo? look it up */
1420 		if (!finfo)
1421 		{
1422 			_sv_to_datum_finfo(typid, &tmp, &typioparam);
1423 			finfo = &tmp;
1424 		}
1425 
1426 		ret = InputFunctionCall(finfo, str, typioparam, typmod);
1427 		pfree(str);
1428 
1429 		return ret;
1430 	}
1431 }
1432 
1433 /* Convert the perl SV to a string returned by the type output function */
1434 char *
plperl_sv_to_literal(SV * sv,char * fqtypename)1435 plperl_sv_to_literal(SV *sv, char *fqtypename)
1436 {
1437 	Datum		str = CStringGetDatum(fqtypename);
1438 	Oid			typid = DirectFunctionCall1(regtypein, str);
1439 	Oid			typoutput;
1440 	Datum		datum;
1441 	bool		typisvarlena,
1442 				isnull;
1443 
1444 	if (!OidIsValid(typid))
1445 		ereport(ERROR,
1446 				(errcode(ERRCODE_UNDEFINED_OBJECT),
1447 				 errmsg("lookup failed for type %s", fqtypename)));
1448 
1449 	datum = plperl_sv_to_datum(sv,
1450 							   typid, -1,
1451 							   NULL, NULL, InvalidOid,
1452 							   &isnull);
1453 
1454 	if (isnull)
1455 		return NULL;
1456 
1457 	getTypeOutputInfo(typid,
1458 					  &typoutput, &typisvarlena);
1459 
1460 	return OidOutputFunctionCall(typoutput, datum);
1461 }
1462 
1463 /*
1464  * Convert PostgreSQL array datum to a perl array reference.
1465  *
1466  * typid is arg's OID, which must be an array type.
1467  */
1468 static SV  *
plperl_ref_from_pg_array(Datum arg,Oid typid)1469 plperl_ref_from_pg_array(Datum arg, Oid typid)
1470 {
1471 	dTHX;
1472 	ArrayType  *ar = DatumGetArrayTypeP(arg);
1473 	Oid			elementtype = ARR_ELEMTYPE(ar);
1474 	int16		typlen;
1475 	bool		typbyval;
1476 	char		typalign,
1477 				typdelim;
1478 	Oid			typioparam;
1479 	Oid			typoutputfunc;
1480 	Oid			transform_funcid;
1481 	int			i,
1482 				nitems,
1483 			   *dims;
1484 	plperl_array_info *info;
1485 	SV		   *av;
1486 	HV		   *hv;
1487 
1488 	/*
1489 	 * Currently we make no effort to cache any of the stuff we look up here,
1490 	 * which is bad.
1491 	 */
1492 	info = palloc0(sizeof(plperl_array_info));
1493 
1494 	/* get element type information, including output conversion function */
1495 	get_type_io_data(elementtype, IOFunc_output,
1496 					 &typlen, &typbyval, &typalign,
1497 					 &typdelim, &typioparam, &typoutputfunc);
1498 
1499 	/* Check for a transform function */
1500 	transform_funcid = get_transform_fromsql(elementtype,
1501 											 current_call_data->prodesc->lang_oid,
1502 											 current_call_data->prodesc->trftypes);
1503 
1504 	/* Look up transform or output function as appropriate */
1505 	if (OidIsValid(transform_funcid))
1506 		fmgr_info(transform_funcid, &info->transform_proc);
1507 	else
1508 		fmgr_info(typoutputfunc, &info->proc);
1509 
1510 	info->elem_is_rowtype = type_is_rowtype(elementtype);
1511 
1512 	/* Get the number and bounds of array dimensions */
1513 	info->ndims = ARR_NDIM(ar);
1514 	dims = ARR_DIMS(ar);
1515 
1516 	/* No dimensions? Return an empty array */
1517 	if (info->ndims == 0)
1518 	{
1519 		av = newRV_noinc((SV *) newAV());
1520 	}
1521 	else
1522 	{
1523 		deconstruct_array(ar, elementtype, typlen, typbyval,
1524 						  typalign, &info->elements, &info->nulls,
1525 						  &nitems);
1526 
1527 		/* Get total number of elements in each dimension */
1528 		info->nelems = palloc(sizeof(int) * info->ndims);
1529 		info->nelems[0] = nitems;
1530 		for (i = 1; i < info->ndims; i++)
1531 			info->nelems[i] = info->nelems[i - 1] / dims[i - 1];
1532 
1533 		av = split_array(info, 0, nitems, 0);
1534 	}
1535 
1536 	hv = newHV();
1537 	(void) hv_store(hv, "array", 5, av, 0);
1538 	(void) hv_store(hv, "typeoid", 7, newSVuv(typid), 0);
1539 
1540 	return sv_bless(newRV_noinc((SV *) hv),
1541 					gv_stashpv("PostgreSQL::InServer::ARRAY", 0));
1542 }
1543 
1544 /*
1545  * Recursively form array references from splices of the initial array
1546  */
1547 static SV  *
split_array(plperl_array_info * info,int first,int last,int nest)1548 split_array(plperl_array_info *info, int first, int last, int nest)
1549 {
1550 	dTHX;
1551 	int			i;
1552 	AV		   *result;
1553 
1554 	/* we should only be called when we have something to split */
1555 	Assert(info->ndims > 0);
1556 
1557 	/* since this function recurses, it could be driven to stack overflow */
1558 	check_stack_depth();
1559 
1560 	/*
1561 	 * Base case, return a reference to a single-dimensional array
1562 	 */
1563 	if (nest >= info->ndims - 1)
1564 		return make_array_ref(info, first, last);
1565 
1566 	result = newAV();
1567 	for (i = first; i < last; i += info->nelems[nest + 1])
1568 	{
1569 		/* Recursively form references to arrays of lower dimensions */
1570 		SV		   *ref = split_array(info, i, i + info->nelems[nest + 1], nest + 1);
1571 
1572 		av_push(result, ref);
1573 	}
1574 	return newRV_noinc((SV *) result);
1575 }
1576 
1577 /*
1578  * Create a Perl reference from a one-dimensional C array, converting
1579  * composite type elements to hash references.
1580  */
1581 static SV  *
make_array_ref(plperl_array_info * info,int first,int last)1582 make_array_ref(plperl_array_info *info, int first, int last)
1583 {
1584 	dTHX;
1585 	int			i;
1586 	AV		   *result = newAV();
1587 
1588 	for (i = first; i < last; i++)
1589 	{
1590 		if (info->nulls[i])
1591 		{
1592 			/*
1593 			 * We can't use &PL_sv_undef here.  See "AVs, HVs and undefined
1594 			 * values" in perlguts.
1595 			 */
1596 			av_push(result, newSV(0));
1597 		}
1598 		else
1599 		{
1600 			Datum		itemvalue = info->elements[i];
1601 
1602 			if (info->transform_proc.fn_oid)
1603 				av_push(result, (SV *) DatumGetPointer(FunctionCall1(&info->transform_proc, itemvalue)));
1604 			else if (info->elem_is_rowtype)
1605 				/* Handle composite type elements */
1606 				av_push(result, plperl_hash_from_datum(itemvalue));
1607 			else
1608 			{
1609 				char	   *val = OutputFunctionCall(&info->proc, itemvalue);
1610 
1611 				av_push(result, cstr2sv(val));
1612 			}
1613 		}
1614 	}
1615 	return newRV_noinc((SV *) result);
1616 }
1617 
1618 /* Set up the arguments for a trigger call. */
1619 static SV  *
plperl_trigger_build_args(FunctionCallInfo fcinfo)1620 plperl_trigger_build_args(FunctionCallInfo fcinfo)
1621 {
1622 	dTHX;
1623 	TriggerData *tdata;
1624 	TupleDesc	tupdesc;
1625 	int			i;
1626 	char	   *level;
1627 	char	   *event;
1628 	char	   *relid;
1629 	char	   *when;
1630 	HV		   *hv;
1631 
1632 	hv = newHV();
1633 	hv_ksplit(hv, 12);			/* pre-grow the hash */
1634 
1635 	tdata = (TriggerData *) fcinfo->context;
1636 	tupdesc = tdata->tg_relation->rd_att;
1637 
1638 	relid = DatumGetCString(
1639 							DirectFunctionCall1(oidout,
1640 												ObjectIdGetDatum(tdata->tg_relation->rd_id)
1641 												)
1642 		);
1643 
1644 	hv_store_string(hv, "name", cstr2sv(tdata->tg_trigger->tgname));
1645 	hv_store_string(hv, "relid", cstr2sv(relid));
1646 
1647 	if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
1648 	{
1649 		event = "INSERT";
1650 		if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
1651 			hv_store_string(hv, "new",
1652 							plperl_hash_from_tuple(tdata->tg_trigtuple,
1653 												   tupdesc));
1654 	}
1655 	else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
1656 	{
1657 		event = "DELETE";
1658 		if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
1659 			hv_store_string(hv, "old",
1660 							plperl_hash_from_tuple(tdata->tg_trigtuple,
1661 												   tupdesc));
1662 	}
1663 	else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
1664 	{
1665 		event = "UPDATE";
1666 		if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
1667 		{
1668 			hv_store_string(hv, "old",
1669 							plperl_hash_from_tuple(tdata->tg_trigtuple,
1670 												   tupdesc));
1671 			hv_store_string(hv, "new",
1672 							plperl_hash_from_tuple(tdata->tg_newtuple,
1673 												   tupdesc));
1674 		}
1675 	}
1676 	else if (TRIGGER_FIRED_BY_TRUNCATE(tdata->tg_event))
1677 		event = "TRUNCATE";
1678 	else
1679 		event = "UNKNOWN";
1680 
1681 	hv_store_string(hv, "event", cstr2sv(event));
1682 	hv_store_string(hv, "argc", newSViv(tdata->tg_trigger->tgnargs));
1683 
1684 	if (tdata->tg_trigger->tgnargs > 0)
1685 	{
1686 		AV		   *av = newAV();
1687 
1688 		av_extend(av, tdata->tg_trigger->tgnargs);
1689 		for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
1690 			av_push(av, cstr2sv(tdata->tg_trigger->tgargs[i]));
1691 		hv_store_string(hv, "args", newRV_noinc((SV *) av));
1692 	}
1693 
1694 	hv_store_string(hv, "relname",
1695 					cstr2sv(SPI_getrelname(tdata->tg_relation)));
1696 
1697 	hv_store_string(hv, "table_name",
1698 					cstr2sv(SPI_getrelname(tdata->tg_relation)));
1699 
1700 	hv_store_string(hv, "table_schema",
1701 					cstr2sv(SPI_getnspname(tdata->tg_relation)));
1702 
1703 	if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
1704 		when = "BEFORE";
1705 	else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
1706 		when = "AFTER";
1707 	else if (TRIGGER_FIRED_INSTEAD(tdata->tg_event))
1708 		when = "INSTEAD OF";
1709 	else
1710 		when = "UNKNOWN";
1711 	hv_store_string(hv, "when", cstr2sv(when));
1712 
1713 	if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
1714 		level = "ROW";
1715 	else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
1716 		level = "STATEMENT";
1717 	else
1718 		level = "UNKNOWN";
1719 	hv_store_string(hv, "level", cstr2sv(level));
1720 
1721 	return newRV_noinc((SV *) hv);
1722 }
1723 
1724 
1725 /* Set up the arguments for an event trigger call. */
1726 static SV  *
plperl_event_trigger_build_args(FunctionCallInfo fcinfo)1727 plperl_event_trigger_build_args(FunctionCallInfo fcinfo)
1728 {
1729 	dTHX;
1730 	EventTriggerData *tdata;
1731 	HV		   *hv;
1732 
1733 	hv = newHV();
1734 
1735 	tdata = (EventTriggerData *) fcinfo->context;
1736 
1737 	hv_store_string(hv, "event", cstr2sv(tdata->event));
1738 	hv_store_string(hv, "tag", cstr2sv(tdata->tag));
1739 
1740 	return newRV_noinc((SV *) hv);
1741 }
1742 
1743 /* Construct the modified new tuple to be returned from a trigger. */
1744 static HeapTuple
plperl_modify_tuple(HV * hvTD,TriggerData * tdata,HeapTuple otup)1745 plperl_modify_tuple(HV *hvTD, TriggerData *tdata, HeapTuple otup)
1746 {
1747 	dTHX;
1748 	SV		  **svp;
1749 	HV		   *hvNew;
1750 	HE		   *he;
1751 	HeapTuple	rtup;
1752 	TupleDesc	tupdesc;
1753 	int			natts;
1754 	Datum	   *modvalues;
1755 	bool	   *modnulls;
1756 	bool	   *modrepls;
1757 
1758 	svp = hv_fetch_string(hvTD, "new");
1759 	if (!svp)
1760 		ereport(ERROR,
1761 				(errcode(ERRCODE_UNDEFINED_COLUMN),
1762 				 errmsg("$_TD->{new} does not exist")));
1763 	if (!SvOK(*svp) || !SvROK(*svp) || SvTYPE(SvRV(*svp)) != SVt_PVHV)
1764 		ereport(ERROR,
1765 				(errcode(ERRCODE_DATATYPE_MISMATCH),
1766 				 errmsg("$_TD->{new} is not a hash reference")));
1767 	hvNew = (HV *) SvRV(*svp);
1768 
1769 	tupdesc = tdata->tg_relation->rd_att;
1770 	natts = tupdesc->natts;
1771 
1772 	modvalues = (Datum *) palloc0(natts * sizeof(Datum));
1773 	modnulls = (bool *) palloc0(natts * sizeof(bool));
1774 	modrepls = (bool *) palloc0(natts * sizeof(bool));
1775 
1776 	hv_iterinit(hvNew);
1777 	while ((he = hv_iternext(hvNew)))
1778 	{
1779 		char	   *key = hek2cstr(he);
1780 		SV		   *val = HeVAL(he);
1781 		int			attn = SPI_fnumber(tupdesc, key);
1782 		Form_pg_attribute attr = TupleDescAttr(tupdesc, attn - 1);
1783 
1784 		if (attn == SPI_ERROR_NOATTRIBUTE)
1785 			ereport(ERROR,
1786 					(errcode(ERRCODE_UNDEFINED_COLUMN),
1787 					 errmsg("Perl hash contains nonexistent column \"%s\"",
1788 							key)));
1789 		if (attn <= 0)
1790 			ereport(ERROR,
1791 					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1792 					 errmsg("cannot set system attribute \"%s\"",
1793 							key)));
1794 
1795 		modvalues[attn - 1] = plperl_sv_to_datum(val,
1796 												 attr->atttypid,
1797 												 attr->atttypmod,
1798 												 NULL,
1799 												 NULL,
1800 												 InvalidOid,
1801 												 &modnulls[attn - 1]);
1802 		modrepls[attn - 1] = true;
1803 
1804 		pfree(key);
1805 	}
1806 	hv_iterinit(hvNew);
1807 
1808 	rtup = heap_modify_tuple(otup, tupdesc, modvalues, modnulls, modrepls);
1809 
1810 	pfree(modvalues);
1811 	pfree(modnulls);
1812 	pfree(modrepls);
1813 
1814 	return rtup;
1815 }
1816 
1817 
1818 /*
1819  * There are three externally visible pieces to plperl: plperl_call_handler,
1820  * plperl_inline_handler, and plperl_validator.
1821  */
1822 
1823 /*
1824  * The call handler is called to run normal functions (including trigger
1825  * functions) that are defined in pg_proc.
1826  */
1827 PG_FUNCTION_INFO_V1(plperl_call_handler);
1828 
1829 Datum
plperl_call_handler(PG_FUNCTION_ARGS)1830 plperl_call_handler(PG_FUNCTION_ARGS)
1831 {
1832 	Datum		retval;
1833 	plperl_call_data *volatile save_call_data = current_call_data;
1834 	plperl_interp_desc *volatile oldinterp = plperl_active_interp;
1835 	plperl_call_data this_call_data;
1836 
1837 	/* Initialize current-call status record */
1838 	MemSet(&this_call_data, 0, sizeof(this_call_data));
1839 	this_call_data.fcinfo = fcinfo;
1840 
1841 	PG_TRY();
1842 	{
1843 		current_call_data = &this_call_data;
1844 		if (CALLED_AS_TRIGGER(fcinfo))
1845 			retval = PointerGetDatum(plperl_trigger_handler(fcinfo));
1846 		else if (CALLED_AS_EVENT_TRIGGER(fcinfo))
1847 		{
1848 			plperl_event_trigger_handler(fcinfo);
1849 			retval = (Datum) 0;
1850 		}
1851 		else
1852 			retval = plperl_func_handler(fcinfo);
1853 	}
1854 	PG_CATCH();
1855 	{
1856 		current_call_data = save_call_data;
1857 		activate_interpreter(oldinterp);
1858 		if (this_call_data.prodesc)
1859 			decrement_prodesc_refcount(this_call_data.prodesc);
1860 		PG_RE_THROW();
1861 	}
1862 	PG_END_TRY();
1863 
1864 	current_call_data = save_call_data;
1865 	activate_interpreter(oldinterp);
1866 	if (this_call_data.prodesc)
1867 		decrement_prodesc_refcount(this_call_data.prodesc);
1868 	return retval;
1869 }
1870 
1871 /*
1872  * The inline handler runs anonymous code blocks (DO blocks).
1873  */
1874 PG_FUNCTION_INFO_V1(plperl_inline_handler);
1875 
1876 Datum
plperl_inline_handler(PG_FUNCTION_ARGS)1877 plperl_inline_handler(PG_FUNCTION_ARGS)
1878 {
1879 	InlineCodeBlock *codeblock = (InlineCodeBlock *) PG_GETARG_POINTER(0);
1880 	FunctionCallInfoData fake_fcinfo;
1881 	FmgrInfo	flinfo;
1882 	plperl_proc_desc desc;
1883 	plperl_call_data *volatile save_call_data = current_call_data;
1884 	plperl_interp_desc *volatile oldinterp = plperl_active_interp;
1885 	plperl_call_data this_call_data;
1886 	ErrorContextCallback pl_error_context;
1887 
1888 	/* Initialize current-call status record */
1889 	MemSet(&this_call_data, 0, sizeof(this_call_data));
1890 
1891 	/* Set up a callback for error reporting */
1892 	pl_error_context.callback = plperl_inline_callback;
1893 	pl_error_context.previous = error_context_stack;
1894 	pl_error_context.arg = NULL;
1895 	error_context_stack = &pl_error_context;
1896 
1897 	/*
1898 	 * Set up a fake fcinfo and descriptor with just enough info to satisfy
1899 	 * plperl_call_perl_func().  In particular note that this sets things up
1900 	 * with no arguments passed, and a result type of VOID.
1901 	 */
1902 	MemSet(&fake_fcinfo, 0, sizeof(fake_fcinfo));
1903 	MemSet(&flinfo, 0, sizeof(flinfo));
1904 	MemSet(&desc, 0, sizeof(desc));
1905 	fake_fcinfo.flinfo = &flinfo;
1906 	flinfo.fn_oid = InvalidOid;
1907 	flinfo.fn_mcxt = CurrentMemoryContext;
1908 
1909 	desc.proname = "inline_code_block";
1910 	desc.fn_readonly = false;
1911 
1912 	desc.lang_oid = codeblock->langOid;
1913 	desc.trftypes = NIL;
1914 	desc.lanpltrusted = codeblock->langIsTrusted;
1915 
1916 	desc.fn_retistuple = false;
1917 	desc.fn_retisset = false;
1918 	desc.fn_retisarray = false;
1919 	desc.result_oid = InvalidOid;
1920 	desc.nargs = 0;
1921 	desc.reference = NULL;
1922 
1923 	this_call_data.fcinfo = &fake_fcinfo;
1924 	this_call_data.prodesc = &desc;
1925 	/* we do not bother with refcounting the fake prodesc */
1926 
1927 	PG_TRY();
1928 	{
1929 		SV		   *perlret;
1930 
1931 		current_call_data = &this_call_data;
1932 
1933 		if (SPI_connect_ext(codeblock->atomic ? 0 : SPI_OPT_NONATOMIC) != SPI_OK_CONNECT)
1934 			elog(ERROR, "could not connect to SPI manager");
1935 
1936 		select_perl_context(desc.lanpltrusted);
1937 
1938 		plperl_create_sub(&desc, codeblock->source_text, 0);
1939 
1940 		if (!desc.reference)	/* can this happen? */
1941 			elog(ERROR, "could not create internal procedure for anonymous code block");
1942 
1943 		perlret = plperl_call_perl_func(&desc, &fake_fcinfo);
1944 
1945 		SvREFCNT_dec_current(perlret);
1946 
1947 		if (SPI_finish() != SPI_OK_FINISH)
1948 			elog(ERROR, "SPI_finish() failed");
1949 	}
1950 	PG_CATCH();
1951 	{
1952 		if (desc.reference)
1953 			SvREFCNT_dec_current(desc.reference);
1954 		current_call_data = save_call_data;
1955 		activate_interpreter(oldinterp);
1956 		PG_RE_THROW();
1957 	}
1958 	PG_END_TRY();
1959 
1960 	if (desc.reference)
1961 		SvREFCNT_dec_current(desc.reference);
1962 
1963 	current_call_data = save_call_data;
1964 	activate_interpreter(oldinterp);
1965 
1966 	error_context_stack = pl_error_context.previous;
1967 
1968 	PG_RETURN_VOID();
1969 }
1970 
1971 /*
1972  * The validator is called during CREATE FUNCTION to validate the function
1973  * being created/replaced. The precise behavior of the validator may be
1974  * modified by the check_function_bodies GUC.
1975  */
1976 PG_FUNCTION_INFO_V1(plperl_validator);
1977 
1978 Datum
plperl_validator(PG_FUNCTION_ARGS)1979 plperl_validator(PG_FUNCTION_ARGS)
1980 {
1981 	Oid			funcoid = PG_GETARG_OID(0);
1982 	HeapTuple	tuple;
1983 	Form_pg_proc proc;
1984 	char		functyptype;
1985 	int			numargs;
1986 	Oid		   *argtypes;
1987 	char	  **argnames;
1988 	char	   *argmodes;
1989 	bool		is_trigger = false;
1990 	bool		is_event_trigger = false;
1991 	int			i;
1992 
1993 	if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
1994 		PG_RETURN_VOID();
1995 
1996 	/* Get the new function's pg_proc entry */
1997 	tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
1998 	if (!HeapTupleIsValid(tuple))
1999 		elog(ERROR, "cache lookup failed for function %u", funcoid);
2000 	proc = (Form_pg_proc) GETSTRUCT(tuple);
2001 
2002 	functyptype = get_typtype(proc->prorettype);
2003 
2004 	/* Disallow pseudotype result */
2005 	/* except for TRIGGER, EVTTRIGGER, RECORD, or VOID */
2006 	if (functyptype == TYPTYPE_PSEUDO)
2007 	{
2008 		/* we assume OPAQUE with no arguments means a trigger */
2009 		if (proc->prorettype == TRIGGEROID ||
2010 			(proc->prorettype == OPAQUEOID && proc->pronargs == 0))
2011 			is_trigger = true;
2012 		else if (proc->prorettype == EVTTRIGGEROID)
2013 			is_event_trigger = true;
2014 		else if (proc->prorettype != RECORDOID &&
2015 				 proc->prorettype != VOIDOID)
2016 			ereport(ERROR,
2017 					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2018 					 errmsg("PL/Perl functions cannot return type %s",
2019 							format_type_be(proc->prorettype))));
2020 	}
2021 
2022 	/* Disallow pseudotypes in arguments (either IN or OUT) */
2023 	numargs = get_func_arg_info(tuple,
2024 								&argtypes, &argnames, &argmodes);
2025 	for (i = 0; i < numargs; i++)
2026 	{
2027 		if (get_typtype(argtypes[i]) == TYPTYPE_PSEUDO &&
2028 			argtypes[i] != RECORDOID)
2029 			ereport(ERROR,
2030 					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2031 					 errmsg("PL/Perl functions cannot accept type %s",
2032 							format_type_be(argtypes[i]))));
2033 	}
2034 
2035 	ReleaseSysCache(tuple);
2036 
2037 	/* Postpone body checks if !check_function_bodies */
2038 	if (check_function_bodies)
2039 	{
2040 		(void) compile_plperl_function(funcoid, is_trigger, is_event_trigger);
2041 	}
2042 
2043 	/* the result of a validator is ignored */
2044 	PG_RETURN_VOID();
2045 }
2046 
2047 
2048 /*
2049  * plperlu likewise requires three externally visible functions:
2050  * plperlu_call_handler, plperlu_inline_handler, and plperlu_validator.
2051  * These are currently just aliases that send control to the plperl
2052  * handler functions, and we decide whether a particular function is
2053  * trusted or not by inspecting the actual pg_language tuple.
2054  */
2055 
2056 PG_FUNCTION_INFO_V1(plperlu_call_handler);
2057 
2058 Datum
plperlu_call_handler(PG_FUNCTION_ARGS)2059 plperlu_call_handler(PG_FUNCTION_ARGS)
2060 {
2061 	return plperl_call_handler(fcinfo);
2062 }
2063 
2064 PG_FUNCTION_INFO_V1(plperlu_inline_handler);
2065 
2066 Datum
plperlu_inline_handler(PG_FUNCTION_ARGS)2067 plperlu_inline_handler(PG_FUNCTION_ARGS)
2068 {
2069 	return plperl_inline_handler(fcinfo);
2070 }
2071 
2072 PG_FUNCTION_INFO_V1(plperlu_validator);
2073 
2074 Datum
plperlu_validator(PG_FUNCTION_ARGS)2075 plperlu_validator(PG_FUNCTION_ARGS)
2076 {
2077 	/* call plperl validator with our fcinfo so it gets our oid */
2078 	return plperl_validator(fcinfo);
2079 }
2080 
2081 
2082 /*
2083  * Uses mksafefunc/mkunsafefunc to create a subroutine whose text is
2084  * supplied in s, and returns a reference to it
2085  */
2086 static void
plperl_create_sub(plperl_proc_desc * prodesc,const char * s,Oid fn_oid)2087 plperl_create_sub(plperl_proc_desc *prodesc, const char *s, Oid fn_oid)
2088 {
2089 	dTHX;
2090 	dSP;
2091 	char		subname[NAMEDATALEN + 40];
2092 	HV		   *pragma_hv = newHV();
2093 	SV		   *subref = NULL;
2094 	int			count;
2095 
2096 	sprintf(subname, "%s__%u", prodesc->proname, fn_oid);
2097 
2098 	if (plperl_use_strict)
2099 		hv_store_string(pragma_hv, "strict", (SV *) newAV());
2100 
2101 	ENTER;
2102 	SAVETMPS;
2103 	PUSHMARK(SP);
2104 	EXTEND(SP, 4);
2105 	PUSHs(sv_2mortal(cstr2sv(subname)));
2106 	PUSHs(sv_2mortal(newRV_noinc((SV *) pragma_hv)));
2107 
2108 	/*
2109 	 * Use 'false' for $prolog in mkfunc, which is kept for compatibility in
2110 	 * case a module such as PostgreSQL::PLPerl::NYTprof replaces the function
2111 	 * compiler.
2112 	 */
2113 	PUSHs(&PL_sv_no);
2114 	PUSHs(sv_2mortal(cstr2sv(s)));
2115 	PUTBACK;
2116 
2117 	/*
2118 	 * G_KEEPERR seems to be needed here, else we don't recognize compile
2119 	 * errors properly.  Perhaps it's because there's another level of eval
2120 	 * inside mksafefunc?
2121 	 */
2122 	count = perl_call_pv("PostgreSQL::InServer::mkfunc",
2123 						 G_SCALAR | G_EVAL | G_KEEPERR);
2124 	SPAGAIN;
2125 
2126 	if (count == 1)
2127 	{
2128 		SV		   *sub_rv = (SV *) POPs;
2129 
2130 		if (sub_rv && SvROK(sub_rv) && SvTYPE(SvRV(sub_rv)) == SVt_PVCV)
2131 		{
2132 			subref = newRV_inc(SvRV(sub_rv));
2133 		}
2134 	}
2135 
2136 	PUTBACK;
2137 	FREETMPS;
2138 	LEAVE;
2139 
2140 	if (SvTRUE(ERRSV))
2141 		ereport(ERROR,
2142 				(errcode(ERRCODE_SYNTAX_ERROR),
2143 				 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV)))));
2144 
2145 	if (!subref)
2146 		ereport(ERROR,
2147 				(errcode(ERRCODE_SYNTAX_ERROR),
2148 				 errmsg("didn't get a CODE reference from compiling function \"%s\"",
2149 						prodesc->proname)));
2150 
2151 	prodesc->reference = subref;
2152 
2153 	return;
2154 }
2155 
2156 
2157 /**********************************************************************
2158  * plperl_init_shared_libs()		-
2159  **********************************************************************/
2160 
2161 static void
plperl_init_shared_libs(pTHX)2162 plperl_init_shared_libs(pTHX)
2163 {
2164 	char	   *file = __FILE__;
2165 
2166 	newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
2167 	newXS("PostgreSQL::InServer::Util::bootstrap",
2168 		  boot_PostgreSQL__InServer__Util, file);
2169 	/* newXS for...::SPI::bootstrap is in select_perl_context() */
2170 }
2171 
2172 
2173 static SV  *
plperl_call_perl_func(plperl_proc_desc * desc,FunctionCallInfo fcinfo)2174 plperl_call_perl_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo)
2175 {
2176 	dTHX;
2177 	dSP;
2178 	SV		   *retval;
2179 	int			i;
2180 	int			count;
2181 	Oid		   *argtypes = NULL;
2182 	int			nargs = 0;
2183 
2184 	ENTER;
2185 	SAVETMPS;
2186 
2187 	PUSHMARK(SP);
2188 	EXTEND(sp, desc->nargs);
2189 
2190 	/* Get signature for true functions; inline blocks have no args. */
2191 	if (fcinfo->flinfo->fn_oid)
2192 		get_func_signature(fcinfo->flinfo->fn_oid, &argtypes, &nargs);
2193 	Assert(nargs == desc->nargs);
2194 
2195 	for (i = 0; i < desc->nargs; i++)
2196 	{
2197 		if (fcinfo->argnull[i])
2198 			PUSHs(&PL_sv_undef);
2199 		else if (desc->arg_is_rowtype[i])
2200 		{
2201 			SV		   *sv = plperl_hash_from_datum(fcinfo->arg[i]);
2202 
2203 			PUSHs(sv_2mortal(sv));
2204 		}
2205 		else
2206 		{
2207 			SV		   *sv;
2208 			Oid			funcid;
2209 
2210 			if (OidIsValid(desc->arg_arraytype[i]))
2211 				sv = plperl_ref_from_pg_array(fcinfo->arg[i], desc->arg_arraytype[i]);
2212 			else if ((funcid = get_transform_fromsql(argtypes[i], current_call_data->prodesc->lang_oid, current_call_data->prodesc->trftypes)))
2213 				sv = (SV *) DatumGetPointer(OidFunctionCall1(funcid, fcinfo->arg[i]));
2214 			else
2215 			{
2216 				char	   *tmp;
2217 
2218 				tmp = OutputFunctionCall(&(desc->arg_out_func[i]),
2219 										 fcinfo->arg[i]);
2220 				sv = cstr2sv(tmp);
2221 				pfree(tmp);
2222 			}
2223 
2224 			PUSHs(sv_2mortal(sv));
2225 		}
2226 	}
2227 	PUTBACK;
2228 
2229 	/* Do NOT use G_KEEPERR here */
2230 	count = perl_call_sv(desc->reference, G_SCALAR | G_EVAL);
2231 
2232 	SPAGAIN;
2233 
2234 	if (count != 1)
2235 	{
2236 		PUTBACK;
2237 		FREETMPS;
2238 		LEAVE;
2239 		ereport(ERROR,
2240 				(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2241 				 errmsg("didn't get a return item from function")));
2242 	}
2243 
2244 	if (SvTRUE(ERRSV))
2245 	{
2246 		(void) POPs;
2247 		PUTBACK;
2248 		FREETMPS;
2249 		LEAVE;
2250 		/* XXX need to find a way to determine a better errcode here */
2251 		ereport(ERROR,
2252 				(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2253 				 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV)))));
2254 	}
2255 
2256 	retval = newSVsv(POPs);
2257 
2258 	PUTBACK;
2259 	FREETMPS;
2260 	LEAVE;
2261 
2262 	return retval;
2263 }
2264 
2265 
2266 static SV  *
plperl_call_perl_trigger_func(plperl_proc_desc * desc,FunctionCallInfo fcinfo,SV * td)2267 plperl_call_perl_trigger_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo,
2268 							  SV *td)
2269 {
2270 	dTHX;
2271 	dSP;
2272 	SV		   *retval,
2273 			   *TDsv;
2274 	int			i,
2275 				count;
2276 	Trigger    *tg_trigger = ((TriggerData *) fcinfo->context)->tg_trigger;
2277 
2278 	ENTER;
2279 	SAVETMPS;
2280 
2281 	TDsv = get_sv("main::_TD", 0);
2282 	if (!TDsv)
2283 		ereport(ERROR,
2284 				(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2285 				 errmsg("couldn't fetch $_TD")));
2286 
2287 	save_item(TDsv);			/* local $_TD */
2288 	sv_setsv(TDsv, td);
2289 
2290 	PUSHMARK(sp);
2291 	EXTEND(sp, tg_trigger->tgnargs);
2292 
2293 	for (i = 0; i < tg_trigger->tgnargs; i++)
2294 		PUSHs(sv_2mortal(cstr2sv(tg_trigger->tgargs[i])));
2295 	PUTBACK;
2296 
2297 	/* Do NOT use G_KEEPERR here */
2298 	count = perl_call_sv(desc->reference, G_SCALAR | G_EVAL);
2299 
2300 	SPAGAIN;
2301 
2302 	if (count != 1)
2303 	{
2304 		PUTBACK;
2305 		FREETMPS;
2306 		LEAVE;
2307 		ereport(ERROR,
2308 				(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2309 				 errmsg("didn't get a return item from trigger function")));
2310 	}
2311 
2312 	if (SvTRUE(ERRSV))
2313 	{
2314 		(void) POPs;
2315 		PUTBACK;
2316 		FREETMPS;
2317 		LEAVE;
2318 		/* XXX need to find a way to determine a better errcode here */
2319 		ereport(ERROR,
2320 				(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2321 				 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV)))));
2322 	}
2323 
2324 	retval = newSVsv(POPs);
2325 
2326 	PUTBACK;
2327 	FREETMPS;
2328 	LEAVE;
2329 
2330 	return retval;
2331 }
2332 
2333 
2334 static void
plperl_call_perl_event_trigger_func(plperl_proc_desc * desc,FunctionCallInfo fcinfo,SV * td)2335 plperl_call_perl_event_trigger_func(plperl_proc_desc *desc,
2336 									FunctionCallInfo fcinfo,
2337 									SV *td)
2338 {
2339 	dTHX;
2340 	dSP;
2341 	SV		   *retval,
2342 			   *TDsv;
2343 	int			count;
2344 
2345 	ENTER;
2346 	SAVETMPS;
2347 
2348 	TDsv = get_sv("main::_TD", 0);
2349 	if (!TDsv)
2350 		ereport(ERROR,
2351 				(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2352 				 errmsg("couldn't fetch $_TD")));
2353 
2354 	save_item(TDsv);			/* local $_TD */
2355 	sv_setsv(TDsv, td);
2356 
2357 	PUSHMARK(sp);
2358 	PUTBACK;
2359 
2360 	/* Do NOT use G_KEEPERR here */
2361 	count = perl_call_sv(desc->reference, G_SCALAR | G_EVAL);
2362 
2363 	SPAGAIN;
2364 
2365 	if (count != 1)
2366 	{
2367 		PUTBACK;
2368 		FREETMPS;
2369 		LEAVE;
2370 		ereport(ERROR,
2371 				(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2372 				 errmsg("didn't get a return item from trigger function")));
2373 	}
2374 
2375 	if (SvTRUE(ERRSV))
2376 	{
2377 		(void) POPs;
2378 		PUTBACK;
2379 		FREETMPS;
2380 		LEAVE;
2381 		/* XXX need to find a way to determine a better errcode here */
2382 		ereport(ERROR,
2383 				(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2384 				 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV)))));
2385 	}
2386 
2387 	retval = newSVsv(POPs);
2388 	(void) retval;				/* silence compiler warning */
2389 
2390 	PUTBACK;
2391 	FREETMPS;
2392 	LEAVE;
2393 
2394 	return;
2395 }
2396 
2397 static Datum
plperl_func_handler(PG_FUNCTION_ARGS)2398 plperl_func_handler(PG_FUNCTION_ARGS)
2399 {
2400 	bool		nonatomic;
2401 	plperl_proc_desc *prodesc;
2402 	SV		   *perlret;
2403 	Datum		retval = 0;
2404 	ReturnSetInfo *rsi;
2405 	ErrorContextCallback pl_error_context;
2406 
2407 	nonatomic = fcinfo->context &&
2408 		IsA(fcinfo->context, CallContext) &&
2409 		!castNode(CallContext, fcinfo->context)->atomic;
2410 
2411 	if (SPI_connect_ext(nonatomic ? SPI_OPT_NONATOMIC : 0) != SPI_OK_CONNECT)
2412 		elog(ERROR, "could not connect to SPI manager");
2413 
2414 	prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, false, false);
2415 	current_call_data->prodesc = prodesc;
2416 	increment_prodesc_refcount(prodesc);
2417 
2418 	/* Set a callback for error reporting */
2419 	pl_error_context.callback = plperl_exec_callback;
2420 	pl_error_context.previous = error_context_stack;
2421 	pl_error_context.arg = prodesc->proname;
2422 	error_context_stack = &pl_error_context;
2423 
2424 	rsi = (ReturnSetInfo *) fcinfo->resultinfo;
2425 
2426 	if (prodesc->fn_retisset)
2427 	{
2428 		/* Check context before allowing the call to go through */
2429 		if (!rsi || !IsA(rsi, ReturnSetInfo) ||
2430 			(rsi->allowedModes & SFRM_Materialize) == 0)
2431 			ereport(ERROR,
2432 					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2433 					 errmsg("set-valued function called in context that "
2434 							"cannot accept a set")));
2435 	}
2436 
2437 	activate_interpreter(prodesc->interp);
2438 
2439 	perlret = plperl_call_perl_func(prodesc, fcinfo);
2440 
2441 	/************************************************************
2442 	 * Disconnect from SPI manager and then create the return
2443 	 * values datum (if the input function does a palloc for it
2444 	 * this must not be allocated in the SPI memory context
2445 	 * because SPI_finish would free it).
2446 	 ************************************************************/
2447 	if (SPI_finish() != SPI_OK_FINISH)
2448 		elog(ERROR, "SPI_finish() failed");
2449 
2450 	if (prodesc->fn_retisset)
2451 	{
2452 		SV		   *sav;
2453 
2454 		/*
2455 		 * If the Perl function returned an arrayref, we pretend that it
2456 		 * called return_next() for each element of the array, to handle old
2457 		 * SRFs that didn't know about return_next(). Any other sort of return
2458 		 * value is an error, except undef which means return an empty set.
2459 		 */
2460 		sav = get_perl_array_ref(perlret);
2461 		if (sav)
2462 		{
2463 			dTHX;
2464 			int			i = 0;
2465 			SV		  **svp = 0;
2466 			AV		   *rav = (AV *) SvRV(sav);
2467 
2468 			while ((svp = av_fetch(rav, i, FALSE)) != NULL)
2469 			{
2470 				plperl_return_next_internal(*svp);
2471 				i++;
2472 			}
2473 		}
2474 		else if (SvOK(perlret))
2475 		{
2476 			ereport(ERROR,
2477 					(errcode(ERRCODE_DATATYPE_MISMATCH),
2478 					 errmsg("set-returning PL/Perl function must return "
2479 							"reference to array or use return_next")));
2480 		}
2481 
2482 		rsi->returnMode = SFRM_Materialize;
2483 		if (current_call_data->tuple_store)
2484 		{
2485 			rsi->setResult = current_call_data->tuple_store;
2486 			rsi->setDesc = current_call_data->ret_tdesc;
2487 		}
2488 		retval = (Datum) 0;
2489 	}
2490 	else if (prodesc->result_oid)
2491 	{
2492 		retval = plperl_sv_to_datum(perlret,
2493 									prodesc->result_oid,
2494 									-1,
2495 									fcinfo,
2496 									&prodesc->result_in_func,
2497 									prodesc->result_typioparam,
2498 									&fcinfo->isnull);
2499 
2500 		if (fcinfo->isnull && rsi && IsA(rsi, ReturnSetInfo))
2501 			rsi->isDone = ExprEndResult;
2502 	}
2503 
2504 	/* Restore the previous error callback */
2505 	error_context_stack = pl_error_context.previous;
2506 
2507 	SvREFCNT_dec_current(perlret);
2508 
2509 	return retval;
2510 }
2511 
2512 
2513 static Datum
plperl_trigger_handler(PG_FUNCTION_ARGS)2514 plperl_trigger_handler(PG_FUNCTION_ARGS)
2515 {
2516 	plperl_proc_desc *prodesc;
2517 	SV		   *perlret;
2518 	Datum		retval;
2519 	SV		   *svTD;
2520 	HV		   *hvTD;
2521 	ErrorContextCallback pl_error_context;
2522 	TriggerData *tdata;
2523 	int			rc PG_USED_FOR_ASSERTS_ONLY;
2524 
2525 	/* Connect to SPI manager */
2526 	if (SPI_connect() != SPI_OK_CONNECT)
2527 		elog(ERROR, "could not connect to SPI manager");
2528 
2529 	/* Make transition tables visible to this SPI connection */
2530 	tdata = (TriggerData *) fcinfo->context;
2531 	rc = SPI_register_trigger_data(tdata);
2532 	Assert(rc >= 0);
2533 
2534 	/* Find or compile the function */
2535 	prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, true, false);
2536 	current_call_data->prodesc = prodesc;
2537 	increment_prodesc_refcount(prodesc);
2538 
2539 	/* Set a callback for error reporting */
2540 	pl_error_context.callback = plperl_exec_callback;
2541 	pl_error_context.previous = error_context_stack;
2542 	pl_error_context.arg = prodesc->proname;
2543 	error_context_stack = &pl_error_context;
2544 
2545 	activate_interpreter(prodesc->interp);
2546 
2547 	svTD = plperl_trigger_build_args(fcinfo);
2548 	perlret = plperl_call_perl_trigger_func(prodesc, fcinfo, svTD);
2549 	hvTD = (HV *) SvRV(svTD);
2550 
2551 	/************************************************************
2552 	* Disconnect from SPI manager and then create the return
2553 	* values datum (if the input function does a palloc for it
2554 	* this must not be allocated in the SPI memory context
2555 	* because SPI_finish would free it).
2556 	************************************************************/
2557 	if (SPI_finish() != SPI_OK_FINISH)
2558 		elog(ERROR, "SPI_finish() failed");
2559 
2560 	if (perlret == NULL || !SvOK(perlret))
2561 	{
2562 		/* undef result means go ahead with original tuple */
2563 		TriggerData *trigdata = ((TriggerData *) fcinfo->context);
2564 
2565 		if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
2566 			retval = (Datum) trigdata->tg_trigtuple;
2567 		else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
2568 			retval = (Datum) trigdata->tg_newtuple;
2569 		else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
2570 			retval = (Datum) trigdata->tg_trigtuple;
2571 		else if (TRIGGER_FIRED_BY_TRUNCATE(trigdata->tg_event))
2572 			retval = (Datum) trigdata->tg_trigtuple;
2573 		else
2574 			retval = (Datum) 0; /* can this happen? */
2575 	}
2576 	else
2577 	{
2578 		HeapTuple	trv;
2579 		char	   *tmp;
2580 
2581 		tmp = sv2cstr(perlret);
2582 
2583 		if (pg_strcasecmp(tmp, "SKIP") == 0)
2584 			trv = NULL;
2585 		else if (pg_strcasecmp(tmp, "MODIFY") == 0)
2586 		{
2587 			TriggerData *trigdata = (TriggerData *) fcinfo->context;
2588 
2589 			if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
2590 				trv = plperl_modify_tuple(hvTD, trigdata,
2591 										  trigdata->tg_trigtuple);
2592 			else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
2593 				trv = plperl_modify_tuple(hvTD, trigdata,
2594 										  trigdata->tg_newtuple);
2595 			else
2596 			{
2597 				ereport(WARNING,
2598 						(errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2599 						 errmsg("ignoring modified row in DELETE trigger")));
2600 				trv = NULL;
2601 			}
2602 		}
2603 		else
2604 		{
2605 			ereport(ERROR,
2606 					(errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2607 					 errmsg("result of PL/Perl trigger function must be undef, "
2608 							"\"SKIP\", or \"MODIFY\"")));
2609 			trv = NULL;
2610 		}
2611 		retval = PointerGetDatum(trv);
2612 		pfree(tmp);
2613 	}
2614 
2615 	/* Restore the previous error callback */
2616 	error_context_stack = pl_error_context.previous;
2617 
2618 	SvREFCNT_dec_current(svTD);
2619 	if (perlret)
2620 		SvREFCNT_dec_current(perlret);
2621 
2622 	return retval;
2623 }
2624 
2625 
2626 static void
plperl_event_trigger_handler(PG_FUNCTION_ARGS)2627 plperl_event_trigger_handler(PG_FUNCTION_ARGS)
2628 {
2629 	plperl_proc_desc *prodesc;
2630 	SV		   *svTD;
2631 	ErrorContextCallback pl_error_context;
2632 
2633 	/* Connect to SPI manager */
2634 	if (SPI_connect() != SPI_OK_CONNECT)
2635 		elog(ERROR, "could not connect to SPI manager");
2636 
2637 	/* Find or compile the function */
2638 	prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, false, true);
2639 	current_call_data->prodesc = prodesc;
2640 	increment_prodesc_refcount(prodesc);
2641 
2642 	/* Set a callback for error reporting */
2643 	pl_error_context.callback = plperl_exec_callback;
2644 	pl_error_context.previous = error_context_stack;
2645 	pl_error_context.arg = prodesc->proname;
2646 	error_context_stack = &pl_error_context;
2647 
2648 	activate_interpreter(prodesc->interp);
2649 
2650 	svTD = plperl_event_trigger_build_args(fcinfo);
2651 	plperl_call_perl_event_trigger_func(prodesc, fcinfo, svTD);
2652 
2653 	if (SPI_finish() != SPI_OK_FINISH)
2654 		elog(ERROR, "SPI_finish() failed");
2655 
2656 	/* Restore the previous error callback */
2657 	error_context_stack = pl_error_context.previous;
2658 
2659 	SvREFCNT_dec_current(svTD);
2660 }
2661 
2662 
2663 static bool
validate_plperl_function(plperl_proc_ptr * proc_ptr,HeapTuple procTup)2664 validate_plperl_function(plperl_proc_ptr *proc_ptr, HeapTuple procTup)
2665 {
2666 	if (proc_ptr && proc_ptr->proc_ptr)
2667 	{
2668 		plperl_proc_desc *prodesc = proc_ptr->proc_ptr;
2669 		bool		uptodate;
2670 
2671 		/************************************************************
2672 		 * If it's present, must check whether it's still up to date.
2673 		 * This is needed because CREATE OR REPLACE FUNCTION can modify the
2674 		 * function's pg_proc entry without changing its OID.
2675 		 ************************************************************/
2676 		uptodate = (prodesc->fn_xmin == HeapTupleHeaderGetRawXmin(procTup->t_data) &&
2677 					ItemPointerEquals(&prodesc->fn_tid, &procTup->t_self));
2678 
2679 		if (uptodate)
2680 			return true;
2681 
2682 		/* Otherwise, unlink the obsoleted entry from the hashtable ... */
2683 		proc_ptr->proc_ptr = NULL;
2684 		/* ... and release the corresponding refcount, probably deleting it */
2685 		decrement_prodesc_refcount(prodesc);
2686 	}
2687 
2688 	return false;
2689 }
2690 
2691 
2692 static void
free_plperl_function(plperl_proc_desc * prodesc)2693 free_plperl_function(plperl_proc_desc *prodesc)
2694 {
2695 	Assert(prodesc->fn_refcount == 0);
2696 	/* Release CODE reference, if we have one, from the appropriate interp */
2697 	if (prodesc->reference)
2698 	{
2699 		plperl_interp_desc *oldinterp = plperl_active_interp;
2700 
2701 		activate_interpreter(prodesc->interp);
2702 		SvREFCNT_dec_current(prodesc->reference);
2703 		activate_interpreter(oldinterp);
2704 	}
2705 	/* Release all PG-owned data for this proc */
2706 	MemoryContextDelete(prodesc->fn_cxt);
2707 }
2708 
2709 
2710 static plperl_proc_desc *
compile_plperl_function(Oid fn_oid,bool is_trigger,bool is_event_trigger)2711 compile_plperl_function(Oid fn_oid, bool is_trigger, bool is_event_trigger)
2712 {
2713 	HeapTuple	procTup;
2714 	Form_pg_proc procStruct;
2715 	plperl_proc_key proc_key;
2716 	plperl_proc_ptr *proc_ptr;
2717 	plperl_proc_desc *volatile prodesc = NULL;
2718 	volatile MemoryContext proc_cxt = NULL;
2719 	plperl_interp_desc *oldinterp = plperl_active_interp;
2720 	ErrorContextCallback plperl_error_context;
2721 
2722 	/* We'll need the pg_proc tuple in any case... */
2723 	procTup = SearchSysCache1(PROCOID, ObjectIdGetDatum(fn_oid));
2724 	if (!HeapTupleIsValid(procTup))
2725 		elog(ERROR, "cache lookup failed for function %u", fn_oid);
2726 	procStruct = (Form_pg_proc) GETSTRUCT(procTup);
2727 
2728 	/*
2729 	 * Try to find function in plperl_proc_hash.  The reason for this
2730 	 * overcomplicated-seeming lookup procedure is that we don't know whether
2731 	 * it's plperl or plperlu, and don't want to spend a lookup in pg_language
2732 	 * to find out.
2733 	 */
2734 	proc_key.proc_id = fn_oid;
2735 	proc_key.is_trigger = is_trigger;
2736 	proc_key.user_id = GetUserId();
2737 	proc_ptr = hash_search(plperl_proc_hash, &proc_key,
2738 						   HASH_FIND, NULL);
2739 	if (validate_plperl_function(proc_ptr, procTup))
2740 	{
2741 		/* Found valid plperl entry */
2742 		ReleaseSysCache(procTup);
2743 		return proc_ptr->proc_ptr;
2744 	}
2745 
2746 	/* If not found or obsolete, maybe it's plperlu */
2747 	proc_key.user_id = InvalidOid;
2748 	proc_ptr = hash_search(plperl_proc_hash, &proc_key,
2749 						   HASH_FIND, NULL);
2750 	if (validate_plperl_function(proc_ptr, procTup))
2751 	{
2752 		/* Found valid plperlu entry */
2753 		ReleaseSysCache(procTup);
2754 		return proc_ptr->proc_ptr;
2755 	}
2756 
2757 	/************************************************************
2758 	 * If we haven't found it in the hashtable, we analyze
2759 	 * the function's arguments and return type and store
2760 	 * the in-/out-functions in the prodesc block,
2761 	 * then we load the procedure into the Perl interpreter,
2762 	 * and last we create a new hashtable entry for it.
2763 	 ************************************************************/
2764 
2765 	/* Set a callback for reporting compilation errors */
2766 	plperl_error_context.callback = plperl_compile_callback;
2767 	plperl_error_context.previous = error_context_stack;
2768 	plperl_error_context.arg = NameStr(procStruct->proname);
2769 	error_context_stack = &plperl_error_context;
2770 
2771 	PG_TRY();
2772 	{
2773 		HeapTuple	langTup;
2774 		HeapTuple	typeTup;
2775 		Form_pg_language langStruct;
2776 		Form_pg_type typeStruct;
2777 		Datum		protrftypes_datum;
2778 		Datum		prosrcdatum;
2779 		bool		isnull;
2780 		char	   *proc_source;
2781 		MemoryContext oldcontext;
2782 
2783 		/************************************************************
2784 		 * Allocate a context that will hold all PG data for the procedure.
2785 		 ************************************************************/
2786 		proc_cxt = AllocSetContextCreate(TopMemoryContext,
2787 										 "PL/Perl function",
2788 										 ALLOCSET_SMALL_SIZES);
2789 
2790 		/************************************************************
2791 		 * Allocate and fill a new procedure description block.
2792 		 * struct prodesc and subsidiary data must all live in proc_cxt.
2793 		 ************************************************************/
2794 		oldcontext = MemoryContextSwitchTo(proc_cxt);
2795 		prodesc = (plperl_proc_desc *) palloc0(sizeof(plperl_proc_desc));
2796 		prodesc->proname = pstrdup(NameStr(procStruct->proname));
2797 		MemoryContextSetIdentifier(proc_cxt, prodesc->proname);
2798 		prodesc->fn_cxt = proc_cxt;
2799 		prodesc->fn_refcount = 0;
2800 		prodesc->fn_xmin = HeapTupleHeaderGetRawXmin(procTup->t_data);
2801 		prodesc->fn_tid = procTup->t_self;
2802 		prodesc->nargs = procStruct->pronargs;
2803 		prodesc->arg_out_func = (FmgrInfo *) palloc0(prodesc->nargs * sizeof(FmgrInfo));
2804 		prodesc->arg_is_rowtype = (bool *) palloc0(prodesc->nargs * sizeof(bool));
2805 		prodesc->arg_arraytype = (Oid *) palloc0(prodesc->nargs * sizeof(Oid));
2806 		MemoryContextSwitchTo(oldcontext);
2807 
2808 		/* Remember if function is STABLE/IMMUTABLE */
2809 		prodesc->fn_readonly =
2810 			(procStruct->provolatile != PROVOLATILE_VOLATILE);
2811 
2812 		/* Fetch protrftypes */
2813 		protrftypes_datum = SysCacheGetAttr(PROCOID, procTup,
2814 											Anum_pg_proc_protrftypes, &isnull);
2815 		MemoryContextSwitchTo(proc_cxt);
2816 		prodesc->trftypes = isnull ? NIL : oid_array_to_list(protrftypes_datum);
2817 		MemoryContextSwitchTo(oldcontext);
2818 
2819 		/************************************************************
2820 		 * Lookup the pg_language tuple by Oid
2821 		 ************************************************************/
2822 		langTup = SearchSysCache1(LANGOID,
2823 								  ObjectIdGetDatum(procStruct->prolang));
2824 		if (!HeapTupleIsValid(langTup))
2825 			elog(ERROR, "cache lookup failed for language %u",
2826 				 procStruct->prolang);
2827 		langStruct = (Form_pg_language) GETSTRUCT(langTup);
2828 		prodesc->lang_oid = HeapTupleGetOid(langTup);
2829 		prodesc->lanpltrusted = langStruct->lanpltrusted;
2830 		ReleaseSysCache(langTup);
2831 
2832 		/************************************************************
2833 		 * Get the required information for input conversion of the
2834 		 * return value.
2835 		 ************************************************************/
2836 		if (!is_trigger && !is_event_trigger)
2837 		{
2838 			Oid			rettype = procStruct->prorettype;
2839 
2840 			typeTup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(rettype));
2841 			if (!HeapTupleIsValid(typeTup))
2842 				elog(ERROR, "cache lookup failed for type %u", rettype);
2843 			typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
2844 
2845 			/* Disallow pseudotype result, except VOID or RECORD */
2846 			if (typeStruct->typtype == TYPTYPE_PSEUDO)
2847 			{
2848 				if (rettype == VOIDOID ||
2849 					rettype == RECORDOID)
2850 					 /* okay */ ;
2851 				else if (rettype == TRIGGEROID ||
2852 						 rettype == EVTTRIGGEROID)
2853 					ereport(ERROR,
2854 							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2855 							 errmsg("trigger functions can only be called "
2856 									"as triggers")));
2857 				else
2858 					ereport(ERROR,
2859 							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2860 							 errmsg("PL/Perl functions cannot return type %s",
2861 									format_type_be(rettype))));
2862 			}
2863 
2864 			prodesc->result_oid = rettype;
2865 			prodesc->fn_retisset = procStruct->proretset;
2866 			prodesc->fn_retistuple = type_is_rowtype(rettype);
2867 
2868 			prodesc->fn_retisarray =
2869 				(typeStruct->typlen == -1 && typeStruct->typelem);
2870 
2871 			fmgr_info_cxt(typeStruct->typinput,
2872 						  &(prodesc->result_in_func),
2873 						  proc_cxt);
2874 			prodesc->result_typioparam = getTypeIOParam(typeTup);
2875 
2876 			ReleaseSysCache(typeTup);
2877 		}
2878 
2879 		/************************************************************
2880 		 * Get the required information for output conversion
2881 		 * of all procedure arguments
2882 		 ************************************************************/
2883 		if (!is_trigger && !is_event_trigger)
2884 		{
2885 			int			i;
2886 
2887 			for (i = 0; i < prodesc->nargs; i++)
2888 			{
2889 				Oid			argtype = procStruct->proargtypes.values[i];
2890 
2891 				typeTup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(argtype));
2892 				if (!HeapTupleIsValid(typeTup))
2893 					elog(ERROR, "cache lookup failed for type %u", argtype);
2894 				typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
2895 
2896 				/* Disallow pseudotype argument, except RECORD */
2897 				if (typeStruct->typtype == TYPTYPE_PSEUDO &&
2898 					argtype != RECORDOID)
2899 					ereport(ERROR,
2900 							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2901 							 errmsg("PL/Perl functions cannot accept type %s",
2902 									format_type_be(argtype))));
2903 
2904 				if (type_is_rowtype(argtype))
2905 					prodesc->arg_is_rowtype[i] = true;
2906 				else
2907 				{
2908 					prodesc->arg_is_rowtype[i] = false;
2909 					fmgr_info_cxt(typeStruct->typoutput,
2910 								  &(prodesc->arg_out_func[i]),
2911 								  proc_cxt);
2912 				}
2913 
2914 				/* Identify array-type arguments */
2915 				if (typeStruct->typelem != 0 && typeStruct->typlen == -1)
2916 					prodesc->arg_arraytype[i] = argtype;
2917 				else
2918 					prodesc->arg_arraytype[i] = InvalidOid;
2919 
2920 				ReleaseSysCache(typeTup);
2921 			}
2922 		}
2923 
2924 		/************************************************************
2925 		 * create the text of the anonymous subroutine.
2926 		 * we do not use a named subroutine so that we can call directly
2927 		 * through the reference.
2928 		 ************************************************************/
2929 		prosrcdatum = SysCacheGetAttr(PROCOID, procTup,
2930 									  Anum_pg_proc_prosrc, &isnull);
2931 		if (isnull)
2932 			elog(ERROR, "null prosrc");
2933 		proc_source = TextDatumGetCString(prosrcdatum);
2934 
2935 		/************************************************************
2936 		 * Create the procedure in the appropriate interpreter
2937 		 ************************************************************/
2938 
2939 		select_perl_context(prodesc->lanpltrusted);
2940 
2941 		prodesc->interp = plperl_active_interp;
2942 
2943 		plperl_create_sub(prodesc, proc_source, fn_oid);
2944 
2945 		activate_interpreter(oldinterp);
2946 
2947 		pfree(proc_source);
2948 
2949 		if (!prodesc->reference)	/* can this happen? */
2950 			elog(ERROR, "could not create PL/Perl internal procedure");
2951 
2952 		/************************************************************
2953 		 * OK, link the procedure into the correct hashtable entry.
2954 		 * Note we assume that the hashtable entry either doesn't exist yet,
2955 		 * or we already cleared its proc_ptr during the validation attempts
2956 		 * above.  So no need to decrement an old refcount here.
2957 		 ************************************************************/
2958 		proc_key.user_id = prodesc->lanpltrusted ? GetUserId() : InvalidOid;
2959 
2960 		proc_ptr = hash_search(plperl_proc_hash, &proc_key,
2961 							   HASH_ENTER, NULL);
2962 		/* We assume these two steps can't throw an error: */
2963 		proc_ptr->proc_ptr = prodesc;
2964 		increment_prodesc_refcount(prodesc);
2965 	}
2966 	PG_CATCH();
2967 	{
2968 		/*
2969 		 * If we got as far as creating a reference, we should be able to use
2970 		 * free_plperl_function() to clean up.  If not, then at most we have
2971 		 * some PG memory resources in proc_cxt, which we can just delete.
2972 		 */
2973 		if (prodesc && prodesc->reference)
2974 			free_plperl_function(prodesc);
2975 		else if (proc_cxt)
2976 			MemoryContextDelete(proc_cxt);
2977 
2978 		/* Be sure to restore the previous interpreter, too, for luck */
2979 		activate_interpreter(oldinterp);
2980 
2981 		PG_RE_THROW();
2982 	}
2983 	PG_END_TRY();
2984 
2985 	/* restore previous error callback */
2986 	error_context_stack = plperl_error_context.previous;
2987 
2988 	ReleaseSysCache(procTup);
2989 
2990 	return prodesc;
2991 }
2992 
2993 /* Build a hash from a given composite/row datum */
2994 static SV  *
plperl_hash_from_datum(Datum attr)2995 plperl_hash_from_datum(Datum attr)
2996 {
2997 	HeapTupleHeader td;
2998 	Oid			tupType;
2999 	int32		tupTypmod;
3000 	TupleDesc	tupdesc;
3001 	HeapTupleData tmptup;
3002 	SV		   *sv;
3003 
3004 	td = DatumGetHeapTupleHeader(attr);
3005 
3006 	/* Extract rowtype info and find a tupdesc */
3007 	tupType = HeapTupleHeaderGetTypeId(td);
3008 	tupTypmod = HeapTupleHeaderGetTypMod(td);
3009 	tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3010 
3011 	/* Build a temporary HeapTuple control structure */
3012 	tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3013 	tmptup.t_data = td;
3014 
3015 	sv = plperl_hash_from_tuple(&tmptup, tupdesc);
3016 	ReleaseTupleDesc(tupdesc);
3017 
3018 	return sv;
3019 }
3020 
3021 /* Build a hash from all attributes of a given tuple. */
3022 static SV  *
plperl_hash_from_tuple(HeapTuple tuple,TupleDesc tupdesc)3023 plperl_hash_from_tuple(HeapTuple tuple, TupleDesc tupdesc)
3024 {
3025 	dTHX;
3026 	HV		   *hv;
3027 	int			i;
3028 
3029 	/* since this function recurses, it could be driven to stack overflow */
3030 	check_stack_depth();
3031 
3032 	hv = newHV();
3033 	hv_ksplit(hv, tupdesc->natts);	/* pre-grow the hash */
3034 
3035 	for (i = 0; i < tupdesc->natts; i++)
3036 	{
3037 		Datum		attr;
3038 		bool		isnull,
3039 					typisvarlena;
3040 		char	   *attname;
3041 		Oid			typoutput;
3042 		Form_pg_attribute att = TupleDescAttr(tupdesc, i);
3043 
3044 		if (att->attisdropped)
3045 			continue;
3046 
3047 		attname = NameStr(att->attname);
3048 		attr = heap_getattr(tuple, i + 1, tupdesc, &isnull);
3049 
3050 		if (isnull)
3051 		{
3052 			/*
3053 			 * Store (attname => undef) and move on.  Note we can't use
3054 			 * &PL_sv_undef here; see "AVs, HVs and undefined values" in
3055 			 * perlguts for an explanation.
3056 			 */
3057 			hv_store_string(hv, attname, newSV(0));
3058 			continue;
3059 		}
3060 
3061 		if (type_is_rowtype(att->atttypid))
3062 		{
3063 			SV		   *sv = plperl_hash_from_datum(attr);
3064 
3065 			hv_store_string(hv, attname, sv);
3066 		}
3067 		else
3068 		{
3069 			SV		   *sv;
3070 			Oid			funcid;
3071 
3072 			if (OidIsValid(get_base_element_type(att->atttypid)))
3073 				sv = plperl_ref_from_pg_array(attr, att->atttypid);
3074 			else if ((funcid = get_transform_fromsql(att->atttypid, current_call_data->prodesc->lang_oid, current_call_data->prodesc->trftypes)))
3075 				sv = (SV *) DatumGetPointer(OidFunctionCall1(funcid, attr));
3076 			else
3077 			{
3078 				char	   *outputstr;
3079 
3080 				/* XXX should have a way to cache these lookups */
3081 				getTypeOutputInfo(att->atttypid, &typoutput, &typisvarlena);
3082 
3083 				outputstr = OidOutputFunctionCall(typoutput, attr);
3084 				sv = cstr2sv(outputstr);
3085 				pfree(outputstr);
3086 			}
3087 
3088 			hv_store_string(hv, attname, sv);
3089 		}
3090 	}
3091 	return newRV_noinc((SV *) hv);
3092 }
3093 
3094 
3095 static void
check_spi_usage_allowed(void)3096 check_spi_usage_allowed(void)
3097 {
3098 	/* see comment in plperl_fini() */
3099 	if (plperl_ending)
3100 	{
3101 		/* simple croak as we don't want to involve PostgreSQL code */
3102 		croak("SPI functions can not be used in END blocks");
3103 	}
3104 }
3105 
3106 
3107 HV *
plperl_spi_exec(char * query,int limit)3108 plperl_spi_exec(char *query, int limit)
3109 {
3110 	HV		   *ret_hv;
3111 
3112 	/*
3113 	 * Execute the query inside a sub-transaction, so we can cope with errors
3114 	 * sanely
3115 	 */
3116 	MemoryContext oldcontext = CurrentMemoryContext;
3117 	ResourceOwner oldowner = CurrentResourceOwner;
3118 
3119 	check_spi_usage_allowed();
3120 
3121 	BeginInternalSubTransaction(NULL);
3122 	/* Want to run inside function's memory context */
3123 	MemoryContextSwitchTo(oldcontext);
3124 
3125 	PG_TRY();
3126 	{
3127 		int			spi_rv;
3128 
3129 		pg_verifymbstr(query, strlen(query), false);
3130 
3131 		spi_rv = SPI_execute(query, current_call_data->prodesc->fn_readonly,
3132 							 limit);
3133 		ret_hv = plperl_spi_execute_fetch_result(SPI_tuptable, SPI_processed,
3134 												 spi_rv);
3135 
3136 		/* Commit the inner transaction, return to outer xact context */
3137 		ReleaseCurrentSubTransaction();
3138 		MemoryContextSwitchTo(oldcontext);
3139 		CurrentResourceOwner = oldowner;
3140 	}
3141 	PG_CATCH();
3142 	{
3143 		ErrorData  *edata;
3144 
3145 		/* Save error info */
3146 		MemoryContextSwitchTo(oldcontext);
3147 		edata = CopyErrorData();
3148 		FlushErrorState();
3149 
3150 		/* Abort the inner transaction */
3151 		RollbackAndReleaseCurrentSubTransaction();
3152 		MemoryContextSwitchTo(oldcontext);
3153 		CurrentResourceOwner = oldowner;
3154 
3155 		/* Punt the error to Perl */
3156 		croak_cstr(edata->message);
3157 
3158 		/* Can't get here, but keep compiler quiet */
3159 		return NULL;
3160 	}
3161 	PG_END_TRY();
3162 
3163 	return ret_hv;
3164 }
3165 
3166 
3167 static HV  *
plperl_spi_execute_fetch_result(SPITupleTable * tuptable,uint64 processed,int status)3168 plperl_spi_execute_fetch_result(SPITupleTable *tuptable, uint64 processed,
3169 								int status)
3170 {
3171 	dTHX;
3172 	HV		   *result;
3173 
3174 	check_spi_usage_allowed();
3175 
3176 	result = newHV();
3177 
3178 	hv_store_string(result, "status",
3179 					cstr2sv(SPI_result_code_string(status)));
3180 	hv_store_string(result, "processed",
3181 					(processed > (uint64) UV_MAX) ?
3182 					newSVnv((NV) processed) :
3183 					newSVuv((UV) processed));
3184 
3185 	if (status > 0 && tuptable)
3186 	{
3187 		AV		   *rows;
3188 		SV		   *row;
3189 		uint64		i;
3190 
3191 		/* Prevent overflow in call to av_extend() */
3192 		if (processed > (uint64) AV_SIZE_MAX)
3193 			ereport(ERROR,
3194 					(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3195 					 errmsg("query result has too many rows to fit in a Perl array")));
3196 
3197 		rows = newAV();
3198 		av_extend(rows, processed);
3199 		for (i = 0; i < processed; i++)
3200 		{
3201 			row = plperl_hash_from_tuple(tuptable->vals[i], tuptable->tupdesc);
3202 			av_push(rows, row);
3203 		}
3204 		hv_store_string(result, "rows",
3205 						newRV_noinc((SV *) rows));
3206 	}
3207 
3208 	SPI_freetuptable(tuptable);
3209 
3210 	return result;
3211 }
3212 
3213 
3214 /*
3215  * plperl_return_next catches any error and converts it to a Perl error.
3216  * We assume (perhaps without adequate justification) that we need not abort
3217  * the current transaction if the Perl code traps the error.
3218  */
3219 void
plperl_return_next(SV * sv)3220 plperl_return_next(SV *sv)
3221 {
3222 	MemoryContext oldcontext = CurrentMemoryContext;
3223 
3224 	PG_TRY();
3225 	{
3226 		plperl_return_next_internal(sv);
3227 	}
3228 	PG_CATCH();
3229 	{
3230 		ErrorData  *edata;
3231 
3232 		/* Must reset elog.c's state */
3233 		MemoryContextSwitchTo(oldcontext);
3234 		edata = CopyErrorData();
3235 		FlushErrorState();
3236 
3237 		/* Punt the error to Perl */
3238 		croak_cstr(edata->message);
3239 	}
3240 	PG_END_TRY();
3241 }
3242 
3243 /*
3244  * plperl_return_next_internal reports any errors in Postgres fashion
3245  * (via ereport).
3246  */
3247 static void
plperl_return_next_internal(SV * sv)3248 plperl_return_next_internal(SV *sv)
3249 {
3250 	plperl_proc_desc *prodesc;
3251 	FunctionCallInfo fcinfo;
3252 	ReturnSetInfo *rsi;
3253 	MemoryContext old_cxt;
3254 
3255 	if (!sv)
3256 		return;
3257 
3258 	prodesc = current_call_data->prodesc;
3259 	fcinfo = current_call_data->fcinfo;
3260 	rsi = (ReturnSetInfo *) fcinfo->resultinfo;
3261 
3262 	if (!prodesc->fn_retisset)
3263 		ereport(ERROR,
3264 				(errcode(ERRCODE_SYNTAX_ERROR),
3265 				 errmsg("cannot use return_next in a non-SETOF function")));
3266 
3267 	if (!current_call_data->ret_tdesc)
3268 	{
3269 		TupleDesc	tupdesc;
3270 
3271 		Assert(!current_call_data->tuple_store);
3272 
3273 		/*
3274 		 * This is the first call to return_next in the current PL/Perl
3275 		 * function call, so identify the output tuple type and create a
3276 		 * tuplestore to hold the result rows.
3277 		 */
3278 		if (prodesc->fn_retistuple)
3279 		{
3280 			TypeFuncClass funcclass;
3281 			Oid			typid;
3282 
3283 			funcclass = get_call_result_type(fcinfo, &typid, &tupdesc);
3284 			if (funcclass != TYPEFUNC_COMPOSITE &&
3285 				funcclass != TYPEFUNC_COMPOSITE_DOMAIN)
3286 				ereport(ERROR,
3287 						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3288 						 errmsg("function returning record called in context "
3289 								"that cannot accept type record")));
3290 			/* if domain-over-composite, remember the domain's type OID */
3291 			if (funcclass == TYPEFUNC_COMPOSITE_DOMAIN)
3292 				current_call_data->cdomain_oid = typid;
3293 		}
3294 		else
3295 		{
3296 			tupdesc = rsi->expectedDesc;
3297 			/* Protect assumption below that we return exactly one column */
3298 			if (tupdesc == NULL || tupdesc->natts != 1)
3299 				elog(ERROR, "expected single-column result descriptor for non-composite SETOF result");
3300 		}
3301 
3302 		/*
3303 		 * Make sure the tuple_store and ret_tdesc are sufficiently
3304 		 * long-lived.
3305 		 */
3306 		old_cxt = MemoryContextSwitchTo(rsi->econtext->ecxt_per_query_memory);
3307 
3308 		current_call_data->ret_tdesc = CreateTupleDescCopy(tupdesc);
3309 		current_call_data->tuple_store =
3310 			tuplestore_begin_heap(rsi->allowedModes & SFRM_Materialize_Random,
3311 								  false, work_mem);
3312 
3313 		MemoryContextSwitchTo(old_cxt);
3314 	}
3315 
3316 	/*
3317 	 * Producing the tuple we want to return requires making plenty of
3318 	 * palloc() allocations that are not cleaned up. Since this function can
3319 	 * be called many times before the current memory context is reset, we
3320 	 * need to do those allocations in a temporary context.
3321 	 */
3322 	if (!current_call_data->tmp_cxt)
3323 	{
3324 		current_call_data->tmp_cxt =
3325 			AllocSetContextCreate(CurrentMemoryContext,
3326 								  "PL/Perl return_next temporary cxt",
3327 								  ALLOCSET_DEFAULT_SIZES);
3328 	}
3329 
3330 	old_cxt = MemoryContextSwitchTo(current_call_data->tmp_cxt);
3331 
3332 	if (prodesc->fn_retistuple)
3333 	{
3334 		HeapTuple	tuple;
3335 
3336 		if (!(SvOK(sv) && SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVHV))
3337 			ereport(ERROR,
3338 					(errcode(ERRCODE_DATATYPE_MISMATCH),
3339 					 errmsg("SETOF-composite-returning PL/Perl function "
3340 							"must call return_next with reference to hash")));
3341 
3342 		tuple = plperl_build_tuple_result((HV *) SvRV(sv),
3343 										  current_call_data->ret_tdesc);
3344 
3345 		if (OidIsValid(current_call_data->cdomain_oid))
3346 			domain_check(HeapTupleGetDatum(tuple), false,
3347 						 current_call_data->cdomain_oid,
3348 						 &current_call_data->cdomain_info,
3349 						 rsi->econtext->ecxt_per_query_memory);
3350 
3351 		tuplestore_puttuple(current_call_data->tuple_store, tuple);
3352 	}
3353 	else if (prodesc->result_oid)
3354 	{
3355 		Datum		ret[1];
3356 		bool		isNull[1];
3357 
3358 		ret[0] = plperl_sv_to_datum(sv,
3359 									prodesc->result_oid,
3360 									-1,
3361 									fcinfo,
3362 									&prodesc->result_in_func,
3363 									prodesc->result_typioparam,
3364 									&isNull[0]);
3365 
3366 		tuplestore_putvalues(current_call_data->tuple_store,
3367 							 current_call_data->ret_tdesc,
3368 							 ret, isNull);
3369 	}
3370 
3371 	MemoryContextSwitchTo(old_cxt);
3372 	MemoryContextReset(current_call_data->tmp_cxt);
3373 }
3374 
3375 
3376 SV *
plperl_spi_query(char * query)3377 plperl_spi_query(char *query)
3378 {
3379 	SV		   *cursor;
3380 
3381 	/*
3382 	 * Execute the query inside a sub-transaction, so we can cope with errors
3383 	 * sanely
3384 	 */
3385 	MemoryContext oldcontext = CurrentMemoryContext;
3386 	ResourceOwner oldowner = CurrentResourceOwner;
3387 
3388 	check_spi_usage_allowed();
3389 
3390 	BeginInternalSubTransaction(NULL);
3391 	/* Want to run inside function's memory context */
3392 	MemoryContextSwitchTo(oldcontext);
3393 
3394 	PG_TRY();
3395 	{
3396 		SPIPlanPtr	plan;
3397 		Portal		portal;
3398 
3399 		/* Make sure the query is validly encoded */
3400 		pg_verifymbstr(query, strlen(query), false);
3401 
3402 		/* Create a cursor for the query */
3403 		plan = SPI_prepare(query, 0, NULL);
3404 		if (plan == NULL)
3405 			elog(ERROR, "SPI_prepare() failed:%s",
3406 				 SPI_result_code_string(SPI_result));
3407 
3408 		portal = SPI_cursor_open(NULL, plan, NULL, NULL, false);
3409 		SPI_freeplan(plan);
3410 		if (portal == NULL)
3411 			elog(ERROR, "SPI_cursor_open() failed:%s",
3412 				 SPI_result_code_string(SPI_result));
3413 		cursor = cstr2sv(portal->name);
3414 
3415 		PinPortal(portal);
3416 
3417 		/* Commit the inner transaction, return to outer xact context */
3418 		ReleaseCurrentSubTransaction();
3419 		MemoryContextSwitchTo(oldcontext);
3420 		CurrentResourceOwner = oldowner;
3421 	}
3422 	PG_CATCH();
3423 	{
3424 		ErrorData  *edata;
3425 
3426 		/* Save error info */
3427 		MemoryContextSwitchTo(oldcontext);
3428 		edata = CopyErrorData();
3429 		FlushErrorState();
3430 
3431 		/* Abort the inner transaction */
3432 		RollbackAndReleaseCurrentSubTransaction();
3433 		MemoryContextSwitchTo(oldcontext);
3434 		CurrentResourceOwner = oldowner;
3435 
3436 		/* Punt the error to Perl */
3437 		croak_cstr(edata->message);
3438 
3439 		/* Can't get here, but keep compiler quiet */
3440 		return NULL;
3441 	}
3442 	PG_END_TRY();
3443 
3444 	return cursor;
3445 }
3446 
3447 
3448 SV *
plperl_spi_fetchrow(char * cursor)3449 plperl_spi_fetchrow(char *cursor)
3450 {
3451 	SV		   *row;
3452 
3453 	/*
3454 	 * Execute the FETCH inside a sub-transaction, so we can cope with errors
3455 	 * sanely
3456 	 */
3457 	MemoryContext oldcontext = CurrentMemoryContext;
3458 	ResourceOwner oldowner = CurrentResourceOwner;
3459 
3460 	check_spi_usage_allowed();
3461 
3462 	BeginInternalSubTransaction(NULL);
3463 	/* Want to run inside function's memory context */
3464 	MemoryContextSwitchTo(oldcontext);
3465 
3466 	PG_TRY();
3467 	{
3468 		dTHX;
3469 		Portal		p = SPI_cursor_find(cursor);
3470 
3471 		if (!p)
3472 		{
3473 			row = &PL_sv_undef;
3474 		}
3475 		else
3476 		{
3477 			SPI_cursor_fetch(p, true, 1);
3478 			if (SPI_processed == 0)
3479 			{
3480 				UnpinPortal(p);
3481 				SPI_cursor_close(p);
3482 				row = &PL_sv_undef;
3483 			}
3484 			else
3485 			{
3486 				row = plperl_hash_from_tuple(SPI_tuptable->vals[0],
3487 											 SPI_tuptable->tupdesc);
3488 			}
3489 			SPI_freetuptable(SPI_tuptable);
3490 		}
3491 
3492 		/* Commit the inner transaction, return to outer xact context */
3493 		ReleaseCurrentSubTransaction();
3494 		MemoryContextSwitchTo(oldcontext);
3495 		CurrentResourceOwner = oldowner;
3496 	}
3497 	PG_CATCH();
3498 	{
3499 		ErrorData  *edata;
3500 
3501 		/* Save error info */
3502 		MemoryContextSwitchTo(oldcontext);
3503 		edata = CopyErrorData();
3504 		FlushErrorState();
3505 
3506 		/* Abort the inner transaction */
3507 		RollbackAndReleaseCurrentSubTransaction();
3508 		MemoryContextSwitchTo(oldcontext);
3509 		CurrentResourceOwner = oldowner;
3510 
3511 		/* Punt the error to Perl */
3512 		croak_cstr(edata->message);
3513 
3514 		/* Can't get here, but keep compiler quiet */
3515 		return NULL;
3516 	}
3517 	PG_END_TRY();
3518 
3519 	return row;
3520 }
3521 
3522 void
plperl_spi_cursor_close(char * cursor)3523 plperl_spi_cursor_close(char *cursor)
3524 {
3525 	Portal		p;
3526 
3527 	check_spi_usage_allowed();
3528 
3529 	p = SPI_cursor_find(cursor);
3530 
3531 	if (p)
3532 	{
3533 		UnpinPortal(p);
3534 		SPI_cursor_close(p);
3535 	}
3536 }
3537 
3538 SV *
plperl_spi_prepare(char * query,int argc,SV ** argv)3539 plperl_spi_prepare(char *query, int argc, SV **argv)
3540 {
3541 	volatile SPIPlanPtr plan = NULL;
3542 	volatile MemoryContext plan_cxt = NULL;
3543 	plperl_query_desc *volatile qdesc = NULL;
3544 	plperl_query_entry *volatile hash_entry = NULL;
3545 	MemoryContext oldcontext = CurrentMemoryContext;
3546 	ResourceOwner oldowner = CurrentResourceOwner;
3547 	MemoryContext work_cxt;
3548 	bool		found;
3549 	int			i;
3550 
3551 	check_spi_usage_allowed();
3552 
3553 	BeginInternalSubTransaction(NULL);
3554 	MemoryContextSwitchTo(oldcontext);
3555 
3556 	PG_TRY();
3557 	{
3558 		CHECK_FOR_INTERRUPTS();
3559 
3560 		/************************************************************
3561 		 * Allocate the new querydesc structure
3562 		 *
3563 		 * The qdesc struct, as well as all its subsidiary data, lives in its
3564 		 * plan_cxt.  But note that the SPIPlan does not.
3565 		 ************************************************************/
3566 		plan_cxt = AllocSetContextCreate(TopMemoryContext,
3567 										 "PL/Perl spi_prepare query",
3568 										 ALLOCSET_SMALL_SIZES);
3569 		MemoryContextSwitchTo(plan_cxt);
3570 		qdesc = (plperl_query_desc *) palloc0(sizeof(plperl_query_desc));
3571 		snprintf(qdesc->qname, sizeof(qdesc->qname), "%p", qdesc);
3572 		qdesc->plan_cxt = plan_cxt;
3573 		qdesc->nargs = argc;
3574 		qdesc->argtypes = (Oid *) palloc(argc * sizeof(Oid));
3575 		qdesc->arginfuncs = (FmgrInfo *) palloc(argc * sizeof(FmgrInfo));
3576 		qdesc->argtypioparams = (Oid *) palloc(argc * sizeof(Oid));
3577 		MemoryContextSwitchTo(oldcontext);
3578 
3579 		/************************************************************
3580 		 * Do the following work in a short-lived context so that we don't
3581 		 * leak a lot of memory in the PL/Perl function's SPI Proc context.
3582 		 ************************************************************/
3583 		work_cxt = AllocSetContextCreate(CurrentMemoryContext,
3584 										 "PL/Perl spi_prepare workspace",
3585 										 ALLOCSET_DEFAULT_SIZES);
3586 		MemoryContextSwitchTo(work_cxt);
3587 
3588 		/************************************************************
3589 		 * Resolve argument type names and then look them up by oid
3590 		 * in the system cache, and remember the required information
3591 		 * for input conversion.
3592 		 ************************************************************/
3593 		for (i = 0; i < argc; i++)
3594 		{
3595 			Oid			typId,
3596 						typInput,
3597 						typIOParam;
3598 			int32		typmod;
3599 			char	   *typstr;
3600 
3601 			typstr = sv2cstr(argv[i]);
3602 			parseTypeString(typstr, &typId, &typmod, false);
3603 			pfree(typstr);
3604 
3605 			getTypeInputInfo(typId, &typInput, &typIOParam);
3606 
3607 			qdesc->argtypes[i] = typId;
3608 			fmgr_info_cxt(typInput, &(qdesc->arginfuncs[i]), plan_cxt);
3609 			qdesc->argtypioparams[i] = typIOParam;
3610 		}
3611 
3612 		/* Make sure the query is validly encoded */
3613 		pg_verifymbstr(query, strlen(query), false);
3614 
3615 		/************************************************************
3616 		 * Prepare the plan and check for errors
3617 		 ************************************************************/
3618 		plan = SPI_prepare(query, argc, qdesc->argtypes);
3619 
3620 		if (plan == NULL)
3621 			elog(ERROR, "SPI_prepare() failed:%s",
3622 				 SPI_result_code_string(SPI_result));
3623 
3624 		/************************************************************
3625 		 * Save the plan into permanent memory (right now it's in the
3626 		 * SPI procCxt, which will go away at function end).
3627 		 ************************************************************/
3628 		if (SPI_keepplan(plan))
3629 			elog(ERROR, "SPI_keepplan() failed");
3630 		qdesc->plan = plan;
3631 
3632 		/************************************************************
3633 		 * Insert a hashtable entry for the plan.
3634 		 ************************************************************/
3635 		hash_entry = hash_search(plperl_active_interp->query_hash,
3636 								 qdesc->qname,
3637 								 HASH_ENTER, &found);
3638 		hash_entry->query_data = qdesc;
3639 
3640 		/* Get rid of workspace */
3641 		MemoryContextDelete(work_cxt);
3642 
3643 		/* Commit the inner transaction, return to outer xact context */
3644 		ReleaseCurrentSubTransaction();
3645 		MemoryContextSwitchTo(oldcontext);
3646 		CurrentResourceOwner = oldowner;
3647 	}
3648 	PG_CATCH();
3649 	{
3650 		ErrorData  *edata;
3651 
3652 		/* Save error info */
3653 		MemoryContextSwitchTo(oldcontext);
3654 		edata = CopyErrorData();
3655 		FlushErrorState();
3656 
3657 		/* Drop anything we managed to allocate */
3658 		if (hash_entry)
3659 			hash_search(plperl_active_interp->query_hash,
3660 						qdesc->qname,
3661 						HASH_REMOVE, NULL);
3662 		if (plan_cxt)
3663 			MemoryContextDelete(plan_cxt);
3664 		if (plan)
3665 			SPI_freeplan(plan);
3666 
3667 		/* Abort the inner transaction */
3668 		RollbackAndReleaseCurrentSubTransaction();
3669 		MemoryContextSwitchTo(oldcontext);
3670 		CurrentResourceOwner = oldowner;
3671 
3672 		/* Punt the error to Perl */
3673 		croak_cstr(edata->message);
3674 
3675 		/* Can't get here, but keep compiler quiet */
3676 		return NULL;
3677 	}
3678 	PG_END_TRY();
3679 
3680 	/************************************************************
3681 	 * Return the query's hash key to the caller.
3682 	 ************************************************************/
3683 	return cstr2sv(qdesc->qname);
3684 }
3685 
3686 HV *
plperl_spi_exec_prepared(char * query,HV * attr,int argc,SV ** argv)3687 plperl_spi_exec_prepared(char *query, HV *attr, int argc, SV **argv)
3688 {
3689 	HV		   *ret_hv;
3690 	SV		  **sv;
3691 	int			i,
3692 				limit,
3693 				spi_rv;
3694 	char	   *nulls;
3695 	Datum	   *argvalues;
3696 	plperl_query_desc *qdesc;
3697 	plperl_query_entry *hash_entry;
3698 
3699 	/*
3700 	 * Execute the query inside a sub-transaction, so we can cope with errors
3701 	 * sanely
3702 	 */
3703 	MemoryContext oldcontext = CurrentMemoryContext;
3704 	ResourceOwner oldowner = CurrentResourceOwner;
3705 
3706 	check_spi_usage_allowed();
3707 
3708 	BeginInternalSubTransaction(NULL);
3709 	/* Want to run inside function's memory context */
3710 	MemoryContextSwitchTo(oldcontext);
3711 
3712 	PG_TRY();
3713 	{
3714 		dTHX;
3715 
3716 		/************************************************************
3717 		 * Fetch the saved plan descriptor, see if it's o.k.
3718 		 ************************************************************/
3719 		hash_entry = hash_search(plperl_active_interp->query_hash, query,
3720 								 HASH_FIND, NULL);
3721 		if (hash_entry == NULL)
3722 			elog(ERROR, "spi_exec_prepared: Invalid prepared query passed");
3723 
3724 		qdesc = hash_entry->query_data;
3725 		if (qdesc == NULL)
3726 			elog(ERROR, "spi_exec_prepared: plperl query_hash value vanished");
3727 
3728 		if (qdesc->nargs != argc)
3729 			elog(ERROR, "spi_exec_prepared: expected %d argument(s), %d passed",
3730 				 qdesc->nargs, argc);
3731 
3732 		/************************************************************
3733 		 * Parse eventual attributes
3734 		 ************************************************************/
3735 		limit = 0;
3736 		if (attr != NULL)
3737 		{
3738 			sv = hv_fetch_string(attr, "limit");
3739 			if (sv && *sv && SvIOK(*sv))
3740 				limit = SvIV(*sv);
3741 		}
3742 		/************************************************************
3743 		 * Set up arguments
3744 		 ************************************************************/
3745 		if (argc > 0)
3746 		{
3747 			nulls = (char *) palloc(argc);
3748 			argvalues = (Datum *) palloc(argc * sizeof(Datum));
3749 		}
3750 		else
3751 		{
3752 			nulls = NULL;
3753 			argvalues = NULL;
3754 		}
3755 
3756 		for (i = 0; i < argc; i++)
3757 		{
3758 			bool		isnull;
3759 
3760 			argvalues[i] = plperl_sv_to_datum(argv[i],
3761 											  qdesc->argtypes[i],
3762 											  -1,
3763 											  NULL,
3764 											  &qdesc->arginfuncs[i],
3765 											  qdesc->argtypioparams[i],
3766 											  &isnull);
3767 			nulls[i] = isnull ? 'n' : ' ';
3768 		}
3769 
3770 		/************************************************************
3771 		 * go
3772 		 ************************************************************/
3773 		spi_rv = SPI_execute_plan(qdesc->plan, argvalues, nulls,
3774 								  current_call_data->prodesc->fn_readonly, limit);
3775 		ret_hv = plperl_spi_execute_fetch_result(SPI_tuptable, SPI_processed,
3776 												 spi_rv);
3777 		if (argc > 0)
3778 		{
3779 			pfree(argvalues);
3780 			pfree(nulls);
3781 		}
3782 
3783 		/* Commit the inner transaction, return to outer xact context */
3784 		ReleaseCurrentSubTransaction();
3785 		MemoryContextSwitchTo(oldcontext);
3786 		CurrentResourceOwner = oldowner;
3787 	}
3788 	PG_CATCH();
3789 	{
3790 		ErrorData  *edata;
3791 
3792 		/* Save error info */
3793 		MemoryContextSwitchTo(oldcontext);
3794 		edata = CopyErrorData();
3795 		FlushErrorState();
3796 
3797 		/* Abort the inner transaction */
3798 		RollbackAndReleaseCurrentSubTransaction();
3799 		MemoryContextSwitchTo(oldcontext);
3800 		CurrentResourceOwner = oldowner;
3801 
3802 		/* Punt the error to Perl */
3803 		croak_cstr(edata->message);
3804 
3805 		/* Can't get here, but keep compiler quiet */
3806 		return NULL;
3807 	}
3808 	PG_END_TRY();
3809 
3810 	return ret_hv;
3811 }
3812 
3813 SV *
plperl_spi_query_prepared(char * query,int argc,SV ** argv)3814 plperl_spi_query_prepared(char *query, int argc, SV **argv)
3815 {
3816 	int			i;
3817 	char	   *nulls;
3818 	Datum	   *argvalues;
3819 	plperl_query_desc *qdesc;
3820 	plperl_query_entry *hash_entry;
3821 	SV		   *cursor;
3822 	Portal		portal = NULL;
3823 
3824 	/*
3825 	 * Execute the query inside a sub-transaction, so we can cope with errors
3826 	 * sanely
3827 	 */
3828 	MemoryContext oldcontext = CurrentMemoryContext;
3829 	ResourceOwner oldowner = CurrentResourceOwner;
3830 
3831 	check_spi_usage_allowed();
3832 
3833 	BeginInternalSubTransaction(NULL);
3834 	/* Want to run inside function's memory context */
3835 	MemoryContextSwitchTo(oldcontext);
3836 
3837 	PG_TRY();
3838 	{
3839 		/************************************************************
3840 		 * Fetch the saved plan descriptor, see if it's o.k.
3841 		 ************************************************************/
3842 		hash_entry = hash_search(plperl_active_interp->query_hash, query,
3843 								 HASH_FIND, NULL);
3844 		if (hash_entry == NULL)
3845 			elog(ERROR, "spi_query_prepared: Invalid prepared query passed");
3846 
3847 		qdesc = hash_entry->query_data;
3848 		if (qdesc == NULL)
3849 			elog(ERROR, "spi_query_prepared: plperl query_hash value vanished");
3850 
3851 		if (qdesc->nargs != argc)
3852 			elog(ERROR, "spi_query_prepared: expected %d argument(s), %d passed",
3853 				 qdesc->nargs, argc);
3854 
3855 		/************************************************************
3856 		 * Set up arguments
3857 		 ************************************************************/
3858 		if (argc > 0)
3859 		{
3860 			nulls = (char *) palloc(argc);
3861 			argvalues = (Datum *) palloc(argc * sizeof(Datum));
3862 		}
3863 		else
3864 		{
3865 			nulls = NULL;
3866 			argvalues = NULL;
3867 		}
3868 
3869 		for (i = 0; i < argc; i++)
3870 		{
3871 			bool		isnull;
3872 
3873 			argvalues[i] = plperl_sv_to_datum(argv[i],
3874 											  qdesc->argtypes[i],
3875 											  -1,
3876 											  NULL,
3877 											  &qdesc->arginfuncs[i],
3878 											  qdesc->argtypioparams[i],
3879 											  &isnull);
3880 			nulls[i] = isnull ? 'n' : ' ';
3881 		}
3882 
3883 		/************************************************************
3884 		 * go
3885 		 ************************************************************/
3886 		portal = SPI_cursor_open(NULL, qdesc->plan, argvalues, nulls,
3887 								 current_call_data->prodesc->fn_readonly);
3888 		if (argc > 0)
3889 		{
3890 			pfree(argvalues);
3891 			pfree(nulls);
3892 		}
3893 		if (portal == NULL)
3894 			elog(ERROR, "SPI_cursor_open() failed:%s",
3895 				 SPI_result_code_string(SPI_result));
3896 
3897 		cursor = cstr2sv(portal->name);
3898 
3899 		PinPortal(portal);
3900 
3901 		/* Commit the inner transaction, return to outer xact context */
3902 		ReleaseCurrentSubTransaction();
3903 		MemoryContextSwitchTo(oldcontext);
3904 		CurrentResourceOwner = oldowner;
3905 	}
3906 	PG_CATCH();
3907 	{
3908 		ErrorData  *edata;
3909 
3910 		/* Save error info */
3911 		MemoryContextSwitchTo(oldcontext);
3912 		edata = CopyErrorData();
3913 		FlushErrorState();
3914 
3915 		/* Abort the inner transaction */
3916 		RollbackAndReleaseCurrentSubTransaction();
3917 		MemoryContextSwitchTo(oldcontext);
3918 		CurrentResourceOwner = oldowner;
3919 
3920 		/* Punt the error to Perl */
3921 		croak_cstr(edata->message);
3922 
3923 		/* Can't get here, but keep compiler quiet */
3924 		return NULL;
3925 	}
3926 	PG_END_TRY();
3927 
3928 	return cursor;
3929 }
3930 
3931 void
plperl_spi_freeplan(char * query)3932 plperl_spi_freeplan(char *query)
3933 {
3934 	SPIPlanPtr	plan;
3935 	plperl_query_desc *qdesc;
3936 	plperl_query_entry *hash_entry;
3937 
3938 	check_spi_usage_allowed();
3939 
3940 	hash_entry = hash_search(plperl_active_interp->query_hash, query,
3941 							 HASH_FIND, NULL);
3942 	if (hash_entry == NULL)
3943 		elog(ERROR, "spi_freeplan: Invalid prepared query passed");
3944 
3945 	qdesc = hash_entry->query_data;
3946 	if (qdesc == NULL)
3947 		elog(ERROR, "spi_freeplan: plperl query_hash value vanished");
3948 	plan = qdesc->plan;
3949 
3950 	/*
3951 	 * free all memory before SPI_freeplan, so if it dies, nothing will be
3952 	 * left over
3953 	 */
3954 	hash_search(plperl_active_interp->query_hash, query,
3955 				HASH_REMOVE, NULL);
3956 
3957 	MemoryContextDelete(qdesc->plan_cxt);
3958 
3959 	SPI_freeplan(plan);
3960 }
3961 
3962 void
plperl_spi_commit(void)3963 plperl_spi_commit(void)
3964 {
3965 	MemoryContext oldcontext = CurrentMemoryContext;
3966 
3967 	PG_TRY();
3968 	{
3969 		SPI_commit();
3970 		SPI_start_transaction();
3971 	}
3972 	PG_CATCH();
3973 	{
3974 		ErrorData  *edata;
3975 
3976 		/* Save error info */
3977 		MemoryContextSwitchTo(oldcontext);
3978 		edata = CopyErrorData();
3979 		FlushErrorState();
3980 
3981 		/* Punt the error to Perl */
3982 		croak_cstr(edata->message);
3983 	}
3984 	PG_END_TRY();
3985 }
3986 
3987 void
plperl_spi_rollback(void)3988 plperl_spi_rollback(void)
3989 {
3990 	MemoryContext oldcontext = CurrentMemoryContext;
3991 
3992 	PG_TRY();
3993 	{
3994 		SPI_rollback();
3995 		SPI_start_transaction();
3996 	}
3997 	PG_CATCH();
3998 	{
3999 		ErrorData  *edata;
4000 
4001 		/* Save error info */
4002 		MemoryContextSwitchTo(oldcontext);
4003 		edata = CopyErrorData();
4004 		FlushErrorState();
4005 
4006 		/* Punt the error to Perl */
4007 		croak_cstr(edata->message);
4008 	}
4009 	PG_END_TRY();
4010 }
4011 
4012 /*
4013  * Implementation of plperl's elog() function
4014  *
4015  * If the error level is less than ERROR, we'll just emit the message and
4016  * return.  When it is ERROR, elog() will longjmp, which we catch and
4017  * turn into a Perl croak().  Note we are assuming that elog() can't have
4018  * any internal failures that are so bad as to require a transaction abort.
4019  *
4020  * The main reason this is out-of-line is to avoid conflicts between XSUB.h
4021  * and the PG_TRY macros.
4022  */
4023 void
plperl_util_elog(int level,SV * msg)4024 plperl_util_elog(int level, SV *msg)
4025 {
4026 	MemoryContext oldcontext = CurrentMemoryContext;
4027 	char	   *volatile cmsg = NULL;
4028 
4029 	PG_TRY();
4030 	{
4031 		cmsg = sv2cstr(msg);
4032 		elog(level, "%s", cmsg);
4033 		pfree(cmsg);
4034 	}
4035 	PG_CATCH();
4036 	{
4037 		ErrorData  *edata;
4038 
4039 		/* Must reset elog.c's state */
4040 		MemoryContextSwitchTo(oldcontext);
4041 		edata = CopyErrorData();
4042 		FlushErrorState();
4043 
4044 		if (cmsg)
4045 			pfree(cmsg);
4046 
4047 		/* Punt the error to Perl */
4048 		croak_cstr(edata->message);
4049 	}
4050 	PG_END_TRY();
4051 }
4052 
4053 /*
4054  * Store an SV into a hash table under a key that is a string assumed to be
4055  * in the current database's encoding.
4056  */
4057 static SV **
hv_store_string(HV * hv,const char * key,SV * val)4058 hv_store_string(HV *hv, const char *key, SV *val)
4059 {
4060 	dTHX;
4061 	int32		hlen;
4062 	char	   *hkey;
4063 	SV		  **ret;
4064 
4065 	hkey = pg_server_to_any(key, strlen(key), PG_UTF8);
4066 
4067 	/*
4068 	 * hv_store() recognizes a negative klen parameter as meaning a UTF-8
4069 	 * encoded key.
4070 	 */
4071 	hlen = -(int) strlen(hkey);
4072 	ret = hv_store(hv, hkey, hlen, val, 0);
4073 
4074 	if (hkey != key)
4075 		pfree(hkey);
4076 
4077 	return ret;
4078 }
4079 
4080 /*
4081  * Fetch an SV from a hash table under a key that is a string assumed to be
4082  * in the current database's encoding.
4083  */
4084 static SV **
hv_fetch_string(HV * hv,const char * key)4085 hv_fetch_string(HV *hv, const char *key)
4086 {
4087 	dTHX;
4088 	int32		hlen;
4089 	char	   *hkey;
4090 	SV		  **ret;
4091 
4092 	hkey = pg_server_to_any(key, strlen(key), PG_UTF8);
4093 
4094 	/* See notes in hv_store_string */
4095 	hlen = -(int) strlen(hkey);
4096 	ret = hv_fetch(hv, hkey, hlen, 0);
4097 
4098 	if (hkey != key)
4099 		pfree(hkey);
4100 
4101 	return ret;
4102 }
4103 
4104 /*
4105  * Provide function name for PL/Perl execution errors
4106  */
4107 static void
plperl_exec_callback(void * arg)4108 plperl_exec_callback(void *arg)
4109 {
4110 	char	   *procname = (char *) arg;
4111 
4112 	if (procname)
4113 		errcontext("PL/Perl function \"%s\"", procname);
4114 }
4115 
4116 /*
4117  * Provide function name for PL/Perl compilation errors
4118  */
4119 static void
plperl_compile_callback(void * arg)4120 plperl_compile_callback(void *arg)
4121 {
4122 	char	   *procname = (char *) arg;
4123 
4124 	if (procname)
4125 		errcontext("compilation of PL/Perl function \"%s\"", procname);
4126 }
4127 
4128 /*
4129  * Provide error context for the inline handler
4130  */
4131 static void
plperl_inline_callback(void * arg)4132 plperl_inline_callback(void *arg)
4133 {
4134 	errcontext("PL/Perl anonymous code block");
4135 }
4136 
4137 
4138 /*
4139  * Perl's own setlocale(), copied from POSIX.xs
4140  * (needed because of the calls to new_*())
4141  */
4142 #ifdef WIN32
4143 static char *
setlocale_perl(int category,char * locale)4144 setlocale_perl(int category, char *locale)
4145 {
4146 	dTHX;
4147 	char	   *RETVAL = setlocale(category, locale);
4148 
4149 	if (RETVAL)
4150 	{
4151 #ifdef USE_LOCALE_CTYPE
4152 		if (category == LC_CTYPE
4153 #ifdef LC_ALL
4154 			|| category == LC_ALL
4155 #endif
4156 			)
4157 		{
4158 			char	   *newctype;
4159 
4160 #ifdef LC_ALL
4161 			if (category == LC_ALL)
4162 				newctype = setlocale(LC_CTYPE, NULL);
4163 			else
4164 #endif
4165 				newctype = RETVAL;
4166 			new_ctype(newctype);
4167 		}
4168 #endif							/* USE_LOCALE_CTYPE */
4169 #ifdef USE_LOCALE_COLLATE
4170 		if (category == LC_COLLATE
4171 #ifdef LC_ALL
4172 			|| category == LC_ALL
4173 #endif
4174 			)
4175 		{
4176 			char	   *newcoll;
4177 
4178 #ifdef LC_ALL
4179 			if (category == LC_ALL)
4180 				newcoll = setlocale(LC_COLLATE, NULL);
4181 			else
4182 #endif
4183 				newcoll = RETVAL;
4184 			new_collate(newcoll);
4185 		}
4186 #endif							/* USE_LOCALE_COLLATE */
4187 
4188 #ifdef USE_LOCALE_NUMERIC
4189 		if (category == LC_NUMERIC
4190 #ifdef LC_ALL
4191 			|| category == LC_ALL
4192 #endif
4193 			)
4194 		{
4195 			char	   *newnum;
4196 
4197 #ifdef LC_ALL
4198 			if (category == LC_ALL)
4199 				newnum = setlocale(LC_NUMERIC, NULL);
4200 			else
4201 #endif
4202 				newnum = RETVAL;
4203 			new_numeric(newnum);
4204 		}
4205 #endif							/* USE_LOCALE_NUMERIC */
4206 	}
4207 
4208 	return RETVAL;
4209 }
4210 
4211 #endif							/* WIN32 */
4212