]> granicus.if.org Git - postgresql/blob - src/backend/utils/fmgr/fmgr.c
Update copyright via script for 2017
[postgresql] / src / backend / utils / fmgr / fmgr.c
1 /*-------------------------------------------------------------------------
2  *
3  * fmgr.c
4  *        The Postgres function manager.
5  *
6  * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        src/backend/utils/fmgr/fmgr.c
12  *
13  *-------------------------------------------------------------------------
14  */
15
16 #include "postgres.h"
17
18 #include "access/tuptoaster.h"
19 #include "catalog/pg_language.h"
20 #include "catalog/pg_proc.h"
21 #include "executor/functions.h"
22 #include "lib/stringinfo.h"
23 #include "miscadmin.h"
24 #include "nodes/nodeFuncs.h"
25 #include "pgstat.h"
26 #include "utils/acl.h"
27 #include "utils/builtins.h"
28 #include "utils/fmgrtab.h"
29 #include "utils/guc.h"
30 #include "utils/lsyscache.h"
31 #include "utils/syscache.h"
32
33 /*
34  * Hooks for function calls
35  */
36 PGDLLIMPORT needs_fmgr_hook_type needs_fmgr_hook = NULL;
37 PGDLLIMPORT fmgr_hook_type fmgr_hook = NULL;
38
39 /*
40  * Declaration for old-style function pointer type.  This is now used only
41  * in fmgr_oldstyle() and is no longer exported.
42  *
43  * The m68k SVR4 ABI defines that pointers are returned in %a0 instead of
44  * %d0. So if a function pointer is declared to return a pointer, the
45  * compiler may look only into %a0, but if the called function was declared
46  * to return an integer type, it puts its value only into %d0. So the
47  * caller doesn't pick up the correct return value. The solution is to
48  * declare the function pointer to return int, so the compiler picks up the
49  * return value from %d0. (Functions returning pointers put their value
50  * *additionally* into %d0 for compatibility.) The price is that there are
51  * some warnings about int->pointer conversions ... which we can suppress
52  * with suitably ugly casts in fmgr_oldstyle().
53  */
54 #if (defined(__mc68000__) || (defined(__m68k__))) && defined(__ELF__)
55 typedef int32 (*func_ptr) ();
56 #else
57 typedef char *(*func_ptr) ();
58 #endif
59
60 /*
61  * For an oldstyle function, fn_extra points to a record like this:
62  */
63 typedef struct
64 {
65         func_ptr        func;                   /* Address of the oldstyle function */
66         bool            arg_toastable[FUNC_MAX_ARGS];   /* is n'th arg of a toastable
67                                                                                                  * datatype? */
68 } Oldstyle_fnextra;
69
70 /*
71  * Hashtable for fast lookup of external C functions
72  */
73 typedef struct
74 {
75         /* fn_oid is the hash key and so must be first! */
76         Oid                     fn_oid;                 /* OID of an external C function */
77         TransactionId fn_xmin;          /* for checking up-to-dateness */
78         ItemPointerData fn_tid;
79         PGFunction      user_fn;                /* the function's address */
80         const Pg_finfo_record *inforec;         /* address of its info record */
81 } CFuncHashTabEntry;
82
83 static HTAB *CFuncHash = NULL;
84
85
86 static void fmgr_info_cxt_security(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt,
87                                            bool ignore_security);
88 static void fmgr_info_C_lang(Oid functionId, FmgrInfo *finfo, HeapTuple procedureTuple);
89 static void fmgr_info_other_lang(Oid functionId, FmgrInfo *finfo, HeapTuple procedureTuple);
90 static CFuncHashTabEntry *lookup_C_func(HeapTuple procedureTuple);
91 static void record_C_func(HeapTuple procedureTuple,
92                           PGFunction user_fn, const Pg_finfo_record *inforec);
93 static Datum fmgr_oldstyle(PG_FUNCTION_ARGS);
94 static Datum fmgr_security_definer(PG_FUNCTION_ARGS);
95
96
97 /*
98  * Lookup routines for builtin-function table.  We can search by either Oid
99  * or name, but search by Oid is much faster.
100  */
101
102 static const FmgrBuiltin *
103 fmgr_isbuiltin(Oid id)
104 {
105         int                     low = 0;
106         int                     high = fmgr_nbuiltins - 1;
107
108         /*
109          * Loop invariant: low is the first index that could contain target entry,
110          * and high is the last index that could contain it.
111          */
112         while (low <= high)
113         {
114                 int                     i = (high + low) / 2;
115                 const FmgrBuiltin *ptr = &fmgr_builtins[i];
116
117                 if (id == ptr->foid)
118                         return ptr;
119                 else if (id > ptr->foid)
120                         low = i + 1;
121                 else
122                         high = i - 1;
123         }
124         return NULL;
125 }
126
127 /*
128  * Lookup a builtin by name.  Note there can be more than one entry in
129  * the array with the same name, but they should all point to the same
130  * routine.
131  */
132 static const FmgrBuiltin *
133 fmgr_lookupByName(const char *name)
134 {
135         int                     i;
136
137         for (i = 0; i < fmgr_nbuiltins; i++)
138         {
139                 if (strcmp(name, fmgr_builtins[i].funcName) == 0)
140                         return fmgr_builtins + i;
141         }
142         return NULL;
143 }
144
145 /*
146  * This routine fills a FmgrInfo struct, given the OID
147  * of the function to be called.
148  *
149  * The caller's CurrentMemoryContext is used as the fn_mcxt of the info
150  * struct; this means that any subsidiary data attached to the info struct
151  * (either by fmgr_info itself, or later on by a function call handler)
152  * will be allocated in that context.  The caller must ensure that this
153  * context is at least as long-lived as the info struct itself.  This is
154  * not a problem in typical cases where the info struct is on the stack or
155  * in freshly-palloc'd space.  However, if one intends to store an info
156  * struct in a long-lived table, it's better to use fmgr_info_cxt.
157  */
158 void
159 fmgr_info(Oid functionId, FmgrInfo *finfo)
160 {
161         fmgr_info_cxt_security(functionId, finfo, CurrentMemoryContext, false);
162 }
163
164 /*
165  * Fill a FmgrInfo struct, specifying a memory context in which its
166  * subsidiary data should go.
167  */
168 void
169 fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt)
170 {
171         fmgr_info_cxt_security(functionId, finfo, mcxt, false);
172 }
173
174 /*
175  * This one does the actual work.  ignore_security is ordinarily false
176  * but is set to true when we need to avoid recursion.
177  */
178 static void
179 fmgr_info_cxt_security(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt,
180                                            bool ignore_security)
181 {
182         const FmgrBuiltin *fbp;
183         HeapTuple       procedureTuple;
184         Form_pg_proc procedureStruct;
185         Datum           prosrcdatum;
186         bool            isnull;
187         char       *prosrc;
188
189         /*
190          * fn_oid *must* be filled in last.  Some code assumes that if fn_oid is
191          * valid, the whole struct is valid.  Some FmgrInfo struct's do survive
192          * elogs.
193          */
194         finfo->fn_oid = InvalidOid;
195         finfo->fn_extra = NULL;
196         finfo->fn_mcxt = mcxt;
197         finfo->fn_expr = NULL;          /* caller may set this later */
198
199         if ((fbp = fmgr_isbuiltin(functionId)) != NULL)
200         {
201                 /*
202                  * Fast path for builtin functions: don't bother consulting pg_proc
203                  */
204                 finfo->fn_nargs = fbp->nargs;
205                 finfo->fn_strict = fbp->strict;
206                 finfo->fn_retset = fbp->retset;
207                 finfo->fn_stats = TRACK_FUNC_ALL;               /* ie, never track */
208                 finfo->fn_addr = fbp->func;
209                 finfo->fn_oid = functionId;
210                 return;
211         }
212
213         /* Otherwise we need the pg_proc entry */
214         procedureTuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(functionId));
215         if (!HeapTupleIsValid(procedureTuple))
216                 elog(ERROR, "cache lookup failed for function %u", functionId);
217         procedureStruct = (Form_pg_proc) GETSTRUCT(procedureTuple);
218
219         finfo->fn_nargs = procedureStruct->pronargs;
220         finfo->fn_strict = procedureStruct->proisstrict;
221         finfo->fn_retset = procedureStruct->proretset;
222
223         /*
224          * If it has prosecdef set, non-null proconfig, or if a plugin wants to
225          * hook function entry/exit, use fmgr_security_definer call handler ---
226          * unless we are being called again by fmgr_security_definer or
227          * fmgr_info_other_lang.
228          *
229          * When using fmgr_security_definer, function stats tracking is always
230          * disabled at the outer level, and instead we set the flag properly in
231          * fmgr_security_definer's private flinfo and implement the tracking
232          * inside fmgr_security_definer.  This loses the ability to charge the
233          * overhead of fmgr_security_definer to the function, but gains the
234          * ability to set the track_functions GUC as a local GUC parameter of an
235          * interesting function and have the right things happen.
236          */
237         if (!ignore_security &&
238                 (procedureStruct->prosecdef ||
239                  !heap_attisnull(procedureTuple, Anum_pg_proc_proconfig) ||
240                  FmgrHookIsNeeded(functionId)))
241         {
242                 finfo->fn_addr = fmgr_security_definer;
243                 finfo->fn_stats = TRACK_FUNC_ALL;               /* ie, never track */
244                 finfo->fn_oid = functionId;
245                 ReleaseSysCache(procedureTuple);
246                 return;
247         }
248
249         switch (procedureStruct->prolang)
250         {
251                 case INTERNALlanguageId:
252
253                         /*
254                          * For an ordinary builtin function, we should never get here
255                          * because the isbuiltin() search above will have succeeded.
256                          * However, if the user has done a CREATE FUNCTION to create an
257                          * alias for a builtin function, we can end up here.  In that case
258                          * we have to look up the function by name.  The name of the
259                          * internal function is stored in prosrc (it doesn't have to be
260                          * the same as the name of the alias!)
261                          */
262                         prosrcdatum = SysCacheGetAttr(PROCOID, procedureTuple,
263                                                                                   Anum_pg_proc_prosrc, &isnull);
264                         if (isnull)
265                                 elog(ERROR, "null prosrc");
266                         prosrc = TextDatumGetCString(prosrcdatum);
267                         fbp = fmgr_lookupByName(prosrc);
268                         if (fbp == NULL)
269                                 ereport(ERROR,
270                                                 (errcode(ERRCODE_UNDEFINED_FUNCTION),
271                                                  errmsg("internal function \"%s\" is not in internal lookup table",
272                                                                 prosrc)));
273                         pfree(prosrc);
274                         /* Should we check that nargs, strict, retset match the table? */
275                         finfo->fn_addr = fbp->func;
276                         /* note this policy is also assumed in fast path above */
277                         finfo->fn_stats = TRACK_FUNC_ALL;       /* ie, never track */
278                         break;
279
280                 case ClanguageId:
281                         fmgr_info_C_lang(functionId, finfo, procedureTuple);
282                         finfo->fn_stats = TRACK_FUNC_PL;        /* ie, track if ALL */
283                         break;
284
285                 case SQLlanguageId:
286                         finfo->fn_addr = fmgr_sql;
287                         finfo->fn_stats = TRACK_FUNC_PL;        /* ie, track if ALL */
288                         break;
289
290                 default:
291                         fmgr_info_other_lang(functionId, finfo, procedureTuple);
292                         finfo->fn_stats = TRACK_FUNC_OFF;       /* ie, track if not OFF */
293                         break;
294         }
295
296         finfo->fn_oid = functionId;
297         ReleaseSysCache(procedureTuple);
298 }
299
300 /*
301  * Special fmgr_info processing for C-language functions.  Note that
302  * finfo->fn_oid is not valid yet.
303  */
304 static void
305 fmgr_info_C_lang(Oid functionId, FmgrInfo *finfo, HeapTuple procedureTuple)
306 {
307         Form_pg_proc procedureStruct = (Form_pg_proc) GETSTRUCT(procedureTuple);
308         CFuncHashTabEntry *hashentry;
309         PGFunction      user_fn;
310         const Pg_finfo_record *inforec;
311         Oldstyle_fnextra *fnextra;
312         bool            isnull;
313         int                     i;
314
315         /*
316          * See if we have the function address cached already
317          */
318         hashentry = lookup_C_func(procedureTuple);
319         if (hashentry)
320         {
321                 user_fn = hashentry->user_fn;
322                 inforec = hashentry->inforec;
323         }
324         else
325         {
326                 Datum           prosrcattr,
327                                         probinattr;
328                 char       *prosrcstring,
329                                    *probinstring;
330                 void       *libraryhandle;
331
332                 /*
333                  * Get prosrc and probin strings (link symbol and library filename).
334                  * While in general these columns might be null, that's not allowed
335                  * for C-language functions.
336                  */
337                 prosrcattr = SysCacheGetAttr(PROCOID, procedureTuple,
338                                                                          Anum_pg_proc_prosrc, &isnull);
339                 if (isnull)
340                         elog(ERROR, "null prosrc for C function %u", functionId);
341                 prosrcstring = TextDatumGetCString(prosrcattr);
342
343                 probinattr = SysCacheGetAttr(PROCOID, procedureTuple,
344                                                                          Anum_pg_proc_probin, &isnull);
345                 if (isnull)
346                         elog(ERROR, "null probin for C function %u", functionId);
347                 probinstring = TextDatumGetCString(probinattr);
348
349                 /* Look up the function itself */
350                 user_fn = load_external_function(probinstring, prosrcstring, true,
351                                                                                  &libraryhandle);
352
353                 /* Get the function information record (real or default) */
354                 inforec = fetch_finfo_record(libraryhandle, prosrcstring);
355
356                 /* Cache the addresses for later calls */
357                 record_C_func(procedureTuple, user_fn, inforec);
358
359                 pfree(prosrcstring);
360                 pfree(probinstring);
361         }
362
363         switch (inforec->api_version)
364         {
365                 case 0:
366                         /* Old style: need to use a handler */
367                         finfo->fn_addr = fmgr_oldstyle;
368                         fnextra = (Oldstyle_fnextra *)
369                                 MemoryContextAllocZero(finfo->fn_mcxt,
370                                                                            sizeof(Oldstyle_fnextra));
371                         finfo->fn_extra = (void *) fnextra;
372                         fnextra->func = (func_ptr) user_fn;
373                         for (i = 0; i < procedureStruct->pronargs; i++)
374                         {
375                                 fnextra->arg_toastable[i] =
376                                         TypeIsToastable(procedureStruct->proargtypes.values[i]);
377                         }
378                         break;
379                 case 1:
380                         /* New style: call directly */
381                         finfo->fn_addr = user_fn;
382                         break;
383                 default:
384                         /* Shouldn't get here if fetch_finfo_record did its job */
385                         elog(ERROR, "unrecognized function API version: %d",
386                                  inforec->api_version);
387                         break;
388         }
389 }
390
391 /*
392  * Special fmgr_info processing for other-language functions.  Note
393  * that finfo->fn_oid is not valid yet.
394  */
395 static void
396 fmgr_info_other_lang(Oid functionId, FmgrInfo *finfo, HeapTuple procedureTuple)
397 {
398         Form_pg_proc procedureStruct = (Form_pg_proc) GETSTRUCT(procedureTuple);
399         Oid                     language = procedureStruct->prolang;
400         HeapTuple       languageTuple;
401         Form_pg_language languageStruct;
402         FmgrInfo        plfinfo;
403
404         languageTuple = SearchSysCache1(LANGOID, ObjectIdGetDatum(language));
405         if (!HeapTupleIsValid(languageTuple))
406                 elog(ERROR, "cache lookup failed for language %u", language);
407         languageStruct = (Form_pg_language) GETSTRUCT(languageTuple);
408
409         /*
410          * Look up the language's call handler function, ignoring any attributes
411          * that would normally cause insertion of fmgr_security_definer.  We need
412          * to get back a bare pointer to the actual C-language function.
413          */
414         fmgr_info_cxt_security(languageStruct->lanplcallfoid, &plfinfo,
415                                                    CurrentMemoryContext, true);
416         finfo->fn_addr = plfinfo.fn_addr;
417
418         /*
419          * If lookup of the PL handler function produced nonnull fn_extra,
420          * complain --- it must be an oldstyle function! We no longer support
421          * oldstyle PL handlers.
422          */
423         if (plfinfo.fn_extra != NULL)
424                 elog(ERROR, "language %u has old-style handler", language);
425
426         ReleaseSysCache(languageTuple);
427 }
428
429 /*
430  * Fetch and validate the information record for the given external function.
431  * The function is specified by a handle for the containing library
432  * (obtained from load_external_function) as well as the function name.
433  *
434  * If no info function exists for the given name, it is not an error.
435  * Instead we return a default info record for a version-0 function.
436  * We want to raise an error here only if the info function returns
437  * something bogus.
438  *
439  * This function is broken out of fmgr_info_C_lang so that fmgr_c_validator
440  * can validate the information record for a function not yet entered into
441  * pg_proc.
442  */
443 const Pg_finfo_record *
444 fetch_finfo_record(void *filehandle, char *funcname)
445 {
446         char       *infofuncname;
447         PGFInfoFunction infofunc;
448         const Pg_finfo_record *inforec;
449         static Pg_finfo_record default_inforec = {0};
450
451         infofuncname = psprintf("pg_finfo_%s", funcname);
452
453         /* Try to look up the info function */
454         infofunc = (PGFInfoFunction) lookup_external_function(filehandle,
455                                                                                                                   infofuncname);
456         if (infofunc == NULL)
457         {
458                 /* Not found --- assume version 0 */
459                 pfree(infofuncname);
460                 return &default_inforec;
461         }
462
463         /* Found, so call it */
464         inforec = (*infofunc) ();
465
466         /* Validate result as best we can */
467         if (inforec == NULL)
468                 elog(ERROR, "null result from info function \"%s\"", infofuncname);
469         switch (inforec->api_version)
470         {
471                 case 0:
472                 case 1:
473                         /* OK, no additional fields to validate */
474                         break;
475                 default:
476                         ereport(ERROR,
477                                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
478                                          errmsg("unrecognized API version %d reported by info function \"%s\"",
479                                                         inforec->api_version, infofuncname)));
480                         break;
481         }
482
483         pfree(infofuncname);
484         return inforec;
485 }
486
487
488 /*-------------------------------------------------------------------------
489  *              Routines for caching lookup information for external C functions.
490  *
491  * The routines in dfmgr.c are relatively slow, so we try to avoid running
492  * them more than once per external function per session.  We use a hash table
493  * with the function OID as the lookup key.
494  *-------------------------------------------------------------------------
495  */
496
497 /*
498  * lookup_C_func: try to find a C function in the hash table
499  *
500  * If an entry exists and is up to date, return it; else return NULL
501  */
502 static CFuncHashTabEntry *
503 lookup_C_func(HeapTuple procedureTuple)
504 {
505         Oid                     fn_oid = HeapTupleGetOid(procedureTuple);
506         CFuncHashTabEntry *entry;
507
508         if (CFuncHash == NULL)
509                 return NULL;                    /* no table yet */
510         entry = (CFuncHashTabEntry *)
511                 hash_search(CFuncHash,
512                                         &fn_oid,
513                                         HASH_FIND,
514                                         NULL);
515         if (entry == NULL)
516                 return NULL;                    /* no such entry */
517         if (entry->fn_xmin == HeapTupleHeaderGetRawXmin(procedureTuple->t_data) &&
518                 ItemPointerEquals(&entry->fn_tid, &procedureTuple->t_self))
519                 return entry;                   /* OK */
520         return NULL;                            /* entry is out of date */
521 }
522
523 /*
524  * record_C_func: enter (or update) info about a C function in the hash table
525  */
526 static void
527 record_C_func(HeapTuple procedureTuple,
528                           PGFunction user_fn, const Pg_finfo_record *inforec)
529 {
530         Oid                     fn_oid = HeapTupleGetOid(procedureTuple);
531         CFuncHashTabEntry *entry;
532         bool            found;
533
534         /* Create the hash table if it doesn't exist yet */
535         if (CFuncHash == NULL)
536         {
537                 HASHCTL         hash_ctl;
538
539                 MemSet(&hash_ctl, 0, sizeof(hash_ctl));
540                 hash_ctl.keysize = sizeof(Oid);
541                 hash_ctl.entrysize = sizeof(CFuncHashTabEntry);
542                 CFuncHash = hash_create("CFuncHash",
543                                                                 100,
544                                                                 &hash_ctl,
545                                                                 HASH_ELEM | HASH_BLOBS);
546         }
547
548         entry = (CFuncHashTabEntry *)
549                 hash_search(CFuncHash,
550                                         &fn_oid,
551                                         HASH_ENTER,
552                                         &found);
553         /* OID is already filled in */
554         entry->fn_xmin = HeapTupleHeaderGetRawXmin(procedureTuple->t_data);
555         entry->fn_tid = procedureTuple->t_self;
556         entry->user_fn = user_fn;
557         entry->inforec = inforec;
558 }
559
560 /*
561  * clear_external_function_hash: remove entries for a library being closed
562  *
563  * Presently we just zap the entire hash table, but later it might be worth
564  * the effort to remove only the entries associated with the given handle.
565  */
566 void
567 clear_external_function_hash(void *filehandle)
568 {
569         if (CFuncHash)
570                 hash_destroy(CFuncHash);
571         CFuncHash = NULL;
572 }
573
574
575 /*
576  * Copy an FmgrInfo struct
577  *
578  * This is inherently somewhat bogus since we can't reliably duplicate
579  * language-dependent subsidiary info.  We cheat by zeroing fn_extra,
580  * instead, meaning that subsidiary info will have to be recomputed.
581  */
582 void
583 fmgr_info_copy(FmgrInfo *dstinfo, FmgrInfo *srcinfo,
584                            MemoryContext destcxt)
585 {
586         memcpy(dstinfo, srcinfo, sizeof(FmgrInfo));
587         dstinfo->fn_mcxt = destcxt;
588         if (dstinfo->fn_addr == fmgr_oldstyle)
589         {
590                 /* For oldstyle functions we must copy fn_extra */
591                 Oldstyle_fnextra *fnextra;
592
593                 fnextra = (Oldstyle_fnextra *)
594                         MemoryContextAlloc(destcxt, sizeof(Oldstyle_fnextra));
595                 memcpy(fnextra, srcinfo->fn_extra, sizeof(Oldstyle_fnextra));
596                 dstinfo->fn_extra = (void *) fnextra;
597         }
598         else
599                 dstinfo->fn_extra = NULL;
600 }
601
602
603 /*
604  * Specialized lookup routine for fmgr_internal_validator: given the alleged
605  * name of an internal function, return the OID of the function.
606  * If the name is not recognized, return InvalidOid.
607  */
608 Oid
609 fmgr_internal_function(const char *proname)
610 {
611         const FmgrBuiltin *fbp = fmgr_lookupByName(proname);
612
613         if (fbp == NULL)
614                 return InvalidOid;
615         return fbp->foid;
616 }
617
618
619 /*
620  * Handler for old-style "C" language functions
621  */
622 static Datum
623 fmgr_oldstyle(PG_FUNCTION_ARGS)
624 {
625         Oldstyle_fnextra *fnextra;
626         int                     n_arguments = fcinfo->nargs;
627         int                     i;
628         bool            isnull;
629         func_ptr        user_fn;
630         char       *returnValue;
631
632         if (fcinfo->flinfo == NULL || fcinfo->flinfo->fn_extra == NULL)
633                 elog(ERROR, "fmgr_oldstyle received NULL pointer");
634         fnextra = (Oldstyle_fnextra *) fcinfo->flinfo->fn_extra;
635
636         /*
637          * Result is NULL if any argument is NULL, but we still call the function
638          * (peculiar, but that's the way it worked before, and after all this is a
639          * backwards-compatibility wrapper).  Note, however, that we'll never get
640          * here with NULL arguments if the function is marked strict.
641          *
642          * We also need to detoast any TOAST-ed inputs, since it's unlikely that
643          * an old-style function knows about TOASTing.
644          */
645         isnull = false;
646         for (i = 0; i < n_arguments; i++)
647         {
648                 if (PG_ARGISNULL(i))
649                         isnull = true;
650                 else if (fnextra->arg_toastable[i])
651                         fcinfo->arg[i] = PointerGetDatum(PG_DETOAST_DATUM(fcinfo->arg[i]));
652         }
653         fcinfo->isnull = isnull;
654
655         user_fn = fnextra->func;
656
657         switch (n_arguments)
658         {
659                 case 0:
660                         returnValue = (char *) (*user_fn) ();
661                         break;
662                 case 1:
663
664                         /*
665                          * nullvalue() used to use isNull to check if arg is NULL; perhaps
666                          * there are other functions still out there that also rely on
667                          * this undocumented hack?
668                          */
669                         returnValue = (char *) (*user_fn) (fcinfo->arg[0],
670                                                                                            &fcinfo->isnull);
671                         break;
672                 case 2:
673                         returnValue = (char *) (*user_fn) (fcinfo->arg[0],
674                                                                                            fcinfo->arg[1]);
675                         break;
676                 case 3:
677                         returnValue = (char *) (*user_fn) (fcinfo->arg[0],
678                                                                                            fcinfo->arg[1],
679                                                                                            fcinfo->arg[2]);
680                         break;
681                 case 4:
682                         returnValue = (char *) (*user_fn) (fcinfo->arg[0],
683                                                                                            fcinfo->arg[1],
684                                                                                            fcinfo->arg[2],
685                                                                                            fcinfo->arg[3]);
686                         break;
687                 case 5:
688                         returnValue = (char *) (*user_fn) (fcinfo->arg[0],
689                                                                                            fcinfo->arg[1],
690                                                                                            fcinfo->arg[2],
691                                                                                            fcinfo->arg[3],
692                                                                                            fcinfo->arg[4]);
693                         break;
694                 case 6:
695                         returnValue = (char *) (*user_fn) (fcinfo->arg[0],
696                                                                                            fcinfo->arg[1],
697                                                                                            fcinfo->arg[2],
698                                                                                            fcinfo->arg[3],
699                                                                                            fcinfo->arg[4],
700                                                                                            fcinfo->arg[5]);
701                         break;
702                 case 7:
703                         returnValue = (char *) (*user_fn) (fcinfo->arg[0],
704                                                                                            fcinfo->arg[1],
705                                                                                            fcinfo->arg[2],
706                                                                                            fcinfo->arg[3],
707                                                                                            fcinfo->arg[4],
708                                                                                            fcinfo->arg[5],
709                                                                                            fcinfo->arg[6]);
710                         break;
711                 case 8:
712                         returnValue = (char *) (*user_fn) (fcinfo->arg[0],
713                                                                                            fcinfo->arg[1],
714                                                                                            fcinfo->arg[2],
715                                                                                            fcinfo->arg[3],
716                                                                                            fcinfo->arg[4],
717                                                                                            fcinfo->arg[5],
718                                                                                            fcinfo->arg[6],
719                                                                                            fcinfo->arg[7]);
720                         break;
721                 case 9:
722                         returnValue = (char *) (*user_fn) (fcinfo->arg[0],
723                                                                                            fcinfo->arg[1],
724                                                                                            fcinfo->arg[2],
725                                                                                            fcinfo->arg[3],
726                                                                                            fcinfo->arg[4],
727                                                                                            fcinfo->arg[5],
728                                                                                            fcinfo->arg[6],
729                                                                                            fcinfo->arg[7],
730                                                                                            fcinfo->arg[8]);
731                         break;
732                 case 10:
733                         returnValue = (char *) (*user_fn) (fcinfo->arg[0],
734                                                                                            fcinfo->arg[1],
735                                                                                            fcinfo->arg[2],
736                                                                                            fcinfo->arg[3],
737                                                                                            fcinfo->arg[4],
738                                                                                            fcinfo->arg[5],
739                                                                                            fcinfo->arg[6],
740                                                                                            fcinfo->arg[7],
741                                                                                            fcinfo->arg[8],
742                                                                                            fcinfo->arg[9]);
743                         break;
744                 case 11:
745                         returnValue = (char *) (*user_fn) (fcinfo->arg[0],
746                                                                                            fcinfo->arg[1],
747                                                                                            fcinfo->arg[2],
748                                                                                            fcinfo->arg[3],
749                                                                                            fcinfo->arg[4],
750                                                                                            fcinfo->arg[5],
751                                                                                            fcinfo->arg[6],
752                                                                                            fcinfo->arg[7],
753                                                                                            fcinfo->arg[8],
754                                                                                            fcinfo->arg[9],
755                                                                                            fcinfo->arg[10]);
756                         break;
757                 case 12:
758                         returnValue = (char *) (*user_fn) (fcinfo->arg[0],
759                                                                                            fcinfo->arg[1],
760                                                                                            fcinfo->arg[2],
761                                                                                            fcinfo->arg[3],
762                                                                                            fcinfo->arg[4],
763                                                                                            fcinfo->arg[5],
764                                                                                            fcinfo->arg[6],
765                                                                                            fcinfo->arg[7],
766                                                                                            fcinfo->arg[8],
767                                                                                            fcinfo->arg[9],
768                                                                                            fcinfo->arg[10],
769                                                                                            fcinfo->arg[11]);
770                         break;
771                 case 13:
772                         returnValue = (char *) (*user_fn) (fcinfo->arg[0],
773                                                                                            fcinfo->arg[1],
774                                                                                            fcinfo->arg[2],
775                                                                                            fcinfo->arg[3],
776                                                                                            fcinfo->arg[4],
777                                                                                            fcinfo->arg[5],
778                                                                                            fcinfo->arg[6],
779                                                                                            fcinfo->arg[7],
780                                                                                            fcinfo->arg[8],
781                                                                                            fcinfo->arg[9],
782                                                                                            fcinfo->arg[10],
783                                                                                            fcinfo->arg[11],
784                                                                                            fcinfo->arg[12]);
785                         break;
786                 case 14:
787                         returnValue = (char *) (*user_fn) (fcinfo->arg[0],
788                                                                                            fcinfo->arg[1],
789                                                                                            fcinfo->arg[2],
790                                                                                            fcinfo->arg[3],
791                                                                                            fcinfo->arg[4],
792                                                                                            fcinfo->arg[5],
793                                                                                            fcinfo->arg[6],
794                                                                                            fcinfo->arg[7],
795                                                                                            fcinfo->arg[8],
796                                                                                            fcinfo->arg[9],
797                                                                                            fcinfo->arg[10],
798                                                                                            fcinfo->arg[11],
799                                                                                            fcinfo->arg[12],
800                                                                                            fcinfo->arg[13]);
801                         break;
802                 case 15:
803                         returnValue = (char *) (*user_fn) (fcinfo->arg[0],
804                                                                                            fcinfo->arg[1],
805                                                                                            fcinfo->arg[2],
806                                                                                            fcinfo->arg[3],
807                                                                                            fcinfo->arg[4],
808                                                                                            fcinfo->arg[5],
809                                                                                            fcinfo->arg[6],
810                                                                                            fcinfo->arg[7],
811                                                                                            fcinfo->arg[8],
812                                                                                            fcinfo->arg[9],
813                                                                                            fcinfo->arg[10],
814                                                                                            fcinfo->arg[11],
815                                                                                            fcinfo->arg[12],
816                                                                                            fcinfo->arg[13],
817                                                                                            fcinfo->arg[14]);
818                         break;
819                 case 16:
820                         returnValue = (char *) (*user_fn) (fcinfo->arg[0],
821                                                                                            fcinfo->arg[1],
822                                                                                            fcinfo->arg[2],
823                                                                                            fcinfo->arg[3],
824                                                                                            fcinfo->arg[4],
825                                                                                            fcinfo->arg[5],
826                                                                                            fcinfo->arg[6],
827                                                                                            fcinfo->arg[7],
828                                                                                            fcinfo->arg[8],
829                                                                                            fcinfo->arg[9],
830                                                                                            fcinfo->arg[10],
831                                                                                            fcinfo->arg[11],
832                                                                                            fcinfo->arg[12],
833                                                                                            fcinfo->arg[13],
834                                                                                            fcinfo->arg[14],
835                                                                                            fcinfo->arg[15]);
836                         break;
837                 default:
838
839                         /*
840                          * Increasing FUNC_MAX_ARGS doesn't automatically add cases to the
841                          * above code, so mention the actual value in this error not
842                          * FUNC_MAX_ARGS.  You could add cases to the above if you needed
843                          * to support old-style functions with many arguments, but making
844                          * 'em be new-style is probably a better idea.
845                          */
846                         ereport(ERROR,
847                                         (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
848                          errmsg("function %u has too many arguments (%d, maximum is %d)",
849                                         fcinfo->flinfo->fn_oid, n_arguments, 16)));
850                         returnValue = NULL; /* keep compiler quiet */
851                         break;
852         }
853
854         return PointerGetDatum(returnValue);
855 }
856
857
858 /*
859  * Support for security-definer and proconfig-using functions.  We support
860  * both of these features using the same call handler, because they are
861  * often used together and it would be inefficient (as well as notationally
862  * messy) to have two levels of call handler involved.
863  */
864 struct fmgr_security_definer_cache
865 {
866         FmgrInfo        flinfo;                 /* lookup info for target function */
867         Oid                     userid;                 /* userid to set, or InvalidOid */
868         ArrayType  *proconfig;          /* GUC values to set, or NULL */
869         Datum           arg;                    /* passthrough argument for plugin modules */
870 };
871
872 /*
873  * Function handler for security-definer/proconfig/plugin-hooked functions.
874  * We extract the OID of the actual function and do a fmgr lookup again.
875  * Then we fetch the pg_proc row and copy the owner ID and proconfig fields.
876  * (All this info is cached for the duration of the current query.)
877  * To execute a call, we temporarily replace the flinfo with the cached
878  * and looked-up one, while keeping the outer fcinfo (which contains all
879  * the actual arguments, etc.) intact.  This is not re-entrant, but then
880  * the fcinfo itself can't be used re-entrantly anyway.
881  */
882 static Datum
883 fmgr_security_definer(PG_FUNCTION_ARGS)
884 {
885         Datum           result;
886         struct fmgr_security_definer_cache *volatile fcache;
887         FmgrInfo   *save_flinfo;
888         Oid                     save_userid;
889         int                     save_sec_context;
890         volatile int save_nestlevel;
891         PgStat_FunctionCallUsage fcusage;
892
893         if (!fcinfo->flinfo->fn_extra)
894         {
895                 HeapTuple       tuple;
896                 Form_pg_proc procedureStruct;
897                 Datum           datum;
898                 bool            isnull;
899                 MemoryContext oldcxt;
900
901                 fcache = MemoryContextAllocZero(fcinfo->flinfo->fn_mcxt,
902                                                                                 sizeof(*fcache));
903
904                 fmgr_info_cxt_security(fcinfo->flinfo->fn_oid, &fcache->flinfo,
905                                                            fcinfo->flinfo->fn_mcxt, true);
906                 fcache->flinfo.fn_expr = fcinfo->flinfo->fn_expr;
907
908                 tuple = SearchSysCache1(PROCOID,
909                                                                 ObjectIdGetDatum(fcinfo->flinfo->fn_oid));
910                 if (!HeapTupleIsValid(tuple))
911                         elog(ERROR, "cache lookup failed for function %u",
912                                  fcinfo->flinfo->fn_oid);
913                 procedureStruct = (Form_pg_proc) GETSTRUCT(tuple);
914
915                 if (procedureStruct->prosecdef)
916                         fcache->userid = procedureStruct->proowner;
917
918                 datum = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_proconfig,
919                                                                 &isnull);
920                 if (!isnull)
921                 {
922                         oldcxt = MemoryContextSwitchTo(fcinfo->flinfo->fn_mcxt);
923                         fcache->proconfig = DatumGetArrayTypePCopy(datum);
924                         MemoryContextSwitchTo(oldcxt);
925                 }
926
927                 ReleaseSysCache(tuple);
928
929                 fcinfo->flinfo->fn_extra = fcache;
930         }
931         else
932                 fcache = fcinfo->flinfo->fn_extra;
933
934         /* GetUserIdAndSecContext is cheap enough that no harm in a wasted call */
935         GetUserIdAndSecContext(&save_userid, &save_sec_context);
936         if (fcache->proconfig)          /* Need a new GUC nesting level */
937                 save_nestlevel = NewGUCNestLevel();
938         else
939                 save_nestlevel = 0;             /* keep compiler quiet */
940
941         if (OidIsValid(fcache->userid))
942                 SetUserIdAndSecContext(fcache->userid,
943                                                         save_sec_context | SECURITY_LOCAL_USERID_CHANGE);
944
945         if (fcache->proconfig)
946         {
947                 ProcessGUCArray(fcache->proconfig,
948                                                 (superuser() ? PGC_SUSET : PGC_USERSET),
949                                                 PGC_S_SESSION,
950                                                 GUC_ACTION_SAVE);
951         }
952
953         /* function manager hook */
954         if (fmgr_hook)
955                 (*fmgr_hook) (FHET_START, &fcache->flinfo, &fcache->arg);
956
957         /*
958          * We don't need to restore GUC or userid settings on error, because the
959          * ensuing xact or subxact abort will do that.  The PG_TRY block is only
960          * needed to clean up the flinfo link.
961          */
962         save_flinfo = fcinfo->flinfo;
963
964         PG_TRY();
965         {
966                 fcinfo->flinfo = &fcache->flinfo;
967
968                 /* See notes in fmgr_info_cxt_security */
969                 pgstat_init_function_usage(fcinfo, &fcusage);
970
971                 result = FunctionCallInvoke(fcinfo);
972
973                 /*
974                  * We could be calling either a regular or a set-returning function,
975                  * so we have to test to see what finalize flag to use.
976                  */
977                 pgstat_end_function_usage(&fcusage,
978                                                                   (fcinfo->resultinfo == NULL ||
979                                                                    !IsA(fcinfo->resultinfo, ReturnSetInfo) ||
980                                                                    ((ReturnSetInfo *) fcinfo->resultinfo)->isDone != ExprMultipleResult));
981         }
982         PG_CATCH();
983         {
984                 fcinfo->flinfo = save_flinfo;
985                 if (fmgr_hook)
986                         (*fmgr_hook) (FHET_ABORT, &fcache->flinfo, &fcache->arg);
987                 PG_RE_THROW();
988         }
989         PG_END_TRY();
990
991         fcinfo->flinfo = save_flinfo;
992
993         if (fcache->proconfig)
994                 AtEOXact_GUC(true, save_nestlevel);
995         if (OidIsValid(fcache->userid))
996                 SetUserIdAndSecContext(save_userid, save_sec_context);
997         if (fmgr_hook)
998                 (*fmgr_hook) (FHET_END, &fcache->flinfo, &fcache->arg);
999
1000         return result;
1001 }
1002
1003
1004 /*-------------------------------------------------------------------------
1005  *              Support routines for callers of fmgr-compatible functions
1006  *-------------------------------------------------------------------------
1007  */
1008
1009 /*
1010  * These are for invocation of a specifically named function with a
1011  * directly-computed parameter list.  Note that neither arguments nor result
1012  * are allowed to be NULL.  Also, the function cannot be one that needs to
1013  * look at FmgrInfo, since there won't be any.
1014  */
1015 Datum
1016 DirectFunctionCall1Coll(PGFunction func, Oid collation, Datum arg1)
1017 {
1018         FunctionCallInfoData fcinfo;
1019         Datum           result;
1020
1021         InitFunctionCallInfoData(fcinfo, NULL, 1, collation, NULL, NULL);
1022
1023         fcinfo.arg[0] = arg1;
1024         fcinfo.argnull[0] = false;
1025
1026         result = (*func) (&fcinfo);
1027
1028         /* Check for null result, since caller is clearly not expecting one */
1029         if (fcinfo.isnull)
1030                 elog(ERROR, "function %p returned NULL", (void *) func);
1031
1032         return result;
1033 }
1034
1035 Datum
1036 DirectFunctionCall2Coll(PGFunction func, Oid collation, Datum arg1, Datum arg2)
1037 {
1038         FunctionCallInfoData fcinfo;
1039         Datum           result;
1040
1041         InitFunctionCallInfoData(fcinfo, NULL, 2, collation, NULL, NULL);
1042
1043         fcinfo.arg[0] = arg1;
1044         fcinfo.arg[1] = arg2;
1045         fcinfo.argnull[0] = false;
1046         fcinfo.argnull[1] = false;
1047
1048         result = (*func) (&fcinfo);
1049
1050         /* Check for null result, since caller is clearly not expecting one */
1051         if (fcinfo.isnull)
1052                 elog(ERROR, "function %p returned NULL", (void *) func);
1053
1054         return result;
1055 }
1056
1057 Datum
1058 DirectFunctionCall3Coll(PGFunction func, Oid collation, Datum arg1, Datum arg2,
1059                                                 Datum arg3)
1060 {
1061         FunctionCallInfoData fcinfo;
1062         Datum           result;
1063
1064         InitFunctionCallInfoData(fcinfo, NULL, 3, collation, NULL, NULL);
1065
1066         fcinfo.arg[0] = arg1;
1067         fcinfo.arg[1] = arg2;
1068         fcinfo.arg[2] = arg3;
1069         fcinfo.argnull[0] = false;
1070         fcinfo.argnull[1] = false;
1071         fcinfo.argnull[2] = false;
1072
1073         result = (*func) (&fcinfo);
1074
1075         /* Check for null result, since caller is clearly not expecting one */
1076         if (fcinfo.isnull)
1077                 elog(ERROR, "function %p returned NULL", (void *) func);
1078
1079         return result;
1080 }
1081
1082 Datum
1083 DirectFunctionCall4Coll(PGFunction func, Oid collation, Datum arg1, Datum arg2,
1084                                                 Datum arg3, Datum arg4)
1085 {
1086         FunctionCallInfoData fcinfo;
1087         Datum           result;
1088
1089         InitFunctionCallInfoData(fcinfo, NULL, 4, collation, NULL, NULL);
1090
1091         fcinfo.arg[0] = arg1;
1092         fcinfo.arg[1] = arg2;
1093         fcinfo.arg[2] = arg3;
1094         fcinfo.arg[3] = arg4;
1095         fcinfo.argnull[0] = false;
1096         fcinfo.argnull[1] = false;
1097         fcinfo.argnull[2] = false;
1098         fcinfo.argnull[3] = false;
1099
1100         result = (*func) (&fcinfo);
1101
1102         /* Check for null result, since caller is clearly not expecting one */
1103         if (fcinfo.isnull)
1104                 elog(ERROR, "function %p returned NULL", (void *) func);
1105
1106         return result;
1107 }
1108
1109 Datum
1110 DirectFunctionCall5Coll(PGFunction func, Oid collation, Datum arg1, Datum arg2,
1111                                                 Datum arg3, Datum arg4, Datum arg5)
1112 {
1113         FunctionCallInfoData fcinfo;
1114         Datum           result;
1115
1116         InitFunctionCallInfoData(fcinfo, NULL, 5, collation, NULL, NULL);
1117
1118         fcinfo.arg[0] = arg1;
1119         fcinfo.arg[1] = arg2;
1120         fcinfo.arg[2] = arg3;
1121         fcinfo.arg[3] = arg4;
1122         fcinfo.arg[4] = arg5;
1123         fcinfo.argnull[0] = false;
1124         fcinfo.argnull[1] = false;
1125         fcinfo.argnull[2] = false;
1126         fcinfo.argnull[3] = false;
1127         fcinfo.argnull[4] = false;
1128
1129         result = (*func) (&fcinfo);
1130
1131         /* Check for null result, since caller is clearly not expecting one */
1132         if (fcinfo.isnull)
1133                 elog(ERROR, "function %p returned NULL", (void *) func);
1134
1135         return result;
1136 }
1137
1138 Datum
1139 DirectFunctionCall6Coll(PGFunction func, Oid collation, Datum arg1, Datum arg2,
1140                                                 Datum arg3, Datum arg4, Datum arg5,
1141                                                 Datum arg6)
1142 {
1143         FunctionCallInfoData fcinfo;
1144         Datum           result;
1145
1146         InitFunctionCallInfoData(fcinfo, NULL, 6, collation, NULL, NULL);
1147
1148         fcinfo.arg[0] = arg1;
1149         fcinfo.arg[1] = arg2;
1150         fcinfo.arg[2] = arg3;
1151         fcinfo.arg[3] = arg4;
1152         fcinfo.arg[4] = arg5;
1153         fcinfo.arg[5] = arg6;
1154         fcinfo.argnull[0] = false;
1155         fcinfo.argnull[1] = false;
1156         fcinfo.argnull[2] = false;
1157         fcinfo.argnull[3] = false;
1158         fcinfo.argnull[4] = false;
1159         fcinfo.argnull[5] = false;
1160
1161         result = (*func) (&fcinfo);
1162
1163         /* Check for null result, since caller is clearly not expecting one */
1164         if (fcinfo.isnull)
1165                 elog(ERROR, "function %p returned NULL", (void *) func);
1166
1167         return result;
1168 }
1169
1170 Datum
1171 DirectFunctionCall7Coll(PGFunction func, Oid collation, Datum arg1, Datum arg2,
1172                                                 Datum arg3, Datum arg4, Datum arg5,
1173                                                 Datum arg6, Datum arg7)
1174 {
1175         FunctionCallInfoData fcinfo;
1176         Datum           result;
1177
1178         InitFunctionCallInfoData(fcinfo, NULL, 7, collation, NULL, NULL);
1179
1180         fcinfo.arg[0] = arg1;
1181         fcinfo.arg[1] = arg2;
1182         fcinfo.arg[2] = arg3;
1183         fcinfo.arg[3] = arg4;
1184         fcinfo.arg[4] = arg5;
1185         fcinfo.arg[5] = arg6;
1186         fcinfo.arg[6] = arg7;
1187         fcinfo.argnull[0] = false;
1188         fcinfo.argnull[1] = false;
1189         fcinfo.argnull[2] = false;
1190         fcinfo.argnull[3] = false;
1191         fcinfo.argnull[4] = false;
1192         fcinfo.argnull[5] = false;
1193         fcinfo.argnull[6] = false;
1194
1195         result = (*func) (&fcinfo);
1196
1197         /* Check for null result, since caller is clearly not expecting one */
1198         if (fcinfo.isnull)
1199                 elog(ERROR, "function %p returned NULL", (void *) func);
1200
1201         return result;
1202 }
1203
1204 Datum
1205 DirectFunctionCall8Coll(PGFunction func, Oid collation, Datum arg1, Datum arg2,
1206                                                 Datum arg3, Datum arg4, Datum arg5,
1207                                                 Datum arg6, Datum arg7, Datum arg8)
1208 {
1209         FunctionCallInfoData fcinfo;
1210         Datum           result;
1211
1212         InitFunctionCallInfoData(fcinfo, NULL, 8, collation, NULL, NULL);
1213
1214         fcinfo.arg[0] = arg1;
1215         fcinfo.arg[1] = arg2;
1216         fcinfo.arg[2] = arg3;
1217         fcinfo.arg[3] = arg4;
1218         fcinfo.arg[4] = arg5;
1219         fcinfo.arg[5] = arg6;
1220         fcinfo.arg[6] = arg7;
1221         fcinfo.arg[7] = arg8;
1222         fcinfo.argnull[0] = false;
1223         fcinfo.argnull[1] = false;
1224         fcinfo.argnull[2] = false;
1225         fcinfo.argnull[3] = false;
1226         fcinfo.argnull[4] = false;
1227         fcinfo.argnull[5] = false;
1228         fcinfo.argnull[6] = false;
1229         fcinfo.argnull[7] = false;
1230
1231         result = (*func) (&fcinfo);
1232
1233         /* Check for null result, since caller is clearly not expecting one */
1234         if (fcinfo.isnull)
1235                 elog(ERROR, "function %p returned NULL", (void *) func);
1236
1237         return result;
1238 }
1239
1240 Datum
1241 DirectFunctionCall9Coll(PGFunction func, Oid collation, Datum arg1, Datum arg2,
1242                                                 Datum arg3, Datum arg4, Datum arg5,
1243                                                 Datum arg6, Datum arg7, Datum arg8,
1244                                                 Datum arg9)
1245 {
1246         FunctionCallInfoData fcinfo;
1247         Datum           result;
1248
1249         InitFunctionCallInfoData(fcinfo, NULL, 9, collation, NULL, NULL);
1250
1251         fcinfo.arg[0] = arg1;
1252         fcinfo.arg[1] = arg2;
1253         fcinfo.arg[2] = arg3;
1254         fcinfo.arg[3] = arg4;
1255         fcinfo.arg[4] = arg5;
1256         fcinfo.arg[5] = arg6;
1257         fcinfo.arg[6] = arg7;
1258         fcinfo.arg[7] = arg8;
1259         fcinfo.arg[8] = arg9;
1260         fcinfo.argnull[0] = false;
1261         fcinfo.argnull[1] = false;
1262         fcinfo.argnull[2] = false;
1263         fcinfo.argnull[3] = false;
1264         fcinfo.argnull[4] = false;
1265         fcinfo.argnull[5] = false;
1266         fcinfo.argnull[6] = false;
1267         fcinfo.argnull[7] = false;
1268         fcinfo.argnull[8] = false;
1269
1270         result = (*func) (&fcinfo);
1271
1272         /* Check for null result, since caller is clearly not expecting one */
1273         if (fcinfo.isnull)
1274                 elog(ERROR, "function %p returned NULL", (void *) func);
1275
1276         return result;
1277 }
1278
1279
1280 /*
1281  * These are for invocation of a previously-looked-up function with a
1282  * directly-computed parameter list.  Note that neither arguments nor result
1283  * are allowed to be NULL.
1284  */
1285 Datum
1286 FunctionCall1Coll(FmgrInfo *flinfo, Oid collation, Datum arg1)
1287 {
1288         FunctionCallInfoData fcinfo;
1289         Datum           result;
1290
1291         InitFunctionCallInfoData(fcinfo, flinfo, 1, collation, NULL, NULL);
1292
1293         fcinfo.arg[0] = arg1;
1294         fcinfo.argnull[0] = false;
1295
1296         result = FunctionCallInvoke(&fcinfo);
1297
1298         /* Check for null result, since caller is clearly not expecting one */
1299         if (fcinfo.isnull)
1300                 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1301
1302         return result;
1303 }
1304
1305 Datum
1306 FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
1307 {
1308         FunctionCallInfoData fcinfo;
1309         Datum           result;
1310
1311         InitFunctionCallInfoData(fcinfo, flinfo, 2, collation, NULL, NULL);
1312
1313         fcinfo.arg[0] = arg1;
1314         fcinfo.arg[1] = arg2;
1315         fcinfo.argnull[0] = false;
1316         fcinfo.argnull[1] = false;
1317
1318         result = FunctionCallInvoke(&fcinfo);
1319
1320         /* Check for null result, since caller is clearly not expecting one */
1321         if (fcinfo.isnull)
1322                 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1323
1324         return result;
1325 }
1326
1327 Datum
1328 FunctionCall3Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2,
1329                                   Datum arg3)
1330 {
1331         FunctionCallInfoData fcinfo;
1332         Datum           result;
1333
1334         InitFunctionCallInfoData(fcinfo, flinfo, 3, collation, NULL, NULL);
1335
1336         fcinfo.arg[0] = arg1;
1337         fcinfo.arg[1] = arg2;
1338         fcinfo.arg[2] = arg3;
1339         fcinfo.argnull[0] = false;
1340         fcinfo.argnull[1] = false;
1341         fcinfo.argnull[2] = false;
1342
1343         result = FunctionCallInvoke(&fcinfo);
1344
1345         /* Check for null result, since caller is clearly not expecting one */
1346         if (fcinfo.isnull)
1347                 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1348
1349         return result;
1350 }
1351
1352 Datum
1353 FunctionCall4Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2,
1354                                   Datum arg3, Datum arg4)
1355 {
1356         FunctionCallInfoData fcinfo;
1357         Datum           result;
1358
1359         InitFunctionCallInfoData(fcinfo, flinfo, 4, collation, NULL, NULL);
1360
1361         fcinfo.arg[0] = arg1;
1362         fcinfo.arg[1] = arg2;
1363         fcinfo.arg[2] = arg3;
1364         fcinfo.arg[3] = arg4;
1365         fcinfo.argnull[0] = false;
1366         fcinfo.argnull[1] = false;
1367         fcinfo.argnull[2] = false;
1368         fcinfo.argnull[3] = false;
1369
1370         result = FunctionCallInvoke(&fcinfo);
1371
1372         /* Check for null result, since caller is clearly not expecting one */
1373         if (fcinfo.isnull)
1374                 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1375
1376         return result;
1377 }
1378
1379 Datum
1380 FunctionCall5Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2,
1381                                   Datum arg3, Datum arg4, Datum arg5)
1382 {
1383         FunctionCallInfoData fcinfo;
1384         Datum           result;
1385
1386         InitFunctionCallInfoData(fcinfo, flinfo, 5, collation, NULL, NULL);
1387
1388         fcinfo.arg[0] = arg1;
1389         fcinfo.arg[1] = arg2;
1390         fcinfo.arg[2] = arg3;
1391         fcinfo.arg[3] = arg4;
1392         fcinfo.arg[4] = arg5;
1393         fcinfo.argnull[0] = false;
1394         fcinfo.argnull[1] = false;
1395         fcinfo.argnull[2] = false;
1396         fcinfo.argnull[3] = false;
1397         fcinfo.argnull[4] = false;
1398
1399         result = FunctionCallInvoke(&fcinfo);
1400
1401         /* Check for null result, since caller is clearly not expecting one */
1402         if (fcinfo.isnull)
1403                 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1404
1405         return result;
1406 }
1407
1408 Datum
1409 FunctionCall6Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2,
1410                                   Datum arg3, Datum arg4, Datum arg5,
1411                                   Datum arg6)
1412 {
1413         FunctionCallInfoData fcinfo;
1414         Datum           result;
1415
1416         InitFunctionCallInfoData(fcinfo, flinfo, 6, collation, NULL, NULL);
1417
1418         fcinfo.arg[0] = arg1;
1419         fcinfo.arg[1] = arg2;
1420         fcinfo.arg[2] = arg3;
1421         fcinfo.arg[3] = arg4;
1422         fcinfo.arg[4] = arg5;
1423         fcinfo.arg[5] = arg6;
1424         fcinfo.argnull[0] = false;
1425         fcinfo.argnull[1] = false;
1426         fcinfo.argnull[2] = false;
1427         fcinfo.argnull[3] = false;
1428         fcinfo.argnull[4] = false;
1429         fcinfo.argnull[5] = false;
1430
1431         result = FunctionCallInvoke(&fcinfo);
1432
1433         /* Check for null result, since caller is clearly not expecting one */
1434         if (fcinfo.isnull)
1435                 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1436
1437         return result;
1438 }
1439
1440 Datum
1441 FunctionCall7Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2,
1442                                   Datum arg3, Datum arg4, Datum arg5,
1443                                   Datum arg6, Datum arg7)
1444 {
1445         FunctionCallInfoData fcinfo;
1446         Datum           result;
1447
1448         InitFunctionCallInfoData(fcinfo, flinfo, 7, collation, NULL, NULL);
1449
1450         fcinfo.arg[0] = arg1;
1451         fcinfo.arg[1] = arg2;
1452         fcinfo.arg[2] = arg3;
1453         fcinfo.arg[3] = arg4;
1454         fcinfo.arg[4] = arg5;
1455         fcinfo.arg[5] = arg6;
1456         fcinfo.arg[6] = arg7;
1457         fcinfo.argnull[0] = false;
1458         fcinfo.argnull[1] = false;
1459         fcinfo.argnull[2] = false;
1460         fcinfo.argnull[3] = false;
1461         fcinfo.argnull[4] = false;
1462         fcinfo.argnull[5] = false;
1463         fcinfo.argnull[6] = false;
1464
1465         result = FunctionCallInvoke(&fcinfo);
1466
1467         /* Check for null result, since caller is clearly not expecting one */
1468         if (fcinfo.isnull)
1469                 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1470
1471         return result;
1472 }
1473
1474 Datum
1475 FunctionCall8Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2,
1476                                   Datum arg3, Datum arg4, Datum arg5,
1477                                   Datum arg6, Datum arg7, Datum arg8)
1478 {
1479         FunctionCallInfoData fcinfo;
1480         Datum           result;
1481
1482         InitFunctionCallInfoData(fcinfo, flinfo, 8, collation, NULL, NULL);
1483
1484         fcinfo.arg[0] = arg1;
1485         fcinfo.arg[1] = arg2;
1486         fcinfo.arg[2] = arg3;
1487         fcinfo.arg[3] = arg4;
1488         fcinfo.arg[4] = arg5;
1489         fcinfo.arg[5] = arg6;
1490         fcinfo.arg[6] = arg7;
1491         fcinfo.arg[7] = arg8;
1492         fcinfo.argnull[0] = false;
1493         fcinfo.argnull[1] = false;
1494         fcinfo.argnull[2] = false;
1495         fcinfo.argnull[3] = false;
1496         fcinfo.argnull[4] = false;
1497         fcinfo.argnull[5] = false;
1498         fcinfo.argnull[6] = false;
1499         fcinfo.argnull[7] = false;
1500
1501         result = FunctionCallInvoke(&fcinfo);
1502
1503         /* Check for null result, since caller is clearly not expecting one */
1504         if (fcinfo.isnull)
1505                 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1506
1507         return result;
1508 }
1509
1510 Datum
1511 FunctionCall9Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2,
1512                                   Datum arg3, Datum arg4, Datum arg5,
1513                                   Datum arg6, Datum arg7, Datum arg8,
1514                                   Datum arg9)
1515 {
1516         FunctionCallInfoData fcinfo;
1517         Datum           result;
1518
1519         InitFunctionCallInfoData(fcinfo, flinfo, 9, collation, NULL, NULL);
1520
1521         fcinfo.arg[0] = arg1;
1522         fcinfo.arg[1] = arg2;
1523         fcinfo.arg[2] = arg3;
1524         fcinfo.arg[3] = arg4;
1525         fcinfo.arg[4] = arg5;
1526         fcinfo.arg[5] = arg6;
1527         fcinfo.arg[6] = arg7;
1528         fcinfo.arg[7] = arg8;
1529         fcinfo.arg[8] = arg9;
1530         fcinfo.argnull[0] = false;
1531         fcinfo.argnull[1] = false;
1532         fcinfo.argnull[2] = false;
1533         fcinfo.argnull[3] = false;
1534         fcinfo.argnull[4] = false;
1535         fcinfo.argnull[5] = false;
1536         fcinfo.argnull[6] = false;
1537         fcinfo.argnull[7] = false;
1538         fcinfo.argnull[8] = false;
1539
1540         result = FunctionCallInvoke(&fcinfo);
1541
1542         /* Check for null result, since caller is clearly not expecting one */
1543         if (fcinfo.isnull)
1544                 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1545
1546         return result;
1547 }
1548
1549
1550 /*
1551  * These are for invocation of a function identified by OID with a
1552  * directly-computed parameter list.  Note that neither arguments nor result
1553  * are allowed to be NULL.  These are essentially fmgr_info() followed
1554  * by FunctionCallN().  If the same function is to be invoked repeatedly,
1555  * do the fmgr_info() once and then use FunctionCallN().
1556  */
1557 Datum
1558 OidFunctionCall0Coll(Oid functionId, Oid collation)
1559 {
1560         FmgrInfo        flinfo;
1561         FunctionCallInfoData fcinfo;
1562         Datum           result;
1563
1564         fmgr_info(functionId, &flinfo);
1565
1566         InitFunctionCallInfoData(fcinfo, &flinfo, 0, collation, NULL, NULL);
1567
1568         result = FunctionCallInvoke(&fcinfo);
1569
1570         /* Check for null result, since caller is clearly not expecting one */
1571         if (fcinfo.isnull)
1572                 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1573
1574         return result;
1575 }
1576
1577 Datum
1578 OidFunctionCall1Coll(Oid functionId, Oid collation, Datum arg1)
1579 {
1580         FmgrInfo        flinfo;
1581         FunctionCallInfoData fcinfo;
1582         Datum           result;
1583
1584         fmgr_info(functionId, &flinfo);
1585
1586         InitFunctionCallInfoData(fcinfo, &flinfo, 1, collation, NULL, NULL);
1587
1588         fcinfo.arg[0] = arg1;
1589         fcinfo.argnull[0] = false;
1590
1591         result = FunctionCallInvoke(&fcinfo);
1592
1593         /* Check for null result, since caller is clearly not expecting one */
1594         if (fcinfo.isnull)
1595                 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1596
1597         return result;
1598 }
1599
1600 Datum
1601 OidFunctionCall2Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2)
1602 {
1603         FmgrInfo        flinfo;
1604         FunctionCallInfoData fcinfo;
1605         Datum           result;
1606
1607         fmgr_info(functionId, &flinfo);
1608
1609         InitFunctionCallInfoData(fcinfo, &flinfo, 2, collation, NULL, NULL);
1610
1611         fcinfo.arg[0] = arg1;
1612         fcinfo.arg[1] = arg2;
1613         fcinfo.argnull[0] = false;
1614         fcinfo.argnull[1] = false;
1615
1616         result = FunctionCallInvoke(&fcinfo);
1617
1618         /* Check for null result, since caller is clearly not expecting one */
1619         if (fcinfo.isnull)
1620                 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1621
1622         return result;
1623 }
1624
1625 Datum
1626 OidFunctionCall3Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2,
1627                                          Datum arg3)
1628 {
1629         FmgrInfo        flinfo;
1630         FunctionCallInfoData fcinfo;
1631         Datum           result;
1632
1633         fmgr_info(functionId, &flinfo);
1634
1635         InitFunctionCallInfoData(fcinfo, &flinfo, 3, collation, NULL, NULL);
1636
1637         fcinfo.arg[0] = arg1;
1638         fcinfo.arg[1] = arg2;
1639         fcinfo.arg[2] = arg3;
1640         fcinfo.argnull[0] = false;
1641         fcinfo.argnull[1] = false;
1642         fcinfo.argnull[2] = false;
1643
1644         result = FunctionCallInvoke(&fcinfo);
1645
1646         /* Check for null result, since caller is clearly not expecting one */
1647         if (fcinfo.isnull)
1648                 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1649
1650         return result;
1651 }
1652
1653 Datum
1654 OidFunctionCall4Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2,
1655                                          Datum arg3, Datum arg4)
1656 {
1657         FmgrInfo        flinfo;
1658         FunctionCallInfoData fcinfo;
1659         Datum           result;
1660
1661         fmgr_info(functionId, &flinfo);
1662
1663         InitFunctionCallInfoData(fcinfo, &flinfo, 4, collation, NULL, NULL);
1664
1665         fcinfo.arg[0] = arg1;
1666         fcinfo.arg[1] = arg2;
1667         fcinfo.arg[2] = arg3;
1668         fcinfo.arg[3] = arg4;
1669         fcinfo.argnull[0] = false;
1670         fcinfo.argnull[1] = false;
1671         fcinfo.argnull[2] = false;
1672         fcinfo.argnull[3] = false;
1673
1674         result = FunctionCallInvoke(&fcinfo);
1675
1676         /* Check for null result, since caller is clearly not expecting one */
1677         if (fcinfo.isnull)
1678                 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1679
1680         return result;
1681 }
1682
1683 Datum
1684 OidFunctionCall5Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2,
1685                                          Datum arg3, Datum arg4, Datum arg5)
1686 {
1687         FmgrInfo        flinfo;
1688         FunctionCallInfoData fcinfo;
1689         Datum           result;
1690
1691         fmgr_info(functionId, &flinfo);
1692
1693         InitFunctionCallInfoData(fcinfo, &flinfo, 5, collation, NULL, NULL);
1694
1695         fcinfo.arg[0] = arg1;
1696         fcinfo.arg[1] = arg2;
1697         fcinfo.arg[2] = arg3;
1698         fcinfo.arg[3] = arg4;
1699         fcinfo.arg[4] = arg5;
1700         fcinfo.argnull[0] = false;
1701         fcinfo.argnull[1] = false;
1702         fcinfo.argnull[2] = false;
1703         fcinfo.argnull[3] = false;
1704         fcinfo.argnull[4] = false;
1705
1706         result = FunctionCallInvoke(&fcinfo);
1707
1708         /* Check for null result, since caller is clearly not expecting one */
1709         if (fcinfo.isnull)
1710                 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1711
1712         return result;
1713 }
1714
1715 Datum
1716 OidFunctionCall6Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2,
1717                                          Datum arg3, Datum arg4, Datum arg5,
1718                                          Datum arg6)
1719 {
1720         FmgrInfo        flinfo;
1721         FunctionCallInfoData fcinfo;
1722         Datum           result;
1723
1724         fmgr_info(functionId, &flinfo);
1725
1726         InitFunctionCallInfoData(fcinfo, &flinfo, 6, collation, NULL, NULL);
1727
1728         fcinfo.arg[0] = arg1;
1729         fcinfo.arg[1] = arg2;
1730         fcinfo.arg[2] = arg3;
1731         fcinfo.arg[3] = arg4;
1732         fcinfo.arg[4] = arg5;
1733         fcinfo.arg[5] = arg6;
1734         fcinfo.argnull[0] = false;
1735         fcinfo.argnull[1] = false;
1736         fcinfo.argnull[2] = false;
1737         fcinfo.argnull[3] = false;
1738         fcinfo.argnull[4] = false;
1739         fcinfo.argnull[5] = false;
1740
1741         result = FunctionCallInvoke(&fcinfo);
1742
1743         /* Check for null result, since caller is clearly not expecting one */
1744         if (fcinfo.isnull)
1745                 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1746
1747         return result;
1748 }
1749
1750 Datum
1751 OidFunctionCall7Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2,
1752                                          Datum arg3, Datum arg4, Datum arg5,
1753                                          Datum arg6, Datum arg7)
1754 {
1755         FmgrInfo        flinfo;
1756         FunctionCallInfoData fcinfo;
1757         Datum           result;
1758
1759         fmgr_info(functionId, &flinfo);
1760
1761         InitFunctionCallInfoData(fcinfo, &flinfo, 7, collation, NULL, NULL);
1762
1763         fcinfo.arg[0] = arg1;
1764         fcinfo.arg[1] = arg2;
1765         fcinfo.arg[2] = arg3;
1766         fcinfo.arg[3] = arg4;
1767         fcinfo.arg[4] = arg5;
1768         fcinfo.arg[5] = arg6;
1769         fcinfo.arg[6] = arg7;
1770         fcinfo.argnull[0] = false;
1771         fcinfo.argnull[1] = false;
1772         fcinfo.argnull[2] = false;
1773         fcinfo.argnull[3] = false;
1774         fcinfo.argnull[4] = false;
1775         fcinfo.argnull[5] = false;
1776         fcinfo.argnull[6] = false;
1777
1778         result = FunctionCallInvoke(&fcinfo);
1779
1780         /* Check for null result, since caller is clearly not expecting one */
1781         if (fcinfo.isnull)
1782                 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1783
1784         return result;
1785 }
1786
1787 Datum
1788 OidFunctionCall8Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2,
1789                                          Datum arg3, Datum arg4, Datum arg5,
1790                                          Datum arg6, Datum arg7, Datum arg8)
1791 {
1792         FmgrInfo        flinfo;
1793         FunctionCallInfoData fcinfo;
1794         Datum           result;
1795
1796         fmgr_info(functionId, &flinfo);
1797
1798         InitFunctionCallInfoData(fcinfo, &flinfo, 8, collation, NULL, NULL);
1799
1800         fcinfo.arg[0] = arg1;
1801         fcinfo.arg[1] = arg2;
1802         fcinfo.arg[2] = arg3;
1803         fcinfo.arg[3] = arg4;
1804         fcinfo.arg[4] = arg5;
1805         fcinfo.arg[5] = arg6;
1806         fcinfo.arg[6] = arg7;
1807         fcinfo.arg[7] = arg8;
1808         fcinfo.argnull[0] = false;
1809         fcinfo.argnull[1] = false;
1810         fcinfo.argnull[2] = false;
1811         fcinfo.argnull[3] = false;
1812         fcinfo.argnull[4] = false;
1813         fcinfo.argnull[5] = false;
1814         fcinfo.argnull[6] = false;
1815         fcinfo.argnull[7] = false;
1816
1817         result = FunctionCallInvoke(&fcinfo);
1818
1819         /* Check for null result, since caller is clearly not expecting one */
1820         if (fcinfo.isnull)
1821                 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1822
1823         return result;
1824 }
1825
1826 Datum
1827 OidFunctionCall9Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2,
1828                                          Datum arg3, Datum arg4, Datum arg5,
1829                                          Datum arg6, Datum arg7, Datum arg8,
1830                                          Datum arg9)
1831 {
1832         FmgrInfo        flinfo;
1833         FunctionCallInfoData fcinfo;
1834         Datum           result;
1835
1836         fmgr_info(functionId, &flinfo);
1837
1838         InitFunctionCallInfoData(fcinfo, &flinfo, 9, collation, NULL, NULL);
1839
1840         fcinfo.arg[0] = arg1;
1841         fcinfo.arg[1] = arg2;
1842         fcinfo.arg[2] = arg3;
1843         fcinfo.arg[3] = arg4;
1844         fcinfo.arg[4] = arg5;
1845         fcinfo.arg[5] = arg6;
1846         fcinfo.arg[6] = arg7;
1847         fcinfo.arg[7] = arg8;
1848         fcinfo.arg[8] = arg9;
1849         fcinfo.argnull[0] = false;
1850         fcinfo.argnull[1] = false;
1851         fcinfo.argnull[2] = false;
1852         fcinfo.argnull[3] = false;
1853         fcinfo.argnull[4] = false;
1854         fcinfo.argnull[5] = false;
1855         fcinfo.argnull[6] = false;
1856         fcinfo.argnull[7] = false;
1857         fcinfo.argnull[8] = false;
1858
1859         result = FunctionCallInvoke(&fcinfo);
1860
1861         /* Check for null result, since caller is clearly not expecting one */
1862         if (fcinfo.isnull)
1863                 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1864
1865         return result;
1866 }
1867
1868
1869 /*
1870  * Special cases for convenient invocation of datatype I/O functions.
1871  */
1872
1873 /*
1874  * Call a previously-looked-up datatype input function.
1875  *
1876  * "str" may be NULL to indicate we are reading a NULL.  In this case
1877  * the caller should assume the result is NULL, but we'll call the input
1878  * function anyway if it's not strict.  So this is almost but not quite
1879  * the same as FunctionCall3.
1880  */
1881 Datum
1882 InputFunctionCall(FmgrInfo *flinfo, char *str, Oid typioparam, int32 typmod)
1883 {
1884         FunctionCallInfoData fcinfo;
1885         Datum           result;
1886
1887         if (str == NULL && flinfo->fn_strict)
1888                 return (Datum) 0;               /* just return null result */
1889
1890         InitFunctionCallInfoData(fcinfo, flinfo, 3, InvalidOid, NULL, NULL);
1891
1892         fcinfo.arg[0] = CStringGetDatum(str);
1893         fcinfo.arg[1] = ObjectIdGetDatum(typioparam);
1894         fcinfo.arg[2] = Int32GetDatum(typmod);
1895         fcinfo.argnull[0] = (str == NULL);
1896         fcinfo.argnull[1] = false;
1897         fcinfo.argnull[2] = false;
1898
1899         result = FunctionCallInvoke(&fcinfo);
1900
1901         /* Should get null result if and only if str is NULL */
1902         if (str == NULL)
1903         {
1904                 if (!fcinfo.isnull)
1905                         elog(ERROR, "input function %u returned non-NULL",
1906                                  fcinfo.flinfo->fn_oid);
1907         }
1908         else
1909         {
1910                 if (fcinfo.isnull)
1911                         elog(ERROR, "input function %u returned NULL",
1912                                  fcinfo.flinfo->fn_oid);
1913         }
1914
1915         return result;
1916 }
1917
1918 /*
1919  * Call a previously-looked-up datatype output function.
1920  *
1921  * Do not call this on NULL datums.
1922  *
1923  * This is currently little more than window dressing for FunctionCall1.
1924  */
1925 char *
1926 OutputFunctionCall(FmgrInfo *flinfo, Datum val)
1927 {
1928         return DatumGetCString(FunctionCall1(flinfo, val));
1929 }
1930
1931 /*
1932  * Call a previously-looked-up datatype binary-input function.
1933  *
1934  * "buf" may be NULL to indicate we are reading a NULL.  In this case
1935  * the caller should assume the result is NULL, but we'll call the receive
1936  * function anyway if it's not strict.  So this is almost but not quite
1937  * the same as FunctionCall3.
1938  */
1939 Datum
1940 ReceiveFunctionCall(FmgrInfo *flinfo, StringInfo buf,
1941                                         Oid typioparam, int32 typmod)
1942 {
1943         FunctionCallInfoData fcinfo;
1944         Datum           result;
1945
1946         if (buf == NULL && flinfo->fn_strict)
1947                 return (Datum) 0;               /* just return null result */
1948
1949         InitFunctionCallInfoData(fcinfo, flinfo, 3, InvalidOid, NULL, NULL);
1950
1951         fcinfo.arg[0] = PointerGetDatum(buf);
1952         fcinfo.arg[1] = ObjectIdGetDatum(typioparam);
1953         fcinfo.arg[2] = Int32GetDatum(typmod);
1954         fcinfo.argnull[0] = (buf == NULL);
1955         fcinfo.argnull[1] = false;
1956         fcinfo.argnull[2] = false;
1957
1958         result = FunctionCallInvoke(&fcinfo);
1959
1960         /* Should get null result if and only if buf is NULL */
1961         if (buf == NULL)
1962         {
1963                 if (!fcinfo.isnull)
1964                         elog(ERROR, "receive function %u returned non-NULL",
1965                                  fcinfo.flinfo->fn_oid);
1966         }
1967         else
1968         {
1969                 if (fcinfo.isnull)
1970                         elog(ERROR, "receive function %u returned NULL",
1971                                  fcinfo.flinfo->fn_oid);
1972         }
1973
1974         return result;
1975 }
1976
1977 /*
1978  * Call a previously-looked-up datatype binary-output function.
1979  *
1980  * Do not call this on NULL datums.
1981  *
1982  * This is little more than window dressing for FunctionCall1, but it does
1983  * guarantee a non-toasted result, which strictly speaking the underlying
1984  * function doesn't.
1985  */
1986 bytea *
1987 SendFunctionCall(FmgrInfo *flinfo, Datum val)
1988 {
1989         return DatumGetByteaP(FunctionCall1(flinfo, val));
1990 }
1991
1992 /*
1993  * As above, for I/O functions identified by OID.  These are only to be used
1994  * in seldom-executed code paths.  They are not only slow but leak memory.
1995  */
1996 Datum
1997 OidInputFunctionCall(Oid functionId, char *str, Oid typioparam, int32 typmod)
1998 {
1999         FmgrInfo        flinfo;
2000
2001         fmgr_info(functionId, &flinfo);
2002         return InputFunctionCall(&flinfo, str, typioparam, typmod);
2003 }
2004
2005 char *
2006 OidOutputFunctionCall(Oid functionId, Datum val)
2007 {
2008         FmgrInfo        flinfo;
2009
2010         fmgr_info(functionId, &flinfo);
2011         return OutputFunctionCall(&flinfo, val);
2012 }
2013
2014 Datum
2015 OidReceiveFunctionCall(Oid functionId, StringInfo buf,
2016                                            Oid typioparam, int32 typmod)
2017 {
2018         FmgrInfo        flinfo;
2019
2020         fmgr_info(functionId, &flinfo);
2021         return ReceiveFunctionCall(&flinfo, buf, typioparam, typmod);
2022 }
2023
2024 bytea *
2025 OidSendFunctionCall(Oid functionId, Datum val)
2026 {
2027         FmgrInfo        flinfo;
2028
2029         fmgr_info(functionId, &flinfo);
2030         return SendFunctionCall(&flinfo, val);
2031 }
2032
2033
2034 /*
2035  * !!! OLD INTERFACE !!!
2036  *
2037  * fmgr() is the only remaining vestige of the old-style caller support
2038  * functions.  It's no longer used anywhere in the Postgres distribution,
2039  * but we should leave it around for a release or two to ease the transition
2040  * for user-supplied C functions.  OidFunctionCallN() replaces it for new
2041  * code.
2042  *
2043  * DEPRECATED, DO NOT USE IN NEW CODE
2044  */
2045 char *
2046 fmgr(Oid procedureId,...)
2047 {
2048         FmgrInfo        flinfo;
2049         FunctionCallInfoData fcinfo;
2050         int                     n_arguments;
2051         Datum           result;
2052
2053         fmgr_info(procedureId, &flinfo);
2054
2055         MemSet(&fcinfo, 0, sizeof(fcinfo));
2056         fcinfo.flinfo = &flinfo;
2057         fcinfo.nargs = flinfo.fn_nargs;
2058         n_arguments = fcinfo.nargs;
2059
2060         if (n_arguments > 0)
2061         {
2062                 va_list         pvar;
2063                 int                     i;
2064
2065                 if (n_arguments > FUNC_MAX_ARGS)
2066                         ereport(ERROR,
2067                                         (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
2068                          errmsg("function %u has too many arguments (%d, maximum is %d)",
2069                                         flinfo.fn_oid, n_arguments, FUNC_MAX_ARGS)));
2070                 va_start(pvar, procedureId);
2071                 for (i = 0; i < n_arguments; i++)
2072                         fcinfo.arg[i] = PointerGetDatum(va_arg(pvar, char *));
2073                 va_end(pvar);
2074         }
2075
2076         result = FunctionCallInvoke(&fcinfo);
2077
2078         /* Check for null result, since caller is clearly not expecting one */
2079         if (fcinfo.isnull)
2080                 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
2081
2082         return DatumGetPointer(result);
2083 }
2084
2085
2086 /*-------------------------------------------------------------------------
2087  *              Support routines for standard maybe-pass-by-reference datatypes
2088  *
2089  * int8, float4, and float8 can be passed by value if Datum is wide enough.
2090  * (For backwards-compatibility reasons, we allow pass-by-ref to be chosen
2091  * at compile time even if pass-by-val is possible.)
2092  *
2093  * Note: there is only one switch controlling the pass-by-value option for
2094  * both int8 and float8; this is to avoid making things unduly complicated
2095  * for the timestamp types, which might have either representation.
2096  *-------------------------------------------------------------------------
2097  */
2098
2099 #ifndef USE_FLOAT8_BYVAL                /* controls int8 too */
2100
2101 Datum
2102 Int64GetDatum(int64 X)
2103 {
2104         int64      *retval = (int64 *) palloc(sizeof(int64));
2105
2106         *retval = X;
2107         return PointerGetDatum(retval);
2108 }
2109 #endif   /* USE_FLOAT8_BYVAL */
2110
2111 #ifndef USE_FLOAT4_BYVAL
2112
2113 Datum
2114 Float4GetDatum(float4 X)
2115 {
2116         float4     *retval = (float4 *) palloc(sizeof(float4));
2117
2118         *retval = X;
2119         return PointerGetDatum(retval);
2120 }
2121 #endif
2122
2123 #ifndef USE_FLOAT8_BYVAL
2124
2125 Datum
2126 Float8GetDatum(float8 X)
2127 {
2128         float8     *retval = (float8 *) palloc(sizeof(float8));
2129
2130         *retval = X;
2131         return PointerGetDatum(retval);
2132 }
2133 #endif
2134
2135
2136 /*-------------------------------------------------------------------------
2137  *              Support routines for toastable datatypes
2138  *-------------------------------------------------------------------------
2139  */
2140
2141 struct varlena *
2142 pg_detoast_datum(struct varlena * datum)
2143 {
2144         if (VARATT_IS_EXTENDED(datum))
2145                 return heap_tuple_untoast_attr(datum);
2146         else
2147                 return datum;
2148 }
2149
2150 struct varlena *
2151 pg_detoast_datum_copy(struct varlena * datum)
2152 {
2153         if (VARATT_IS_EXTENDED(datum))
2154                 return heap_tuple_untoast_attr(datum);
2155         else
2156         {
2157                 /* Make a modifiable copy of the varlena object */
2158                 Size            len = VARSIZE(datum);
2159                 struct varlena *result = (struct varlena *) palloc(len);
2160
2161                 memcpy(result, datum, len);
2162                 return result;
2163         }
2164 }
2165
2166 struct varlena *
2167 pg_detoast_datum_slice(struct varlena * datum, int32 first, int32 count)
2168 {
2169         /* Only get the specified portion from the toast rel */
2170         return heap_tuple_untoast_attr_slice(datum, first, count);
2171 }
2172
2173 struct varlena *
2174 pg_detoast_datum_packed(struct varlena * datum)
2175 {
2176         if (VARATT_IS_COMPRESSED(datum) || VARATT_IS_EXTERNAL(datum))
2177                 return heap_tuple_untoast_attr(datum);
2178         else
2179                 return datum;
2180 }
2181
2182 /*-------------------------------------------------------------------------
2183  *              Support routines for extracting info from fn_expr parse tree
2184  *
2185  * These are needed by polymorphic functions, which accept multiple possible
2186  * input types and need help from the parser to know what they've got.
2187  * Also, some functions might be interested in whether a parameter is constant.
2188  * Functions taking VARIADIC ANY also need to know about the VARIADIC keyword.
2189  *-------------------------------------------------------------------------
2190  */
2191
2192 /*
2193  * Get the actual type OID of the function return type
2194  *
2195  * Returns InvalidOid if information is not available
2196  */
2197 Oid
2198 get_fn_expr_rettype(FmgrInfo *flinfo)
2199 {
2200         Node       *expr;
2201
2202         /*
2203          * can't return anything useful if we have no FmgrInfo or if its fn_expr
2204          * node has not been initialized
2205          */
2206         if (!flinfo || !flinfo->fn_expr)
2207                 return InvalidOid;
2208
2209         expr = flinfo->fn_expr;
2210
2211         return exprType(expr);
2212 }
2213
2214 /*
2215  * Get the actual type OID of a specific function argument (counting from 0)
2216  *
2217  * Returns InvalidOid if information is not available
2218  */
2219 Oid
2220 get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
2221 {
2222         /*
2223          * can't return anything useful if we have no FmgrInfo or if its fn_expr
2224          * node has not been initialized
2225          */
2226         if (!flinfo || !flinfo->fn_expr)
2227                 return InvalidOid;
2228
2229         return get_call_expr_argtype(flinfo->fn_expr, argnum);
2230 }
2231
2232 /*
2233  * Get the actual type OID of a specific function argument (counting from 0),
2234  * but working from the calling expression tree instead of FmgrInfo
2235  *
2236  * Returns InvalidOid if information is not available
2237  */
2238 Oid
2239 get_call_expr_argtype(Node *expr, int argnum)
2240 {
2241         List       *args;
2242         Oid                     argtype;
2243
2244         if (expr == NULL)
2245                 return InvalidOid;
2246
2247         if (IsA(expr, FuncExpr))
2248                 args = ((FuncExpr *) expr)->args;
2249         else if (IsA(expr, OpExpr))
2250                 args = ((OpExpr *) expr)->args;
2251         else if (IsA(expr, DistinctExpr))
2252                 args = ((DistinctExpr *) expr)->args;
2253         else if (IsA(expr, ScalarArrayOpExpr))
2254                 args = ((ScalarArrayOpExpr *) expr)->args;
2255         else if (IsA(expr, ArrayCoerceExpr))
2256                 args = list_make1(((ArrayCoerceExpr *) expr)->arg);
2257         else if (IsA(expr, NullIfExpr))
2258                 args = ((NullIfExpr *) expr)->args;
2259         else if (IsA(expr, WindowFunc))
2260                 args = ((WindowFunc *) expr)->args;
2261         else
2262                 return InvalidOid;
2263
2264         if (argnum < 0 || argnum >= list_length(args))
2265                 return InvalidOid;
2266
2267         argtype = exprType((Node *) list_nth(args, argnum));
2268
2269         /*
2270          * special hack for ScalarArrayOpExpr and ArrayCoerceExpr: what the
2271          * underlying function will actually get passed is the element type of the
2272          * array.
2273          */
2274         if (IsA(expr, ScalarArrayOpExpr) &&
2275                 argnum == 1)
2276                 argtype = get_base_element_type(argtype);
2277         else if (IsA(expr, ArrayCoerceExpr) &&
2278                          argnum == 0)
2279                 argtype = get_base_element_type(argtype);
2280
2281         return argtype;
2282 }
2283
2284 /*
2285  * Find out whether a specific function argument is constant for the
2286  * duration of a query
2287  *
2288  * Returns false if information is not available
2289  */
2290 bool
2291 get_fn_expr_arg_stable(FmgrInfo *flinfo, int argnum)
2292 {
2293         /*
2294          * can't return anything useful if we have no FmgrInfo or if its fn_expr
2295          * node has not been initialized
2296          */
2297         if (!flinfo || !flinfo->fn_expr)
2298                 return false;
2299
2300         return get_call_expr_arg_stable(flinfo->fn_expr, argnum);
2301 }
2302
2303 /*
2304  * Find out whether a specific function argument is constant for the
2305  * duration of a query, but working from the calling expression tree
2306  *
2307  * Returns false if information is not available
2308  */
2309 bool
2310 get_call_expr_arg_stable(Node *expr, int argnum)
2311 {
2312         List       *args;
2313         Node       *arg;
2314
2315         if (expr == NULL)
2316                 return false;
2317
2318         if (IsA(expr, FuncExpr))
2319                 args = ((FuncExpr *) expr)->args;
2320         else if (IsA(expr, OpExpr))
2321                 args = ((OpExpr *) expr)->args;
2322         else if (IsA(expr, DistinctExpr))
2323                 args = ((DistinctExpr *) expr)->args;
2324         else if (IsA(expr, ScalarArrayOpExpr))
2325                 args = ((ScalarArrayOpExpr *) expr)->args;
2326         else if (IsA(expr, ArrayCoerceExpr))
2327                 args = list_make1(((ArrayCoerceExpr *) expr)->arg);
2328         else if (IsA(expr, NullIfExpr))
2329                 args = ((NullIfExpr *) expr)->args;
2330         else if (IsA(expr, WindowFunc))
2331                 args = ((WindowFunc *) expr)->args;
2332         else
2333                 return false;
2334
2335         if (argnum < 0 || argnum >= list_length(args))
2336                 return false;
2337
2338         arg = (Node *) list_nth(args, argnum);
2339
2340         /*
2341          * Either a true Const or an external Param will have a value that doesn't
2342          * change during the execution of the query.  In future we might want to
2343          * consider other cases too, e.g. now().
2344          */
2345         if (IsA(arg, Const))
2346                 return true;
2347         if (IsA(arg, Param) &&
2348                 ((Param *) arg)->paramkind == PARAM_EXTERN)
2349                 return true;
2350
2351         return false;
2352 }
2353
2354 /*
2355  * Get the VARIADIC flag from the function invocation
2356  *
2357  * Returns false (the default assumption) if information is not available
2358  *
2359  * Note this is generally only of interest to VARIADIC ANY functions
2360  */
2361 bool
2362 get_fn_expr_variadic(FmgrInfo *flinfo)
2363 {
2364         Node       *expr;
2365
2366         /*
2367          * can't return anything useful if we have no FmgrInfo or if its fn_expr
2368          * node has not been initialized
2369          */
2370         if (!flinfo || !flinfo->fn_expr)
2371                 return false;
2372
2373         expr = flinfo->fn_expr;
2374
2375         if (IsA(expr, FuncExpr))
2376                 return ((FuncExpr *) expr)->funcvariadic;
2377         else
2378                 return false;
2379 }
2380
2381 /*-------------------------------------------------------------------------
2382  *              Support routines for procedural language implementations
2383  *-------------------------------------------------------------------------
2384  */
2385
2386 /*
2387  * Verify that a validator is actually associated with the language of a
2388  * particular function and that the user has access to both the language and
2389  * the function.  All validators should call this before doing anything
2390  * substantial.  Doing so ensures a user cannot achieve anything with explicit
2391  * calls to validators that he could not achieve with CREATE FUNCTION or by
2392  * simply calling an existing function.
2393  *
2394  * When this function returns false, callers should skip all validation work
2395  * and call PG_RETURN_VOID().  This never happens at present; it is reserved
2396  * for future expansion.
2397  *
2398  * In particular, checking that the validator corresponds to the function's
2399  * language allows untrusted language validators to assume they process only
2400  * superuser-chosen source code.  (Untrusted language call handlers, by
2401  * definition, do assume that.)  A user lacking the USAGE language privilege
2402  * would be unable to reach the validator through CREATE FUNCTION, so we check
2403  * that to block explicit calls as well.  Checking the EXECUTE privilege on
2404  * the function is often superfluous, because most users can clone the
2405  * function to get an executable copy.  It is meaningful against users with no
2406  * database TEMP right and no permanent schema CREATE right, thereby unable to
2407  * create any function.  Also, if the function tracks persistent state by
2408  * function OID or name, validating the original function might permit more
2409  * mischief than creating and validating a clone thereof.
2410  */
2411 bool
2412 CheckFunctionValidatorAccess(Oid validatorOid, Oid functionOid)
2413 {
2414         HeapTuple       procTup;
2415         HeapTuple       langTup;
2416         Form_pg_proc procStruct;
2417         Form_pg_language langStruct;
2418         AclResult       aclresult;
2419
2420         /*
2421          * Get the function's pg_proc entry.  Throw a user-facing error for bad
2422          * OID, because validators can be called with user-specified OIDs.
2423          */
2424         procTup = SearchSysCache1(PROCOID, ObjectIdGetDatum(functionOid));
2425         if (!HeapTupleIsValid(procTup))
2426                 ereport(ERROR,
2427                                 (errcode(ERRCODE_UNDEFINED_FUNCTION),
2428                                  errmsg("function with OID %u does not exist", functionOid)));
2429         procStruct = (Form_pg_proc) GETSTRUCT(procTup);
2430
2431         /*
2432          * Fetch pg_language entry to know if this is the correct validation
2433          * function for that pg_proc entry.
2434          */
2435         langTup = SearchSysCache1(LANGOID, ObjectIdGetDatum(procStruct->prolang));
2436         if (!HeapTupleIsValid(langTup))
2437                 elog(ERROR, "cache lookup failed for language %u", procStruct->prolang);
2438         langStruct = (Form_pg_language) GETSTRUCT(langTup);
2439
2440         if (langStruct->lanvalidator != validatorOid)
2441                 ereport(ERROR,
2442                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2443                                  errmsg("language validation function %u called for language %u instead of %u",
2444                                                 validatorOid, procStruct->prolang,
2445                                                 langStruct->lanvalidator)));
2446
2447         /* first validate that we have permissions to use the language */
2448         aclresult = pg_language_aclcheck(procStruct->prolang, GetUserId(),
2449                                                                          ACL_USAGE);
2450         if (aclresult != ACLCHECK_OK)
2451                 aclcheck_error(aclresult, ACL_KIND_LANGUAGE,
2452                                            NameStr(langStruct->lanname));
2453
2454         /*
2455          * Check whether we are allowed to execute the function itself. If we can
2456          * execute it, there should be no possible side-effect of
2457          * compiling/validation that execution can't have.
2458          */
2459         aclresult = pg_proc_aclcheck(functionOid, GetUserId(), ACL_EXECUTE);
2460         if (aclresult != ACLCHECK_OK)
2461                 aclcheck_error(aclresult, ACL_KIND_PROC, NameStr(procStruct->proname));
2462
2463         ReleaseSysCache(procTup);
2464         ReleaseSysCache(langTup);
2465
2466         return true;
2467 }