Debian Codegraph @

src/pl/plperl/plperl.c

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