LCOV - code coverage report
Current view: top level - src/pl/plperl - plperl.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 89.1 % 1437 1281
Test Date: 2026-08-29 05:15:52 Functions: 100.0 % 73 73
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 59.2 % 975 577

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

Generated by: LCOV version 2.0-1