Avoid crash in estimate_array_length with null root pointer.
[pgsql.git] / src / backend / utils / misc / guc.c
blob99854be4394fb502b64936e3577e7bf65ddbb32c
1 /*--------------------------------------------------------------------
2 * guc.c
4 * Support for grand unified configuration scheme, including SET
5 * command, configuration file, and command line options.
7 * This file contains the generic option processing infrastructure.
8 * guc_funcs.c contains SQL-level functionality, including SET/SHOW
9 * commands and various system-administration SQL functions.
10 * guc_tables.c contains the arrays that define all the built-in
11 * GUC variables. Code that implements variable-specific behavior
12 * is scattered around the system in check, assign, and show hooks.
14 * See src/backend/utils/misc/README for more information.
17 * Copyright (c) 2000-2024, PostgreSQL Global Development Group
18 * Written by Peter Eisentraut <peter_e@gmx.net>.
20 * IDENTIFICATION
21 * src/backend/utils/misc/guc.c
23 *--------------------------------------------------------------------
25 #include "postgres.h"
27 #include <limits.h>
28 #include <math.h>
29 #include <sys/stat.h>
30 #include <unistd.h>
32 #include "access/xact.h"
33 #include "access/xlog.h"
34 #include "catalog/objectaccess.h"
35 #include "catalog/pg_authid.h"
36 #include "catalog/pg_parameter_acl.h"
37 #include "guc_internal.h"
38 #include "libpq/pqformat.h"
39 #include "libpq/protocol.h"
40 #include "miscadmin.h"
41 #include "parser/scansup.h"
42 #include "port/pg_bitutils.h"
43 #include "storage/fd.h"
44 #include "storage/lwlock.h"
45 #include "storage/shmem.h"
46 #include "tcop/tcopprot.h"
47 #include "utils/acl.h"
48 #include "utils/builtins.h"
49 #include "utils/conffiles.h"
50 #include "utils/guc_tables.h"
51 #include "utils/memutils.h"
52 #include "utils/timestamp.h"
55 #define CONFIG_FILENAME "postgresql.conf"
56 #define HBA_FILENAME "pg_hba.conf"
57 #define IDENT_FILENAME "pg_ident.conf"
59 #ifdef EXEC_BACKEND
60 #define CONFIG_EXEC_PARAMS "global/config_exec_params"
61 #define CONFIG_EXEC_PARAMS_NEW "global/config_exec_params.new"
62 #endif
65 * Precision with which REAL type guc values are to be printed for GUC
66 * serialization.
68 #define REALTYPE_PRECISION 17
71 * Safe search path when executing code as the table owner, such as during
72 * maintenance operations.
74 #define GUC_SAFE_SEARCH_PATH "pg_catalog, pg_temp"
76 static int GUC_check_errcode_value;
78 static List *reserved_class_prefix = NIL;
80 /* global variables for check hook support */
81 char *GUC_check_errmsg_string;
82 char *GUC_check_errdetail_string;
83 char *GUC_check_errhint_string;
85 /* Kluge: for speed, we examine this GUC variable's value directly */
86 extern bool in_hot_standby_guc;
90 * Unit conversion tables.
92 * There are two tables, one for memory units, and another for time units.
93 * For each supported conversion from one unit to another, we have an entry
94 * in the table.
96 * To keep things simple, and to avoid possible roundoff error,
97 * conversions are never chained. There needs to be a direct conversion
98 * between all units (of the same type).
100 * The conversions for each base unit must be kept in order from greatest to
101 * smallest human-friendly unit; convert_xxx_from_base_unit() rely on that.
102 * (The order of the base-unit groups does not matter.)
104 #define MAX_UNIT_LEN 3 /* length of longest recognized unit string */
106 typedef struct
108 char unit[MAX_UNIT_LEN + 1]; /* unit, as a string, like "kB" or
109 * "min" */
110 int base_unit; /* GUC_UNIT_XXX */
111 double multiplier; /* Factor for converting unit -> base_unit */
112 } unit_conversion;
114 /* Ensure that the constants in the tables don't overflow or underflow */
115 #if BLCKSZ < 1024 || BLCKSZ > (1024*1024)
116 #error BLCKSZ must be between 1KB and 1MB
117 #endif
118 #if XLOG_BLCKSZ < 1024 || XLOG_BLCKSZ > (1024*1024)
119 #error XLOG_BLCKSZ must be between 1KB and 1MB
120 #endif
122 static const char *const memory_units_hint = gettext_noop("Valid units for this parameter are \"B\", \"kB\", \"MB\", \"GB\", and \"TB\".");
124 static const unit_conversion memory_unit_conversion_table[] =
126 {"TB", GUC_UNIT_BYTE, 1024.0 * 1024.0 * 1024.0 * 1024.0},
127 {"GB", GUC_UNIT_BYTE, 1024.0 * 1024.0 * 1024.0},
128 {"MB", GUC_UNIT_BYTE, 1024.0 * 1024.0},
129 {"kB", GUC_UNIT_BYTE, 1024.0},
130 {"B", GUC_UNIT_BYTE, 1.0},
132 {"TB", GUC_UNIT_KB, 1024.0 * 1024.0 * 1024.0},
133 {"GB", GUC_UNIT_KB, 1024.0 * 1024.0},
134 {"MB", GUC_UNIT_KB, 1024.0},
135 {"kB", GUC_UNIT_KB, 1.0},
136 {"B", GUC_UNIT_KB, 1.0 / 1024.0},
138 {"TB", GUC_UNIT_MB, 1024.0 * 1024.0},
139 {"GB", GUC_UNIT_MB, 1024.0},
140 {"MB", GUC_UNIT_MB, 1.0},
141 {"kB", GUC_UNIT_MB, 1.0 / 1024.0},
142 {"B", GUC_UNIT_MB, 1.0 / (1024.0 * 1024.0)},
144 {"TB", GUC_UNIT_BLOCKS, (1024.0 * 1024.0 * 1024.0) / (BLCKSZ / 1024)},
145 {"GB", GUC_UNIT_BLOCKS, (1024.0 * 1024.0) / (BLCKSZ / 1024)},
146 {"MB", GUC_UNIT_BLOCKS, 1024.0 / (BLCKSZ / 1024)},
147 {"kB", GUC_UNIT_BLOCKS, 1.0 / (BLCKSZ / 1024)},
148 {"B", GUC_UNIT_BLOCKS, 1.0 / BLCKSZ},
150 {"TB", GUC_UNIT_XBLOCKS, (1024.0 * 1024.0 * 1024.0) / (XLOG_BLCKSZ / 1024)},
151 {"GB", GUC_UNIT_XBLOCKS, (1024.0 * 1024.0) / (XLOG_BLCKSZ / 1024)},
152 {"MB", GUC_UNIT_XBLOCKS, 1024.0 / (XLOG_BLCKSZ / 1024)},
153 {"kB", GUC_UNIT_XBLOCKS, 1.0 / (XLOG_BLCKSZ / 1024)},
154 {"B", GUC_UNIT_XBLOCKS, 1.0 / XLOG_BLCKSZ},
156 {""} /* end of table marker */
159 static const char *const time_units_hint = gettext_noop("Valid units for this parameter are \"us\", \"ms\", \"s\", \"min\", \"h\", and \"d\".");
161 static const unit_conversion time_unit_conversion_table[] =
163 {"d", GUC_UNIT_MS, 1000 * 60 * 60 * 24},
164 {"h", GUC_UNIT_MS, 1000 * 60 * 60},
165 {"min", GUC_UNIT_MS, 1000 * 60},
166 {"s", GUC_UNIT_MS, 1000},
167 {"ms", GUC_UNIT_MS, 1},
168 {"us", GUC_UNIT_MS, 1.0 / 1000},
170 {"d", GUC_UNIT_S, 60 * 60 * 24},
171 {"h", GUC_UNIT_S, 60 * 60},
172 {"min", GUC_UNIT_S, 60},
173 {"s", GUC_UNIT_S, 1},
174 {"ms", GUC_UNIT_S, 1.0 / 1000},
175 {"us", GUC_UNIT_S, 1.0 / (1000 * 1000)},
177 {"d", GUC_UNIT_MIN, 60 * 24},
178 {"h", GUC_UNIT_MIN, 60},
179 {"min", GUC_UNIT_MIN, 1},
180 {"s", GUC_UNIT_MIN, 1.0 / 60},
181 {"ms", GUC_UNIT_MIN, 1.0 / (1000 * 60)},
182 {"us", GUC_UNIT_MIN, 1.0 / (1000 * 1000 * 60)},
184 {""} /* end of table marker */
188 * To allow continued support of obsolete names for GUC variables, we apply
189 * the following mappings to any unrecognized name. Note that an old name
190 * should be mapped to a new one only if the new variable has very similar
191 * semantics to the old.
193 static const char *const map_old_guc_names[] = {
194 "sort_mem", "work_mem",
195 "vacuum_mem", "maintenance_work_mem",
196 NULL
200 /* Memory context holding all GUC-related data */
201 static MemoryContext GUCMemoryContext;
204 * We use a dynahash table to look up GUCs by name, or to iterate through
205 * all the GUCs. The gucname field is redundant with gucvar->name, but
206 * dynahash makes it too painful to not store the hash key separately.
208 typedef struct
210 const char *gucname; /* hash key */
211 struct config_generic *gucvar; /* -> GUC's defining structure */
212 } GUCHashEntry;
214 static HTAB *guc_hashtab; /* entries are GUCHashEntrys */
217 * In addition to the hash table, variables having certain properties are
218 * linked into these lists, so that we can find them without scanning the
219 * whole hash table. In most applications, only a small fraction of the
220 * GUCs appear in these lists at any given time. The usage of the stack
221 * and report lists is stylized enough that they can be slists, but the
222 * nondef list has to be a dlist to avoid O(N) deletes in common cases.
224 static dlist_head guc_nondef_list; /* list of variables that have source
225 * different from PGC_S_DEFAULT */
226 static slist_head guc_stack_list; /* list of variables that have non-NULL
227 * stack */
228 static slist_head guc_report_list; /* list of variables that have the
229 * GUC_NEEDS_REPORT bit set in status */
231 static bool reporting_enabled; /* true to enable GUC_REPORT */
233 static int GUCNestLevel = 0; /* 1 when in main transaction */
236 static int guc_var_compare(const void *a, const void *b);
237 static uint32 guc_name_hash(const void *key, Size keysize);
238 static int guc_name_match(const void *key1, const void *key2, Size keysize);
239 static void InitializeGUCOptionsFromEnvironment(void);
240 static void InitializeOneGUCOption(struct config_generic *gconf);
241 static void RemoveGUCFromLists(struct config_generic *gconf);
242 static void set_guc_source(struct config_generic *gconf, GucSource newsource);
243 static void pg_timezone_abbrev_initialize(void);
244 static void push_old_value(struct config_generic *gconf, GucAction action);
245 static void ReportGUCOption(struct config_generic *record);
246 static void set_config_sourcefile(const char *name, char *sourcefile,
247 int sourceline);
248 static void reapply_stacked_values(struct config_generic *variable,
249 struct config_string *pHolder,
250 GucStack *stack,
251 const char *curvalue,
252 GucContext curscontext, GucSource cursource,
253 Oid cursrole);
254 static bool validate_option_array_item(const char *name, const char *value,
255 bool skipIfNoPermissions);
256 static void write_auto_conf_file(int fd, const char *filename, ConfigVariable *head);
257 static void replace_auto_config_value(ConfigVariable **head_p, ConfigVariable **tail_p,
258 const char *name, const char *value);
259 static bool valid_custom_variable_name(const char *name);
260 static bool assignable_custom_variable_name(const char *name, bool skip_errors,
261 int elevel);
262 static void do_serialize(char **destptr, Size *maxbytes,
263 const char *fmt,...) pg_attribute_printf(3, 4);
264 static bool call_bool_check_hook(struct config_bool *conf, bool *newval,
265 void **extra, GucSource source, int elevel);
266 static bool call_int_check_hook(struct config_int *conf, int *newval,
267 void **extra, GucSource source, int elevel);
268 static bool call_real_check_hook(struct config_real *conf, double *newval,
269 void **extra, GucSource source, int elevel);
270 static bool call_string_check_hook(struct config_string *conf, char **newval,
271 void **extra, GucSource source, int elevel);
272 static bool call_enum_check_hook(struct config_enum *conf, int *newval,
273 void **extra, GucSource source, int elevel);
277 * This function handles both actual config file (re)loads and execution of
278 * show_all_file_settings() (i.e., the pg_file_settings view). In the latter
279 * case we don't apply any of the settings, but we make all the usual validity
280 * checks, and we return the ConfigVariable list so that it can be printed out
281 * by show_all_file_settings().
283 ConfigVariable *
284 ProcessConfigFileInternal(GucContext context, bool applySettings, int elevel)
286 bool error = false;
287 bool applying = false;
288 const char *ConfFileWithError;
289 ConfigVariable *item,
290 *head,
291 *tail;
292 HASH_SEQ_STATUS status;
293 GUCHashEntry *hentry;
295 /* Parse the main config file into a list of option names and values */
296 ConfFileWithError = ConfigFileName;
297 head = tail = NULL;
299 if (!ParseConfigFile(ConfigFileName, true,
300 NULL, 0, CONF_FILE_START_DEPTH, elevel,
301 &head, &tail))
303 /* Syntax error(s) detected in the file, so bail out */
304 error = true;
305 goto bail_out;
309 * Parse the PG_AUTOCONF_FILENAME file, if present, after the main file to
310 * replace any parameters set by ALTER SYSTEM command. Because this file
311 * is in the data directory, we can't read it until the DataDir has been
312 * set.
314 if (DataDir)
316 if (!ParseConfigFile(PG_AUTOCONF_FILENAME, false,
317 NULL, 0, CONF_FILE_START_DEPTH, elevel,
318 &head, &tail))
320 /* Syntax error(s) detected in the file, so bail out */
321 error = true;
322 ConfFileWithError = PG_AUTOCONF_FILENAME;
323 goto bail_out;
326 else
329 * If DataDir is not set, the PG_AUTOCONF_FILENAME file cannot be
330 * read. In this case, we don't want to accept any settings but
331 * data_directory from postgresql.conf, because they might be
332 * overwritten with settings in the PG_AUTOCONF_FILENAME file which
333 * will be read later. OTOH, since data_directory isn't allowed in the
334 * PG_AUTOCONF_FILENAME file, it will never be overwritten later.
336 ConfigVariable *newlist = NULL;
339 * Prune all items except the last "data_directory" from the list.
341 for (item = head; item; item = item->next)
343 if (!item->ignore &&
344 strcmp(item->name, "data_directory") == 0)
345 newlist = item;
348 if (newlist)
349 newlist->next = NULL;
350 head = tail = newlist;
353 * Quick exit if data_directory is not present in file.
355 * We need not do any further processing, in particular we don't set
356 * PgReloadTime; that will be set soon by subsequent full loading of
357 * the config file.
359 if (head == NULL)
360 goto bail_out;
364 * Mark all extant GUC variables as not present in the config file. We
365 * need this so that we can tell below which ones have been removed from
366 * the file since we last processed it.
368 hash_seq_init(&status, guc_hashtab);
369 while ((hentry = (GUCHashEntry *) hash_seq_search(&status)) != NULL)
371 struct config_generic *gconf = hentry->gucvar;
373 gconf->status &= ~GUC_IS_IN_FILE;
377 * Check if all the supplied option names are valid, as an additional
378 * quasi-syntactic check on the validity of the config file. It is
379 * important that the postmaster and all backends agree on the results of
380 * this phase, else we will have strange inconsistencies about which
381 * processes accept a config file update and which don't. Hence, unknown
382 * custom variable names have to be accepted without complaint. For the
383 * same reason, we don't attempt to validate the options' values here.
385 * In addition, the GUC_IS_IN_FILE flag is set on each existing GUC
386 * variable mentioned in the file; and we detect duplicate entries in the
387 * file and mark the earlier occurrences as ignorable.
389 for (item = head; item; item = item->next)
391 struct config_generic *record;
393 /* Ignore anything already marked as ignorable */
394 if (item->ignore)
395 continue;
398 * Try to find the variable; but do not create a custom placeholder if
399 * it's not there already.
401 record = find_option(item->name, false, true, elevel);
403 if (record)
405 /* If it's already marked, then this is a duplicate entry */
406 if (record->status & GUC_IS_IN_FILE)
409 * Mark the earlier occurrence(s) as dead/ignorable. We could
410 * avoid the O(N^2) behavior here with some additional state,
411 * but it seems unlikely to be worth the trouble.
413 ConfigVariable *pitem;
415 for (pitem = head; pitem != item; pitem = pitem->next)
417 if (!pitem->ignore &&
418 strcmp(pitem->name, item->name) == 0)
419 pitem->ignore = true;
422 /* Now mark it as present in file */
423 record->status |= GUC_IS_IN_FILE;
425 else if (!valid_custom_variable_name(item->name))
427 /* Invalid non-custom variable, so complain */
428 ereport(elevel,
429 (errcode(ERRCODE_UNDEFINED_OBJECT),
430 errmsg("unrecognized configuration parameter \"%s\" in file \"%s\" line %d",
431 item->name,
432 item->filename, item->sourceline)));
433 item->errmsg = pstrdup("unrecognized configuration parameter");
434 error = true;
435 ConfFileWithError = item->filename;
440 * If we've detected any errors so far, we don't want to risk applying any
441 * changes.
443 if (error)
444 goto bail_out;
446 /* Otherwise, set flag that we're beginning to apply changes */
447 applying = true;
450 * Check for variables having been removed from the config file, and
451 * revert their reset values (and perhaps also effective values) to the
452 * boot-time defaults. If such a variable can't be changed after startup,
453 * report that and continue.
455 hash_seq_init(&status, guc_hashtab);
456 while ((hentry = (GUCHashEntry *) hash_seq_search(&status)) != NULL)
458 struct config_generic *gconf = hentry->gucvar;
459 GucStack *stack;
461 if (gconf->reset_source != PGC_S_FILE ||
462 (gconf->status & GUC_IS_IN_FILE))
463 continue;
464 if (gconf->context < PGC_SIGHUP)
466 /* The removal can't be effective without a restart */
467 gconf->status |= GUC_PENDING_RESTART;
468 ereport(elevel,
469 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
470 errmsg("parameter \"%s\" cannot be changed without restarting the server",
471 gconf->name)));
472 record_config_file_error(psprintf("parameter \"%s\" cannot be changed without restarting the server",
473 gconf->name),
474 NULL, 0,
475 &head, &tail);
476 error = true;
477 continue;
480 /* No more to do if we're just doing show_all_file_settings() */
481 if (!applySettings)
482 continue;
485 * Reset any "file" sources to "default", else set_config_option will
486 * not override those settings.
488 if (gconf->reset_source == PGC_S_FILE)
489 gconf->reset_source = PGC_S_DEFAULT;
490 if (gconf->source == PGC_S_FILE)
491 set_guc_source(gconf, PGC_S_DEFAULT);
492 for (stack = gconf->stack; stack; stack = stack->prev)
494 if (stack->source == PGC_S_FILE)
495 stack->source = PGC_S_DEFAULT;
498 /* Now we can re-apply the wired-in default (i.e., the boot_val) */
499 if (set_config_option(gconf->name, NULL,
500 context, PGC_S_DEFAULT,
501 GUC_ACTION_SET, true, 0, false) > 0)
503 /* Log the change if appropriate */
504 if (context == PGC_SIGHUP)
505 ereport(elevel,
506 (errmsg("parameter \"%s\" removed from configuration file, reset to default",
507 gconf->name)));
512 * Restore any variables determined by environment variables or
513 * dynamically-computed defaults. This is a no-op except in the case
514 * where one of these had been in the config file and is now removed.
516 * In particular, we *must not* do this during the postmaster's initial
517 * loading of the file, since the timezone functions in particular should
518 * be run only after initialization is complete.
520 * XXX this is an unmaintainable crock, because we have to know how to set
521 * (or at least what to call to set) every non-PGC_INTERNAL variable that
522 * could potentially have PGC_S_DYNAMIC_DEFAULT or PGC_S_ENV_VAR source.
524 if (context == PGC_SIGHUP && applySettings)
526 InitializeGUCOptionsFromEnvironment();
527 pg_timezone_abbrev_initialize();
528 /* this selects SQL_ASCII in processes not connected to a database */
529 SetConfigOption("client_encoding", GetDatabaseEncodingName(),
530 PGC_BACKEND, PGC_S_DYNAMIC_DEFAULT);
534 * Now apply the values from the config file.
536 for (item = head; item; item = item->next)
538 char *pre_value = NULL;
539 int scres;
541 /* Ignore anything marked as ignorable */
542 if (item->ignore)
543 continue;
545 /* In SIGHUP cases in the postmaster, we want to report changes */
546 if (context == PGC_SIGHUP && applySettings && !IsUnderPostmaster)
548 const char *preval = GetConfigOption(item->name, true, false);
550 /* If option doesn't exist yet or is NULL, treat as empty string */
551 if (!preval)
552 preval = "";
553 /* must dup, else might have dangling pointer below */
554 pre_value = pstrdup(preval);
557 scres = set_config_option(item->name, item->value,
558 context, PGC_S_FILE,
559 GUC_ACTION_SET, applySettings, 0, false);
560 if (scres > 0)
562 /* variable was updated, so log the change if appropriate */
563 if (pre_value)
565 const char *post_value = GetConfigOption(item->name, true, false);
567 if (!post_value)
568 post_value = "";
569 if (strcmp(pre_value, post_value) != 0)
570 ereport(elevel,
571 (errmsg("parameter \"%s\" changed to \"%s\"",
572 item->name, item->value)));
574 item->applied = true;
576 else if (scres == 0)
578 error = true;
579 item->errmsg = pstrdup("setting could not be applied");
580 ConfFileWithError = item->filename;
582 else
584 /* no error, but variable's active value was not changed */
585 item->applied = true;
589 * We should update source location unless there was an error, since
590 * even if the active value didn't change, the reset value might have.
591 * (In the postmaster, there won't be a difference, but it does matter
592 * in backends.)
594 if (scres != 0 && applySettings)
595 set_config_sourcefile(item->name, item->filename,
596 item->sourceline);
598 if (pre_value)
599 pfree(pre_value);
602 /* Remember when we last successfully loaded the config file. */
603 if (applySettings)
604 PgReloadTime = GetCurrentTimestamp();
606 bail_out:
607 if (error && applySettings)
609 /* During postmaster startup, any error is fatal */
610 if (context == PGC_POSTMASTER)
611 ereport(ERROR,
612 (errcode(ERRCODE_CONFIG_FILE_ERROR),
613 errmsg("configuration file \"%s\" contains errors",
614 ConfFileWithError)));
615 else if (applying)
616 ereport(elevel,
617 (errcode(ERRCODE_CONFIG_FILE_ERROR),
618 errmsg("configuration file \"%s\" contains errors; unaffected changes were applied",
619 ConfFileWithError)));
620 else
621 ereport(elevel,
622 (errcode(ERRCODE_CONFIG_FILE_ERROR),
623 errmsg("configuration file \"%s\" contains errors; no changes were applied",
624 ConfFileWithError)));
627 /* Successful or otherwise, return the collected data list */
628 return head;
633 * Some infrastructure for GUC-related memory allocation
635 * These functions are generally modeled on libc's malloc/realloc/etc,
636 * but any OOM issue is reported at the specified elevel.
637 * (Thus, control returns only if that's less than ERROR.)
639 void *
640 guc_malloc(int elevel, size_t size)
642 void *data;
644 data = MemoryContextAllocExtended(GUCMemoryContext, size,
645 MCXT_ALLOC_NO_OOM);
646 if (unlikely(data == NULL))
647 ereport(elevel,
648 (errcode(ERRCODE_OUT_OF_MEMORY),
649 errmsg("out of memory")));
650 return data;
653 void *
654 guc_realloc(int elevel, void *old, size_t size)
656 void *data;
658 if (old != NULL)
660 /* This is to help catch old code that malloc's GUC data. */
661 Assert(GetMemoryChunkContext(old) == GUCMemoryContext);
662 data = repalloc_extended(old, size,
663 MCXT_ALLOC_NO_OOM);
665 else
667 /* Like realloc(3), but not like repalloc(), we allow old == NULL. */
668 data = MemoryContextAllocExtended(GUCMemoryContext, size,
669 MCXT_ALLOC_NO_OOM);
671 if (unlikely(data == NULL))
672 ereport(elevel,
673 (errcode(ERRCODE_OUT_OF_MEMORY),
674 errmsg("out of memory")));
675 return data;
678 char *
679 guc_strdup(int elevel, const char *src)
681 char *data;
682 size_t len = strlen(src) + 1;
684 data = guc_malloc(elevel, len);
685 if (likely(data != NULL))
686 memcpy(data, src, len);
687 return data;
690 void
691 guc_free(void *ptr)
694 * Historically, GUC-related code has relied heavily on the ability to do
695 * free(NULL), so we allow that here even though pfree() doesn't.
697 if (ptr != NULL)
699 /* This is to help catch old code that malloc's GUC data. */
700 Assert(GetMemoryChunkContext(ptr) == GUCMemoryContext);
701 pfree(ptr);
707 * Detect whether strval is referenced anywhere in a GUC string item
709 static bool
710 string_field_used(struct config_string *conf, char *strval)
712 GucStack *stack;
714 if (strval == *(conf->variable) ||
715 strval == conf->reset_val ||
716 strval == conf->boot_val)
717 return true;
718 for (stack = conf->gen.stack; stack; stack = stack->prev)
720 if (strval == stack->prior.val.stringval ||
721 strval == stack->masked.val.stringval)
722 return true;
724 return false;
728 * Support for assigning to a field of a string GUC item. Free the prior
729 * value if it's not referenced anywhere else in the item (including stacked
730 * states).
732 static void
733 set_string_field(struct config_string *conf, char **field, char *newval)
735 char *oldval = *field;
737 /* Do the assignment */
738 *field = newval;
740 /* Free old value if it's not NULL and isn't referenced anymore */
741 if (oldval && !string_field_used(conf, oldval))
742 guc_free(oldval);
746 * Detect whether an "extra" struct is referenced anywhere in a GUC item
748 static bool
749 extra_field_used(struct config_generic *gconf, void *extra)
751 GucStack *stack;
753 if (extra == gconf->extra)
754 return true;
755 switch (gconf->vartype)
757 case PGC_BOOL:
758 if (extra == ((struct config_bool *) gconf)->reset_extra)
759 return true;
760 break;
761 case PGC_INT:
762 if (extra == ((struct config_int *) gconf)->reset_extra)
763 return true;
764 break;
765 case PGC_REAL:
766 if (extra == ((struct config_real *) gconf)->reset_extra)
767 return true;
768 break;
769 case PGC_STRING:
770 if (extra == ((struct config_string *) gconf)->reset_extra)
771 return true;
772 break;
773 case PGC_ENUM:
774 if (extra == ((struct config_enum *) gconf)->reset_extra)
775 return true;
776 break;
778 for (stack = gconf->stack; stack; stack = stack->prev)
780 if (extra == stack->prior.extra ||
781 extra == stack->masked.extra)
782 return true;
785 return false;
789 * Support for assigning to an "extra" field of a GUC item. Free the prior
790 * value if it's not referenced anywhere else in the item (including stacked
791 * states).
793 static void
794 set_extra_field(struct config_generic *gconf, void **field, void *newval)
796 void *oldval = *field;
798 /* Do the assignment */
799 *field = newval;
801 /* Free old value if it's not NULL and isn't referenced anymore */
802 if (oldval && !extra_field_used(gconf, oldval))
803 guc_free(oldval);
807 * Support for copying a variable's active value into a stack entry.
808 * The "extra" field associated with the active value is copied, too.
810 * NB: be sure stringval and extra fields of a new stack entry are
811 * initialized to NULL before this is used, else we'll try to guc_free() them.
813 static void
814 set_stack_value(struct config_generic *gconf, config_var_value *val)
816 switch (gconf->vartype)
818 case PGC_BOOL:
819 val->val.boolval =
820 *((struct config_bool *) gconf)->variable;
821 break;
822 case PGC_INT:
823 val->val.intval =
824 *((struct config_int *) gconf)->variable;
825 break;
826 case PGC_REAL:
827 val->val.realval =
828 *((struct config_real *) gconf)->variable;
829 break;
830 case PGC_STRING:
831 set_string_field((struct config_string *) gconf,
832 &(val->val.stringval),
833 *((struct config_string *) gconf)->variable);
834 break;
835 case PGC_ENUM:
836 val->val.enumval =
837 *((struct config_enum *) gconf)->variable;
838 break;
840 set_extra_field(gconf, &(val->extra), gconf->extra);
844 * Support for discarding a no-longer-needed value in a stack entry.
845 * The "extra" field associated with the stack entry is cleared, too.
847 static void
848 discard_stack_value(struct config_generic *gconf, config_var_value *val)
850 switch (gconf->vartype)
852 case PGC_BOOL:
853 case PGC_INT:
854 case PGC_REAL:
855 case PGC_ENUM:
856 /* no need to do anything */
857 break;
858 case PGC_STRING:
859 set_string_field((struct config_string *) gconf,
860 &(val->val.stringval),
861 NULL);
862 break;
864 set_extra_field(gconf, &(val->extra), NULL);
869 * Fetch a palloc'd, sorted array of GUC struct pointers
871 * The array length is returned into *num_vars.
873 struct config_generic **
874 get_guc_variables(int *num_vars)
876 struct config_generic **result;
877 HASH_SEQ_STATUS status;
878 GUCHashEntry *hentry;
879 int i;
881 *num_vars = hash_get_num_entries(guc_hashtab);
882 result = palloc(sizeof(struct config_generic *) * *num_vars);
884 /* Extract pointers from the hash table */
885 i = 0;
886 hash_seq_init(&status, guc_hashtab);
887 while ((hentry = (GUCHashEntry *) hash_seq_search(&status)) != NULL)
888 result[i++] = hentry->gucvar;
889 Assert(i == *num_vars);
891 /* Sort by name */
892 qsort(result, *num_vars,
893 sizeof(struct config_generic *), guc_var_compare);
895 return result;
900 * Build the GUC hash table. This is split out so that help_config.c can
901 * extract all the variables without running all of InitializeGUCOptions.
902 * It's not meant for use anyplace else.
904 void
905 build_guc_variables(void)
907 int size_vars;
908 int num_vars = 0;
909 HASHCTL hash_ctl;
910 GUCHashEntry *hentry;
911 bool found;
912 int i;
915 * Create the memory context that will hold all GUC-related data.
917 Assert(GUCMemoryContext == NULL);
918 GUCMemoryContext = AllocSetContextCreate(TopMemoryContext,
919 "GUCMemoryContext",
920 ALLOCSET_DEFAULT_SIZES);
923 * Count all the built-in variables, and set their vartypes correctly.
925 for (i = 0; ConfigureNamesBool[i].gen.name; i++)
927 struct config_bool *conf = &ConfigureNamesBool[i];
929 /* Rather than requiring vartype to be filled in by hand, do this: */
930 conf->gen.vartype = PGC_BOOL;
931 num_vars++;
934 for (i = 0; ConfigureNamesInt[i].gen.name; i++)
936 struct config_int *conf = &ConfigureNamesInt[i];
938 conf->gen.vartype = PGC_INT;
939 num_vars++;
942 for (i = 0; ConfigureNamesReal[i].gen.name; i++)
944 struct config_real *conf = &ConfigureNamesReal[i];
946 conf->gen.vartype = PGC_REAL;
947 num_vars++;
950 for (i = 0; ConfigureNamesString[i].gen.name; i++)
952 struct config_string *conf = &ConfigureNamesString[i];
954 conf->gen.vartype = PGC_STRING;
955 num_vars++;
958 for (i = 0; ConfigureNamesEnum[i].gen.name; i++)
960 struct config_enum *conf = &ConfigureNamesEnum[i];
962 conf->gen.vartype = PGC_ENUM;
963 num_vars++;
967 * Create hash table with 20% slack
969 size_vars = num_vars + num_vars / 4;
971 hash_ctl.keysize = sizeof(char *);
972 hash_ctl.entrysize = sizeof(GUCHashEntry);
973 hash_ctl.hash = guc_name_hash;
974 hash_ctl.match = guc_name_match;
975 hash_ctl.hcxt = GUCMemoryContext;
976 guc_hashtab = hash_create("GUC hash table",
977 size_vars,
978 &hash_ctl,
979 HASH_ELEM | HASH_FUNCTION | HASH_COMPARE | HASH_CONTEXT);
981 for (i = 0; ConfigureNamesBool[i].gen.name; i++)
983 struct config_generic *gucvar = &ConfigureNamesBool[i].gen;
985 hentry = (GUCHashEntry *) hash_search(guc_hashtab,
986 &gucvar->name,
987 HASH_ENTER,
988 &found);
989 Assert(!found);
990 hentry->gucvar = gucvar;
993 for (i = 0; ConfigureNamesInt[i].gen.name; i++)
995 struct config_generic *gucvar = &ConfigureNamesInt[i].gen;
997 hentry = (GUCHashEntry *) hash_search(guc_hashtab,
998 &gucvar->name,
999 HASH_ENTER,
1000 &found);
1001 Assert(!found);
1002 hentry->gucvar = gucvar;
1005 for (i = 0; ConfigureNamesReal[i].gen.name; i++)
1007 struct config_generic *gucvar = &ConfigureNamesReal[i].gen;
1009 hentry = (GUCHashEntry *) hash_search(guc_hashtab,
1010 &gucvar->name,
1011 HASH_ENTER,
1012 &found);
1013 Assert(!found);
1014 hentry->gucvar = gucvar;
1017 for (i = 0; ConfigureNamesString[i].gen.name; i++)
1019 struct config_generic *gucvar = &ConfigureNamesString[i].gen;
1021 hentry = (GUCHashEntry *) hash_search(guc_hashtab,
1022 &gucvar->name,
1023 HASH_ENTER,
1024 &found);
1025 Assert(!found);
1026 hentry->gucvar = gucvar;
1029 for (i = 0; ConfigureNamesEnum[i].gen.name; i++)
1031 struct config_generic *gucvar = &ConfigureNamesEnum[i].gen;
1033 hentry = (GUCHashEntry *) hash_search(guc_hashtab,
1034 &gucvar->name,
1035 HASH_ENTER,
1036 &found);
1037 Assert(!found);
1038 hentry->gucvar = gucvar;
1041 Assert(num_vars == hash_get_num_entries(guc_hashtab));
1045 * Add a new GUC variable to the hash of known variables. The
1046 * hash is expanded if needed.
1048 static bool
1049 add_guc_variable(struct config_generic *var, int elevel)
1051 GUCHashEntry *hentry;
1052 bool found;
1054 hentry = (GUCHashEntry *) hash_search(guc_hashtab,
1055 &var->name,
1056 HASH_ENTER_NULL,
1057 &found);
1058 if (unlikely(hentry == NULL))
1060 ereport(elevel,
1061 (errcode(ERRCODE_OUT_OF_MEMORY),
1062 errmsg("out of memory")));
1063 return false; /* out of memory */
1065 Assert(!found);
1066 hentry->gucvar = var;
1067 return true;
1071 * Decide whether a proposed custom variable name is allowed.
1073 * It must be two or more identifiers separated by dots, where the rules
1074 * for what is an identifier agree with scan.l. (If you change this rule,
1075 * adjust the errdetail in assignable_custom_variable_name().)
1077 static bool
1078 valid_custom_variable_name(const char *name)
1080 bool saw_sep = false;
1081 bool name_start = true;
1083 for (const char *p = name; *p; p++)
1085 if (*p == GUC_QUALIFIER_SEPARATOR)
1087 if (name_start)
1088 return false; /* empty name component */
1089 saw_sep = true;
1090 name_start = true;
1092 else if (strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1093 "abcdefghijklmnopqrstuvwxyz_", *p) != NULL ||
1094 IS_HIGHBIT_SET(*p))
1096 /* okay as first or non-first character */
1097 name_start = false;
1099 else if (!name_start && strchr("0123456789$", *p) != NULL)
1100 /* okay as non-first character */ ;
1101 else
1102 return false;
1104 if (name_start)
1105 return false; /* empty name component */
1106 /* OK if we found at least one separator */
1107 return saw_sep;
1111 * Decide whether an unrecognized variable name is allowed to be SET.
1113 * It must pass the syntactic rules of valid_custom_variable_name(),
1114 * and it must not be in any namespace already reserved by an extension.
1115 * (We make this separate from valid_custom_variable_name() because we don't
1116 * apply the reserved-namespace test when reading configuration files.)
1118 * If valid, return true. Otherwise, return false if skip_errors is true,
1119 * else throw a suitable error at the specified elevel (and return false
1120 * if that's less than ERROR).
1122 static bool
1123 assignable_custom_variable_name(const char *name, bool skip_errors, int elevel)
1125 /* If there's no separator, it can't be a custom variable */
1126 const char *sep = strchr(name, GUC_QUALIFIER_SEPARATOR);
1128 if (sep != NULL)
1130 size_t classLen = sep - name;
1131 ListCell *lc;
1133 /* The name must be syntactically acceptable ... */
1134 if (!valid_custom_variable_name(name))
1136 if (!skip_errors)
1137 ereport(elevel,
1138 (errcode(ERRCODE_INVALID_NAME),
1139 errmsg("invalid configuration parameter name \"%s\"",
1140 name),
1141 errdetail("Custom parameter names must be two or more simple identifiers separated by dots.")));
1142 return false;
1144 /* ... and it must not match any previously-reserved prefix */
1145 foreach(lc, reserved_class_prefix)
1147 const char *rcprefix = lfirst(lc);
1149 if (strlen(rcprefix) == classLen &&
1150 strncmp(name, rcprefix, classLen) == 0)
1152 if (!skip_errors)
1153 ereport(elevel,
1154 (errcode(ERRCODE_INVALID_NAME),
1155 errmsg("invalid configuration parameter name \"%s\"",
1156 name),
1157 errdetail("\"%s\" is a reserved prefix.",
1158 rcprefix)));
1159 return false;
1162 /* OK to create it */
1163 return true;
1166 /* Unrecognized single-part name */
1167 if (!skip_errors)
1168 ereport(elevel,
1169 (errcode(ERRCODE_UNDEFINED_OBJECT),
1170 errmsg("unrecognized configuration parameter \"%s\"",
1171 name)));
1172 return false;
1176 * Create and add a placeholder variable for a custom variable name.
1178 static struct config_generic *
1179 add_placeholder_variable(const char *name, int elevel)
1181 size_t sz = sizeof(struct config_string) + sizeof(char *);
1182 struct config_string *var;
1183 struct config_generic *gen;
1185 var = (struct config_string *) guc_malloc(elevel, sz);
1186 if (var == NULL)
1187 return NULL;
1188 memset(var, 0, sz);
1189 gen = &var->gen;
1191 gen->name = guc_strdup(elevel, name);
1192 if (gen->name == NULL)
1194 guc_free(var);
1195 return NULL;
1198 gen->context = PGC_USERSET;
1199 gen->group = CUSTOM_OPTIONS;
1200 gen->short_desc = "GUC placeholder variable";
1201 gen->flags = GUC_NO_SHOW_ALL | GUC_NOT_IN_SAMPLE | GUC_CUSTOM_PLACEHOLDER;
1202 gen->vartype = PGC_STRING;
1205 * The char* is allocated at the end of the struct since we have no
1206 * 'static' place to point to. Note that the current value, as well as
1207 * the boot and reset values, start out NULL.
1209 var->variable = (char **) (var + 1);
1211 if (!add_guc_variable((struct config_generic *) var, elevel))
1213 guc_free(unconstify(char *, gen->name));
1214 guc_free(var);
1215 return NULL;
1218 return gen;
1222 * Look up option "name". If it exists, return a pointer to its record.
1223 * Otherwise, if create_placeholders is true and name is a valid-looking
1224 * custom variable name, we'll create and return a placeholder record.
1225 * Otherwise, if skip_errors is true, then we silently return NULL for
1226 * an unrecognized or invalid name. Otherwise, the error is reported at
1227 * error level elevel (and we return NULL if that's less than ERROR).
1229 * Note: internal errors, primarily out-of-memory, draw an elevel-level
1230 * report and NULL return regardless of skip_errors. Hence, callers must
1231 * handle a NULL return whenever elevel < ERROR, but they should not need
1232 * to emit any additional error message. (In practice, internal errors
1233 * can only happen when create_placeholders is true, so callers passing
1234 * false need not think terribly hard about this.)
1236 struct config_generic *
1237 find_option(const char *name, bool create_placeholders, bool skip_errors,
1238 int elevel)
1240 GUCHashEntry *hentry;
1241 int i;
1243 Assert(name);
1245 /* Look it up using the hash table. */
1246 hentry = (GUCHashEntry *) hash_search(guc_hashtab,
1247 &name,
1248 HASH_FIND,
1249 NULL);
1250 if (hentry)
1251 return hentry->gucvar;
1254 * See if the name is an obsolete name for a variable. We assume that the
1255 * set of supported old names is short enough that a brute-force search is
1256 * the best way.
1258 for (i = 0; map_old_guc_names[i] != NULL; i += 2)
1260 if (guc_name_compare(name, map_old_guc_names[i]) == 0)
1261 return find_option(map_old_guc_names[i + 1], false,
1262 skip_errors, elevel);
1265 if (create_placeholders)
1268 * Check if the name is valid, and if so, add a placeholder.
1270 if (assignable_custom_variable_name(name, skip_errors, elevel))
1271 return add_placeholder_variable(name, elevel);
1272 else
1273 return NULL; /* error message, if any, already emitted */
1276 /* Unknown name and we're not supposed to make a placeholder */
1277 if (!skip_errors)
1278 ereport(elevel,
1279 (errcode(ERRCODE_UNDEFINED_OBJECT),
1280 errmsg("unrecognized configuration parameter \"%s\"",
1281 name)));
1282 return NULL;
1287 * comparator for qsorting an array of GUC pointers
1289 static int
1290 guc_var_compare(const void *a, const void *b)
1292 const char *namea = **(const char **const *) a;
1293 const char *nameb = **(const char **const *) b;
1295 return guc_name_compare(namea, nameb);
1299 * the bare comparison function for GUC names
1302 guc_name_compare(const char *namea, const char *nameb)
1305 * The temptation to use strcasecmp() here must be resisted, because the
1306 * hash mapping has to remain stable across setlocale() calls. So, build
1307 * our own with a simple ASCII-only downcasing.
1309 while (*namea && *nameb)
1311 char cha = *namea++;
1312 char chb = *nameb++;
1314 if (cha >= 'A' && cha <= 'Z')
1315 cha += 'a' - 'A';
1316 if (chb >= 'A' && chb <= 'Z')
1317 chb += 'a' - 'A';
1318 if (cha != chb)
1319 return cha - chb;
1321 if (*namea)
1322 return 1; /* a is longer */
1323 if (*nameb)
1324 return -1; /* b is longer */
1325 return 0;
1329 * Hash function that's compatible with guc_name_compare
1331 static uint32
1332 guc_name_hash(const void *key, Size keysize)
1334 uint32 result = 0;
1335 const char *name = *(const char *const *) key;
1337 while (*name)
1339 char ch = *name++;
1341 /* Case-fold in the same way as guc_name_compare */
1342 if (ch >= 'A' && ch <= 'Z')
1343 ch += 'a' - 'A';
1345 /* Merge into hash ... not very bright, but it needn't be */
1346 result = pg_rotate_left32(result, 5);
1347 result ^= (uint32) ch;
1349 return result;
1353 * Dynahash match function to use in guc_hashtab
1355 static int
1356 guc_name_match(const void *key1, const void *key2, Size keysize)
1358 const char *name1 = *(const char *const *) key1;
1359 const char *name2 = *(const char *const *) key2;
1361 return guc_name_compare(name1, name2);
1366 * Convert a GUC name to the form that should be used in pg_parameter_acl.
1368 * We need to canonicalize entries since, for example, case should not be
1369 * significant. In addition, we apply the map_old_guc_names[] mapping so that
1370 * any obsolete names will be converted when stored in a new PG version.
1371 * Note however that this function does not verify legality of the name.
1373 * The result is a palloc'd string.
1375 char *
1376 convert_GUC_name_for_parameter_acl(const char *name)
1378 char *result;
1380 /* Apply old-GUC-name mapping. */
1381 for (int i = 0; map_old_guc_names[i] != NULL; i += 2)
1383 if (guc_name_compare(name, map_old_guc_names[i]) == 0)
1385 name = map_old_guc_names[i + 1];
1386 break;
1390 /* Apply case-folding that matches guc_name_compare(). */
1391 result = pstrdup(name);
1392 for (char *ptr = result; *ptr != '\0'; ptr++)
1394 char ch = *ptr;
1396 if (ch >= 'A' && ch <= 'Z')
1398 ch += 'a' - 'A';
1399 *ptr = ch;
1403 return result;
1407 * Check whether we should allow creation of a pg_parameter_acl entry
1408 * for the given name. (This can be applied either before or after
1409 * canonicalizing it.) Throws error if not.
1411 void
1412 check_GUC_name_for_parameter_acl(const char *name)
1414 /* OK if the GUC exists. */
1415 if (find_option(name, false, true, DEBUG5) != NULL)
1416 return;
1417 /* Otherwise, it'd better be a valid custom GUC name. */
1418 (void) assignable_custom_variable_name(name, false, ERROR);
1422 * Routine in charge of checking various states of a GUC.
1424 * This performs two sanity checks. First, it checks that the initial
1425 * value of a GUC is the same when declared and when loaded to prevent
1426 * anybody looking at the C declarations of these GUCs from being fooled by
1427 * mismatched values. Second, it checks for incorrect flag combinations.
1429 * The following validation rules apply for the values:
1430 * bool - can be false, otherwise must be same as the boot_val
1431 * int - can be 0, otherwise must be same as the boot_val
1432 * real - can be 0.0, otherwise must be same as the boot_val
1433 * string - can be NULL, otherwise must be strcmp equal to the boot_val
1434 * enum - must be same as the boot_val
1436 #ifdef USE_ASSERT_CHECKING
1437 static bool
1438 check_GUC_init(struct config_generic *gconf)
1440 /* Checks on values */
1441 switch (gconf->vartype)
1443 case PGC_BOOL:
1445 struct config_bool *conf = (struct config_bool *) gconf;
1447 if (*conf->variable && !conf->boot_val)
1449 elog(LOG, "GUC (PGC_BOOL) %s, boot_val=%d, C-var=%d",
1450 conf->gen.name, conf->boot_val, *conf->variable);
1451 return false;
1453 break;
1455 case PGC_INT:
1457 struct config_int *conf = (struct config_int *) gconf;
1459 if (*conf->variable != 0 && *conf->variable != conf->boot_val)
1461 elog(LOG, "GUC (PGC_INT) %s, boot_val=%d, C-var=%d",
1462 conf->gen.name, conf->boot_val, *conf->variable);
1463 return false;
1465 break;
1467 case PGC_REAL:
1469 struct config_real *conf = (struct config_real *) gconf;
1471 if (*conf->variable != 0.0 && *conf->variable != conf->boot_val)
1473 elog(LOG, "GUC (PGC_REAL) %s, boot_val=%g, C-var=%g",
1474 conf->gen.name, conf->boot_val, *conf->variable);
1475 return false;
1477 break;
1479 case PGC_STRING:
1481 struct config_string *conf = (struct config_string *) gconf;
1483 if (*conf->variable != NULL &&
1484 (conf->boot_val == NULL ||
1485 strcmp(*conf->variable, conf->boot_val) != 0))
1487 elog(LOG, "GUC (PGC_STRING) %s, boot_val=%s, C-var=%s",
1488 conf->gen.name, conf->boot_val ? conf->boot_val : "<null>", *conf->variable);
1489 return false;
1491 break;
1493 case PGC_ENUM:
1495 struct config_enum *conf = (struct config_enum *) gconf;
1497 if (*conf->variable != conf->boot_val)
1499 elog(LOG, "GUC (PGC_ENUM) %s, boot_val=%d, C-var=%d",
1500 conf->gen.name, conf->boot_val, *conf->variable);
1501 return false;
1503 break;
1507 /* Flag combinations */
1510 * GUC_NO_SHOW_ALL requires GUC_NOT_IN_SAMPLE, as a parameter not part of
1511 * SHOW ALL should not be hidden in postgresql.conf.sample.
1513 if ((gconf->flags & GUC_NO_SHOW_ALL) &&
1514 !(gconf->flags & GUC_NOT_IN_SAMPLE))
1516 elog(LOG, "GUC %s flags: NO_SHOW_ALL and !NOT_IN_SAMPLE",
1517 gconf->name);
1518 return false;
1521 return true;
1523 #endif
1526 * Initialize GUC options during program startup.
1528 * Note that we cannot read the config file yet, since we have not yet
1529 * processed command-line switches.
1531 void
1532 InitializeGUCOptions(void)
1534 HASH_SEQ_STATUS status;
1535 GUCHashEntry *hentry;
1538 * Before log_line_prefix could possibly receive a nonempty setting, make
1539 * sure that timezone processing is minimally alive (see elog.c).
1541 pg_timezone_initialize();
1544 * Create GUCMemoryContext and build hash table of all GUC variables.
1546 build_guc_variables();
1549 * Load all variables with their compiled-in defaults, and initialize
1550 * status fields as needed.
1552 hash_seq_init(&status, guc_hashtab);
1553 while ((hentry = (GUCHashEntry *) hash_seq_search(&status)) != NULL)
1555 /* Check mapping between initial and default value */
1556 Assert(check_GUC_init(hentry->gucvar));
1558 InitializeOneGUCOption(hentry->gucvar);
1561 reporting_enabled = false;
1564 * Prevent any attempt to override the transaction modes from
1565 * non-interactive sources.
1567 SetConfigOption("transaction_isolation", "read committed",
1568 PGC_POSTMASTER, PGC_S_OVERRIDE);
1569 SetConfigOption("transaction_read_only", "no",
1570 PGC_POSTMASTER, PGC_S_OVERRIDE);
1571 SetConfigOption("transaction_deferrable", "no",
1572 PGC_POSTMASTER, PGC_S_OVERRIDE);
1575 * For historical reasons, some GUC parameters can receive defaults from
1576 * environment variables. Process those settings.
1578 InitializeGUCOptionsFromEnvironment();
1582 * Assign any GUC values that can come from the server's environment.
1584 * This is called from InitializeGUCOptions, and also from ProcessConfigFile
1585 * to deal with the possibility that a setting has been removed from
1586 * postgresql.conf and should now get a value from the environment.
1587 * (The latter is a kludge that should probably go away someday; if so,
1588 * fold this back into InitializeGUCOptions.)
1590 static void
1591 InitializeGUCOptionsFromEnvironment(void)
1593 char *env;
1594 long stack_rlimit;
1596 env = getenv("PGPORT");
1597 if (env != NULL)
1598 SetConfigOption("port", env, PGC_POSTMASTER, PGC_S_ENV_VAR);
1600 env = getenv("PGDATESTYLE");
1601 if (env != NULL)
1602 SetConfigOption("datestyle", env, PGC_POSTMASTER, PGC_S_ENV_VAR);
1604 env = getenv("PGCLIENTENCODING");
1605 if (env != NULL)
1606 SetConfigOption("client_encoding", env, PGC_POSTMASTER, PGC_S_ENV_VAR);
1609 * rlimit isn't exactly an "environment variable", but it behaves about
1610 * the same. If we can identify the platform stack depth rlimit, increase
1611 * default stack depth setting up to whatever is safe (but at most 2MB).
1612 * Report the value's source as PGC_S_DYNAMIC_DEFAULT if it's 2MB, or as
1613 * PGC_S_ENV_VAR if it's reflecting the rlimit limit.
1615 stack_rlimit = get_stack_depth_rlimit();
1616 if (stack_rlimit > 0)
1618 long new_limit = (stack_rlimit - STACK_DEPTH_SLOP) / 1024L;
1620 if (new_limit > 100)
1622 GucSource source;
1623 char limbuf[16];
1625 if (new_limit < 2048)
1626 source = PGC_S_ENV_VAR;
1627 else
1629 new_limit = 2048;
1630 source = PGC_S_DYNAMIC_DEFAULT;
1632 snprintf(limbuf, sizeof(limbuf), "%ld", new_limit);
1633 SetConfigOption("max_stack_depth", limbuf,
1634 PGC_POSTMASTER, source);
1640 * Initialize one GUC option variable to its compiled-in default.
1642 * Note: the reason for calling check_hooks is not that we think the boot_val
1643 * might fail, but that the hooks might wish to compute an "extra" struct.
1645 static void
1646 InitializeOneGUCOption(struct config_generic *gconf)
1648 gconf->status = 0;
1649 gconf->source = PGC_S_DEFAULT;
1650 gconf->reset_source = PGC_S_DEFAULT;
1651 gconf->scontext = PGC_INTERNAL;
1652 gconf->reset_scontext = PGC_INTERNAL;
1653 gconf->srole = BOOTSTRAP_SUPERUSERID;
1654 gconf->reset_srole = BOOTSTRAP_SUPERUSERID;
1655 gconf->stack = NULL;
1656 gconf->extra = NULL;
1657 gconf->last_reported = NULL;
1658 gconf->sourcefile = NULL;
1659 gconf->sourceline = 0;
1661 switch (gconf->vartype)
1663 case PGC_BOOL:
1665 struct config_bool *conf = (struct config_bool *) gconf;
1666 bool newval = conf->boot_val;
1667 void *extra = NULL;
1669 if (!call_bool_check_hook(conf, &newval, &extra,
1670 PGC_S_DEFAULT, LOG))
1671 elog(FATAL, "failed to initialize %s to %d",
1672 conf->gen.name, (int) newval);
1673 if (conf->assign_hook)
1674 conf->assign_hook(newval, extra);
1675 *conf->variable = conf->reset_val = newval;
1676 conf->gen.extra = conf->reset_extra = extra;
1677 break;
1679 case PGC_INT:
1681 struct config_int *conf = (struct config_int *) gconf;
1682 int newval = conf->boot_val;
1683 void *extra = NULL;
1685 Assert(newval >= conf->min);
1686 Assert(newval <= conf->max);
1687 if (!call_int_check_hook(conf, &newval, &extra,
1688 PGC_S_DEFAULT, LOG))
1689 elog(FATAL, "failed to initialize %s to %d",
1690 conf->gen.name, newval);
1691 if (conf->assign_hook)
1692 conf->assign_hook(newval, extra);
1693 *conf->variable = conf->reset_val = newval;
1694 conf->gen.extra = conf->reset_extra = extra;
1695 break;
1697 case PGC_REAL:
1699 struct config_real *conf = (struct config_real *) gconf;
1700 double newval = conf->boot_val;
1701 void *extra = NULL;
1703 Assert(newval >= conf->min);
1704 Assert(newval <= conf->max);
1705 if (!call_real_check_hook(conf, &newval, &extra,
1706 PGC_S_DEFAULT, LOG))
1707 elog(FATAL, "failed to initialize %s to %g",
1708 conf->gen.name, newval);
1709 if (conf->assign_hook)
1710 conf->assign_hook(newval, extra);
1711 *conf->variable = conf->reset_val = newval;
1712 conf->gen.extra = conf->reset_extra = extra;
1713 break;
1715 case PGC_STRING:
1717 struct config_string *conf = (struct config_string *) gconf;
1718 char *newval;
1719 void *extra = NULL;
1721 /* non-NULL boot_val must always get strdup'd */
1722 if (conf->boot_val != NULL)
1723 newval = guc_strdup(FATAL, conf->boot_val);
1724 else
1725 newval = NULL;
1727 if (!call_string_check_hook(conf, &newval, &extra,
1728 PGC_S_DEFAULT, LOG))
1729 elog(FATAL, "failed to initialize %s to \"%s\"",
1730 conf->gen.name, newval ? newval : "");
1731 if (conf->assign_hook)
1732 conf->assign_hook(newval, extra);
1733 *conf->variable = conf->reset_val = newval;
1734 conf->gen.extra = conf->reset_extra = extra;
1735 break;
1737 case PGC_ENUM:
1739 struct config_enum *conf = (struct config_enum *) gconf;
1740 int newval = conf->boot_val;
1741 void *extra = NULL;
1743 if (!call_enum_check_hook(conf, &newval, &extra,
1744 PGC_S_DEFAULT, LOG))
1745 elog(FATAL, "failed to initialize %s to %d",
1746 conf->gen.name, newval);
1747 if (conf->assign_hook)
1748 conf->assign_hook(newval, extra);
1749 *conf->variable = conf->reset_val = newval;
1750 conf->gen.extra = conf->reset_extra = extra;
1751 break;
1757 * Summarily remove a GUC variable from any linked lists it's in.
1759 * We use this in cases where the variable is about to be deleted or reset.
1760 * These aren't common operations, so it's okay if this is a bit slow.
1762 static void
1763 RemoveGUCFromLists(struct config_generic *gconf)
1765 if (gconf->source != PGC_S_DEFAULT)
1766 dlist_delete(&gconf->nondef_link);
1767 if (gconf->stack != NULL)
1768 slist_delete(&guc_stack_list, &gconf->stack_link);
1769 if (gconf->status & GUC_NEEDS_REPORT)
1770 slist_delete(&guc_report_list, &gconf->report_link);
1775 * Select the configuration files and data directory to be used, and
1776 * do the initial read of postgresql.conf.
1778 * This is called after processing command-line switches.
1779 * userDoption is the -D switch value if any (NULL if unspecified).
1780 * progname is just for use in error messages.
1782 * Returns true on success; on failure, prints a suitable error message
1783 * to stderr and returns false.
1785 bool
1786 SelectConfigFiles(const char *userDoption, const char *progname)
1788 char *configdir;
1789 char *fname;
1790 bool fname_is_malloced;
1791 struct stat stat_buf;
1792 struct config_string *data_directory_rec;
1794 /* configdir is -D option, or $PGDATA if no -D */
1795 if (userDoption)
1796 configdir = make_absolute_path(userDoption);
1797 else
1798 configdir = make_absolute_path(getenv("PGDATA"));
1800 if (configdir && stat(configdir, &stat_buf) != 0)
1802 write_stderr("%s: could not access directory \"%s\": %m\n",
1803 progname,
1804 configdir);
1805 if (errno == ENOENT)
1806 write_stderr("Run initdb or pg_basebackup to initialize a PostgreSQL data directory.\n");
1807 return false;
1811 * Find the configuration file: if config_file was specified on the
1812 * command line, use it, else use configdir/postgresql.conf. In any case
1813 * ensure the result is an absolute path, so that it will be interpreted
1814 * the same way by future backends.
1816 if (ConfigFileName)
1818 fname = make_absolute_path(ConfigFileName);
1819 fname_is_malloced = true;
1821 else if (configdir)
1823 fname = guc_malloc(FATAL,
1824 strlen(configdir) + strlen(CONFIG_FILENAME) + 2);
1825 sprintf(fname, "%s/%s", configdir, CONFIG_FILENAME);
1826 fname_is_malloced = false;
1828 else
1830 write_stderr("%s does not know where to find the server configuration file.\n"
1831 "You must specify the --config-file or -D invocation "
1832 "option or set the PGDATA environment variable.\n",
1833 progname);
1834 return false;
1838 * Set the ConfigFileName GUC variable to its final value, ensuring that
1839 * it can't be overridden later.
1841 SetConfigOption("config_file", fname, PGC_POSTMASTER, PGC_S_OVERRIDE);
1843 if (fname_is_malloced)
1844 free(fname);
1845 else
1846 guc_free(fname);
1849 * Now read the config file for the first time.
1851 if (stat(ConfigFileName, &stat_buf) != 0)
1853 write_stderr("%s: could not access the server configuration file \"%s\": %m\n",
1854 progname, ConfigFileName);
1855 free(configdir);
1856 return false;
1860 * Read the configuration file for the first time. This time only the
1861 * data_directory parameter is picked up to determine the data directory,
1862 * so that we can read the PG_AUTOCONF_FILENAME file next time.
1864 ProcessConfigFile(PGC_POSTMASTER);
1867 * If the data_directory GUC variable has been set, use that as DataDir;
1868 * otherwise use configdir if set; else punt.
1870 * Note: SetDataDir will copy and absolute-ize its argument, so we don't
1871 * have to.
1873 data_directory_rec = (struct config_string *)
1874 find_option("data_directory", false, false, PANIC);
1875 if (*data_directory_rec->variable)
1876 SetDataDir(*data_directory_rec->variable);
1877 else if (configdir)
1878 SetDataDir(configdir);
1879 else
1881 write_stderr("%s does not know where to find the database system data.\n"
1882 "This can be specified as \"data_directory\" in \"%s\", "
1883 "or by the -D invocation option, or by the "
1884 "PGDATA environment variable.\n",
1885 progname, ConfigFileName);
1886 return false;
1890 * Reflect the final DataDir value back into the data_directory GUC var.
1891 * (If you are wondering why we don't just make them a single variable,
1892 * it's because the EXEC_BACKEND case needs DataDir to be transmitted to
1893 * child backends specially. XXX is that still true? Given that we now
1894 * chdir to DataDir, EXEC_BACKEND can read the config file without knowing
1895 * DataDir in advance.)
1897 SetConfigOption("data_directory", DataDir, PGC_POSTMASTER, PGC_S_OVERRIDE);
1900 * Now read the config file a second time, allowing any settings in the
1901 * PG_AUTOCONF_FILENAME file to take effect. (This is pretty ugly, but
1902 * since we have to determine the DataDir before we can find the autoconf
1903 * file, the alternatives seem worse.)
1905 ProcessConfigFile(PGC_POSTMASTER);
1908 * If timezone_abbreviations wasn't set in the configuration file, install
1909 * the default value. We do it this way because we can't safely install a
1910 * "real" value until my_exec_path is set, which may not have happened
1911 * when InitializeGUCOptions runs, so the bootstrap default value cannot
1912 * be the real desired default.
1914 pg_timezone_abbrev_initialize();
1917 * Figure out where pg_hba.conf is, and make sure the path is absolute.
1919 if (HbaFileName)
1921 fname = make_absolute_path(HbaFileName);
1922 fname_is_malloced = true;
1924 else if (configdir)
1926 fname = guc_malloc(FATAL,
1927 strlen(configdir) + strlen(HBA_FILENAME) + 2);
1928 sprintf(fname, "%s/%s", configdir, HBA_FILENAME);
1929 fname_is_malloced = false;
1931 else
1933 write_stderr("%s does not know where to find the \"hba\" configuration file.\n"
1934 "This can be specified as \"hba_file\" in \"%s\", "
1935 "or by the -D invocation option, or by the "
1936 "PGDATA environment variable.\n",
1937 progname, ConfigFileName);
1938 return false;
1940 SetConfigOption("hba_file", fname, PGC_POSTMASTER, PGC_S_OVERRIDE);
1942 if (fname_is_malloced)
1943 free(fname);
1944 else
1945 guc_free(fname);
1948 * Likewise for pg_ident.conf.
1950 if (IdentFileName)
1952 fname = make_absolute_path(IdentFileName);
1953 fname_is_malloced = true;
1955 else if (configdir)
1957 fname = guc_malloc(FATAL,
1958 strlen(configdir) + strlen(IDENT_FILENAME) + 2);
1959 sprintf(fname, "%s/%s", configdir, IDENT_FILENAME);
1960 fname_is_malloced = false;
1962 else
1964 write_stderr("%s does not know where to find the \"ident\" configuration file.\n"
1965 "This can be specified as \"ident_file\" in \"%s\", "
1966 "or by the -D invocation option, or by the "
1967 "PGDATA environment variable.\n",
1968 progname, ConfigFileName);
1969 return false;
1971 SetConfigOption("ident_file", fname, PGC_POSTMASTER, PGC_S_OVERRIDE);
1973 if (fname_is_malloced)
1974 free(fname);
1975 else
1976 guc_free(fname);
1978 free(configdir);
1980 return true;
1984 * pg_timezone_abbrev_initialize --- set default value if not done already
1986 * This is called after initial loading of postgresql.conf. If no
1987 * timezone_abbreviations setting was found therein, select default.
1988 * If a non-default value is already installed, nothing will happen.
1990 * This can also be called from ProcessConfigFile to establish the default
1991 * value after a postgresql.conf entry for it is removed.
1993 static void
1994 pg_timezone_abbrev_initialize(void)
1996 SetConfigOption("timezone_abbreviations", "Default",
1997 PGC_POSTMASTER, PGC_S_DYNAMIC_DEFAULT);
2002 * Reset all options to their saved default values (implements RESET ALL)
2004 void
2005 ResetAllOptions(void)
2007 dlist_mutable_iter iter;
2009 /* We need only consider GUCs not already at PGC_S_DEFAULT */
2010 dlist_foreach_modify(iter, &guc_nondef_list)
2012 struct config_generic *gconf = dlist_container(struct config_generic,
2013 nondef_link, iter.cur);
2015 /* Don't reset non-SET-able values */
2016 if (gconf->context != PGC_SUSET &&
2017 gconf->context != PGC_USERSET)
2018 continue;
2019 /* Don't reset if special exclusion from RESET ALL */
2020 if (gconf->flags & GUC_NO_RESET_ALL)
2021 continue;
2022 /* No need to reset if wasn't SET */
2023 if (gconf->source <= PGC_S_OVERRIDE)
2024 continue;
2026 /* Save old value to support transaction abort */
2027 push_old_value(gconf, GUC_ACTION_SET);
2029 switch (gconf->vartype)
2031 case PGC_BOOL:
2033 struct config_bool *conf = (struct config_bool *) gconf;
2035 if (conf->assign_hook)
2036 conf->assign_hook(conf->reset_val,
2037 conf->reset_extra);
2038 *conf->variable = conf->reset_val;
2039 set_extra_field(&conf->gen, &conf->gen.extra,
2040 conf->reset_extra);
2041 break;
2043 case PGC_INT:
2045 struct config_int *conf = (struct config_int *) gconf;
2047 if (conf->assign_hook)
2048 conf->assign_hook(conf->reset_val,
2049 conf->reset_extra);
2050 *conf->variable = conf->reset_val;
2051 set_extra_field(&conf->gen, &conf->gen.extra,
2052 conf->reset_extra);
2053 break;
2055 case PGC_REAL:
2057 struct config_real *conf = (struct config_real *) gconf;
2059 if (conf->assign_hook)
2060 conf->assign_hook(conf->reset_val,
2061 conf->reset_extra);
2062 *conf->variable = conf->reset_val;
2063 set_extra_field(&conf->gen, &conf->gen.extra,
2064 conf->reset_extra);
2065 break;
2067 case PGC_STRING:
2069 struct config_string *conf = (struct config_string *) gconf;
2071 if (conf->assign_hook)
2072 conf->assign_hook(conf->reset_val,
2073 conf->reset_extra);
2074 set_string_field(conf, conf->variable, conf->reset_val);
2075 set_extra_field(&conf->gen, &conf->gen.extra,
2076 conf->reset_extra);
2077 break;
2079 case PGC_ENUM:
2081 struct config_enum *conf = (struct config_enum *) gconf;
2083 if (conf->assign_hook)
2084 conf->assign_hook(conf->reset_val,
2085 conf->reset_extra);
2086 *conf->variable = conf->reset_val;
2087 set_extra_field(&conf->gen, &conf->gen.extra,
2088 conf->reset_extra);
2089 break;
2093 set_guc_source(gconf, gconf->reset_source);
2094 gconf->scontext = gconf->reset_scontext;
2095 gconf->srole = gconf->reset_srole;
2097 if ((gconf->flags & GUC_REPORT) && !(gconf->status & GUC_NEEDS_REPORT))
2099 gconf->status |= GUC_NEEDS_REPORT;
2100 slist_push_head(&guc_report_list, &gconf->report_link);
2107 * Apply a change to a GUC variable's "source" field.
2109 * Use this rather than just assigning, to ensure that the variable's
2110 * membership in guc_nondef_list is updated correctly.
2112 static void
2113 set_guc_source(struct config_generic *gconf, GucSource newsource)
2115 /* Adjust nondef list membership if appropriate for change */
2116 if (gconf->source == PGC_S_DEFAULT)
2118 if (newsource != PGC_S_DEFAULT)
2119 dlist_push_tail(&guc_nondef_list, &gconf->nondef_link);
2121 else
2123 if (newsource == PGC_S_DEFAULT)
2124 dlist_delete(&gconf->nondef_link);
2126 /* Now update the source field */
2127 gconf->source = newsource;
2132 * push_old_value
2133 * Push previous state during transactional assignment to a GUC variable.
2135 static void
2136 push_old_value(struct config_generic *gconf, GucAction action)
2138 GucStack *stack;
2140 /* If we're not inside a nest level, do nothing */
2141 if (GUCNestLevel == 0)
2142 return;
2144 /* Do we already have a stack entry of the current nest level? */
2145 stack = gconf->stack;
2146 if (stack && stack->nest_level >= GUCNestLevel)
2148 /* Yes, so adjust its state if necessary */
2149 Assert(stack->nest_level == GUCNestLevel);
2150 switch (action)
2152 case GUC_ACTION_SET:
2153 /* SET overrides any prior action at same nest level */
2154 if (stack->state == GUC_SET_LOCAL)
2156 /* must discard old masked value */
2157 discard_stack_value(gconf, &stack->masked);
2159 stack->state = GUC_SET;
2160 break;
2161 case GUC_ACTION_LOCAL:
2162 if (stack->state == GUC_SET)
2164 /* SET followed by SET LOCAL, remember SET's value */
2165 stack->masked_scontext = gconf->scontext;
2166 stack->masked_srole = gconf->srole;
2167 set_stack_value(gconf, &stack->masked);
2168 stack->state = GUC_SET_LOCAL;
2170 /* in all other cases, no change to stack entry */
2171 break;
2172 case GUC_ACTION_SAVE:
2173 /* Could only have a prior SAVE of same variable */
2174 Assert(stack->state == GUC_SAVE);
2175 break;
2177 return;
2181 * Push a new stack entry
2183 * We keep all the stack entries in TopTransactionContext for simplicity.
2185 stack = (GucStack *) MemoryContextAllocZero(TopTransactionContext,
2186 sizeof(GucStack));
2188 stack->prev = gconf->stack;
2189 stack->nest_level = GUCNestLevel;
2190 switch (action)
2192 case GUC_ACTION_SET:
2193 stack->state = GUC_SET;
2194 break;
2195 case GUC_ACTION_LOCAL:
2196 stack->state = GUC_LOCAL;
2197 break;
2198 case GUC_ACTION_SAVE:
2199 stack->state = GUC_SAVE;
2200 break;
2202 stack->source = gconf->source;
2203 stack->scontext = gconf->scontext;
2204 stack->srole = gconf->srole;
2205 set_stack_value(gconf, &stack->prior);
2207 if (gconf->stack == NULL)
2208 slist_push_head(&guc_stack_list, &gconf->stack_link);
2209 gconf->stack = stack;
2214 * Do GUC processing at main transaction start.
2216 void
2217 AtStart_GUC(void)
2220 * The nest level should be 0 between transactions; if it isn't, somebody
2221 * didn't call AtEOXact_GUC, or called it with the wrong nestLevel. We
2222 * throw a warning but make no other effort to clean up.
2224 if (GUCNestLevel != 0)
2225 elog(WARNING, "GUC nest level = %d at transaction start",
2226 GUCNestLevel);
2227 GUCNestLevel = 1;
2231 * Enter a new nesting level for GUC values. This is called at subtransaction
2232 * start, and when entering a function that has proconfig settings, and in
2233 * some other places where we want to set GUC variables transiently.
2234 * NOTE we must not risk error here, else subtransaction start will be unhappy.
2237 NewGUCNestLevel(void)
2239 return ++GUCNestLevel;
2243 * Set search_path to a fixed value for maintenance operations. No effect
2244 * during bootstrap, when the search_path is already set to a fixed value and
2245 * cannot be changed.
2247 void
2248 RestrictSearchPath(void)
2250 if (!IsBootstrapProcessingMode())
2251 set_config_option("search_path", GUC_SAFE_SEARCH_PATH, PGC_USERSET,
2252 PGC_S_SESSION, GUC_ACTION_SAVE, true, 0, false);
2256 * Do GUC processing at transaction or subtransaction commit or abort, or
2257 * when exiting a function that has proconfig settings, or when undoing a
2258 * transient assignment to some GUC variables. (The name is thus a bit of
2259 * a misnomer; perhaps it should be ExitGUCNestLevel or some such.)
2260 * During abort, we discard all GUC settings that were applied at nesting
2261 * levels >= nestLevel. nestLevel == 1 corresponds to the main transaction.
2263 void
2264 AtEOXact_GUC(bool isCommit, int nestLevel)
2266 slist_mutable_iter iter;
2269 * Note: it's possible to get here with GUCNestLevel == nestLevel-1 during
2270 * abort, if there is a failure during transaction start before
2271 * AtStart_GUC is called.
2273 Assert(nestLevel > 0 &&
2274 (nestLevel <= GUCNestLevel ||
2275 (nestLevel == GUCNestLevel + 1 && !isCommit)));
2277 /* We need only process GUCs having nonempty stacks */
2278 slist_foreach_modify(iter, &guc_stack_list)
2280 struct config_generic *gconf = slist_container(struct config_generic,
2281 stack_link, iter.cur);
2282 GucStack *stack;
2285 * Process and pop each stack entry within the nest level. To simplify
2286 * fmgr_security_definer() and other places that use GUC_ACTION_SAVE,
2287 * we allow failure exit from code that uses a local nest level to be
2288 * recovered at the surrounding transaction or subtransaction abort;
2289 * so there could be more than one stack entry to pop.
2291 while ((stack = gconf->stack) != NULL &&
2292 stack->nest_level >= nestLevel)
2294 GucStack *prev = stack->prev;
2295 bool restorePrior = false;
2296 bool restoreMasked = false;
2297 bool changed;
2300 * In this next bit, if we don't set either restorePrior or
2301 * restoreMasked, we must "discard" any unwanted fields of the
2302 * stack entries to avoid leaking memory. If we do set one of
2303 * those flags, unused fields will be cleaned up after restoring.
2305 if (!isCommit) /* if abort, always restore prior value */
2306 restorePrior = true;
2307 else if (stack->state == GUC_SAVE)
2308 restorePrior = true;
2309 else if (stack->nest_level == 1)
2311 /* transaction commit */
2312 if (stack->state == GUC_SET_LOCAL)
2313 restoreMasked = true;
2314 else if (stack->state == GUC_SET)
2316 /* we keep the current active value */
2317 discard_stack_value(gconf, &stack->prior);
2319 else /* must be GUC_LOCAL */
2320 restorePrior = true;
2322 else if (prev == NULL ||
2323 prev->nest_level < stack->nest_level - 1)
2325 /* decrement entry's level and do not pop it */
2326 stack->nest_level--;
2327 continue;
2329 else
2332 * We have to merge this stack entry into prev. See README for
2333 * discussion of this bit.
2335 switch (stack->state)
2337 case GUC_SAVE:
2338 Assert(false); /* can't get here */
2339 break;
2341 case GUC_SET:
2342 /* next level always becomes SET */
2343 discard_stack_value(gconf, &stack->prior);
2344 if (prev->state == GUC_SET_LOCAL)
2345 discard_stack_value(gconf, &prev->masked);
2346 prev->state = GUC_SET;
2347 break;
2349 case GUC_LOCAL:
2350 if (prev->state == GUC_SET)
2352 /* LOCAL migrates down */
2353 prev->masked_scontext = stack->scontext;
2354 prev->masked_srole = stack->srole;
2355 prev->masked = stack->prior;
2356 prev->state = GUC_SET_LOCAL;
2358 else
2360 /* else just forget this stack level */
2361 discard_stack_value(gconf, &stack->prior);
2363 break;
2365 case GUC_SET_LOCAL:
2366 /* prior state at this level no longer wanted */
2367 discard_stack_value(gconf, &stack->prior);
2368 /* copy down the masked state */
2369 prev->masked_scontext = stack->masked_scontext;
2370 prev->masked_srole = stack->masked_srole;
2371 if (prev->state == GUC_SET_LOCAL)
2372 discard_stack_value(gconf, &prev->masked);
2373 prev->masked = stack->masked;
2374 prev->state = GUC_SET_LOCAL;
2375 break;
2379 changed = false;
2381 if (restorePrior || restoreMasked)
2383 /* Perform appropriate restoration of the stacked value */
2384 config_var_value newvalue;
2385 GucSource newsource;
2386 GucContext newscontext;
2387 Oid newsrole;
2389 if (restoreMasked)
2391 newvalue = stack->masked;
2392 newsource = PGC_S_SESSION;
2393 newscontext = stack->masked_scontext;
2394 newsrole = stack->masked_srole;
2396 else
2398 newvalue = stack->prior;
2399 newsource = stack->source;
2400 newscontext = stack->scontext;
2401 newsrole = stack->srole;
2404 switch (gconf->vartype)
2406 case PGC_BOOL:
2408 struct config_bool *conf = (struct config_bool *) gconf;
2409 bool newval = newvalue.val.boolval;
2410 void *newextra = newvalue.extra;
2412 if (*conf->variable != newval ||
2413 conf->gen.extra != newextra)
2415 if (conf->assign_hook)
2416 conf->assign_hook(newval, newextra);
2417 *conf->variable = newval;
2418 set_extra_field(&conf->gen, &conf->gen.extra,
2419 newextra);
2420 changed = true;
2422 break;
2424 case PGC_INT:
2426 struct config_int *conf = (struct config_int *) gconf;
2427 int newval = newvalue.val.intval;
2428 void *newextra = newvalue.extra;
2430 if (*conf->variable != newval ||
2431 conf->gen.extra != newextra)
2433 if (conf->assign_hook)
2434 conf->assign_hook(newval, newextra);
2435 *conf->variable = newval;
2436 set_extra_field(&conf->gen, &conf->gen.extra,
2437 newextra);
2438 changed = true;
2440 break;
2442 case PGC_REAL:
2444 struct config_real *conf = (struct config_real *) gconf;
2445 double newval = newvalue.val.realval;
2446 void *newextra = newvalue.extra;
2448 if (*conf->variable != newval ||
2449 conf->gen.extra != newextra)
2451 if (conf->assign_hook)
2452 conf->assign_hook(newval, newextra);
2453 *conf->variable = newval;
2454 set_extra_field(&conf->gen, &conf->gen.extra,
2455 newextra);
2456 changed = true;
2458 break;
2460 case PGC_STRING:
2462 struct config_string *conf = (struct config_string *) gconf;
2463 char *newval = newvalue.val.stringval;
2464 void *newextra = newvalue.extra;
2466 if (*conf->variable != newval ||
2467 conf->gen.extra != newextra)
2469 if (conf->assign_hook)
2470 conf->assign_hook(newval, newextra);
2471 set_string_field(conf, conf->variable, newval);
2472 set_extra_field(&conf->gen, &conf->gen.extra,
2473 newextra);
2474 changed = true;
2478 * Release stacked values if not used anymore. We
2479 * could use discard_stack_value() here, but since
2480 * we have type-specific code anyway, might as
2481 * well inline it.
2483 set_string_field(conf, &stack->prior.val.stringval, NULL);
2484 set_string_field(conf, &stack->masked.val.stringval, NULL);
2485 break;
2487 case PGC_ENUM:
2489 struct config_enum *conf = (struct config_enum *) gconf;
2490 int newval = newvalue.val.enumval;
2491 void *newextra = newvalue.extra;
2493 if (*conf->variable != newval ||
2494 conf->gen.extra != newextra)
2496 if (conf->assign_hook)
2497 conf->assign_hook(newval, newextra);
2498 *conf->variable = newval;
2499 set_extra_field(&conf->gen, &conf->gen.extra,
2500 newextra);
2501 changed = true;
2503 break;
2508 * Release stacked extra values if not used anymore.
2510 set_extra_field(gconf, &(stack->prior.extra), NULL);
2511 set_extra_field(gconf, &(stack->masked.extra), NULL);
2513 /* And restore source information */
2514 set_guc_source(gconf, newsource);
2515 gconf->scontext = newscontext;
2516 gconf->srole = newsrole;
2520 * Pop the GUC's state stack; if it's now empty, remove the GUC
2521 * from guc_stack_list.
2523 gconf->stack = prev;
2524 if (prev == NULL)
2525 slist_delete_current(&iter);
2526 pfree(stack);
2528 /* Report new value if we changed it */
2529 if (changed && (gconf->flags & GUC_REPORT) &&
2530 !(gconf->status & GUC_NEEDS_REPORT))
2532 gconf->status |= GUC_NEEDS_REPORT;
2533 slist_push_head(&guc_report_list, &gconf->report_link);
2535 } /* end of stack-popping loop */
2538 /* Update nesting level */
2539 GUCNestLevel = nestLevel - 1;
2544 * Start up automatic reporting of changes to variables marked GUC_REPORT.
2545 * This is executed at completion of backend startup.
2547 void
2548 BeginReportingGUCOptions(void)
2550 HASH_SEQ_STATUS status;
2551 GUCHashEntry *hentry;
2554 * Don't do anything unless talking to an interactive frontend.
2556 if (whereToSendOutput != DestRemote)
2557 return;
2559 reporting_enabled = true;
2562 * Hack for in_hot_standby: set the GUC value true if appropriate. This
2563 * is kind of an ugly place to do it, but there's few better options.
2565 * (This could be out of date by the time we actually send it, in which
2566 * case the next ReportChangedGUCOptions call will send a duplicate
2567 * report.)
2569 if (RecoveryInProgress())
2570 SetConfigOption("in_hot_standby", "true",
2571 PGC_INTERNAL, PGC_S_OVERRIDE);
2573 /* Transmit initial values of interesting variables */
2574 hash_seq_init(&status, guc_hashtab);
2575 while ((hentry = (GUCHashEntry *) hash_seq_search(&status)) != NULL)
2577 struct config_generic *conf = hentry->gucvar;
2579 if (conf->flags & GUC_REPORT)
2580 ReportGUCOption(conf);
2585 * ReportChangedGUCOptions: report recently-changed GUC_REPORT variables
2587 * This is called just before we wait for a new client query.
2589 * By handling things this way, we ensure that a ParameterStatus message
2590 * is sent at most once per variable per query, even if the variable
2591 * changed multiple times within the query. That's quite possible when
2592 * using features such as function SET clauses. Function SET clauses
2593 * also tend to cause values to change intraquery but eventually revert
2594 * to their prevailing values; ReportGUCOption is responsible for avoiding
2595 * redundant reports in such cases.
2597 void
2598 ReportChangedGUCOptions(void)
2600 slist_mutable_iter iter;
2602 /* Quick exit if not (yet) enabled */
2603 if (!reporting_enabled)
2604 return;
2607 * Since in_hot_standby isn't actually changed by normal GUC actions, we
2608 * need a hack to check whether a new value needs to be reported to the
2609 * client. For speed, we rely on the assumption that it can never
2610 * transition from false to true.
2612 if (in_hot_standby_guc && !RecoveryInProgress())
2613 SetConfigOption("in_hot_standby", "false",
2614 PGC_INTERNAL, PGC_S_OVERRIDE);
2616 /* Transmit new values of interesting variables */
2617 slist_foreach_modify(iter, &guc_report_list)
2619 struct config_generic *conf = slist_container(struct config_generic,
2620 report_link, iter.cur);
2622 Assert((conf->flags & GUC_REPORT) && (conf->status & GUC_NEEDS_REPORT));
2623 ReportGUCOption(conf);
2624 conf->status &= ~GUC_NEEDS_REPORT;
2625 slist_delete_current(&iter);
2630 * ReportGUCOption: if appropriate, transmit option value to frontend
2632 * We need not transmit the value if it's the same as what we last
2633 * transmitted.
2635 static void
2636 ReportGUCOption(struct config_generic *record)
2638 char *val = ShowGUCOption(record, false);
2640 if (record->last_reported == NULL ||
2641 strcmp(val, record->last_reported) != 0)
2643 StringInfoData msgbuf;
2645 pq_beginmessage(&msgbuf, PqMsg_ParameterStatus);
2646 pq_sendstring(&msgbuf, record->name);
2647 pq_sendstring(&msgbuf, val);
2648 pq_endmessage(&msgbuf);
2651 * We need a long-lifespan copy. If guc_strdup() fails due to OOM,
2652 * we'll set last_reported to NULL and thereby possibly make a
2653 * duplicate report later.
2655 guc_free(record->last_reported);
2656 record->last_reported = guc_strdup(LOG, val);
2659 pfree(val);
2663 * Convert a value from one of the human-friendly units ("kB", "min" etc.)
2664 * to the given base unit. 'value' and 'unit' are the input value and unit
2665 * to convert from (there can be trailing spaces in the unit string).
2666 * The converted value is stored in *base_value.
2667 * It's caller's responsibility to round off the converted value as necessary
2668 * and check for out-of-range.
2670 * Returns true on success, false if the input unit is not recognized.
2672 static bool
2673 convert_to_base_unit(double value, const char *unit,
2674 int base_unit, double *base_value)
2676 char unitstr[MAX_UNIT_LEN + 1];
2677 int unitlen;
2678 const unit_conversion *table;
2679 int i;
2681 /* extract unit string to compare to table entries */
2682 unitlen = 0;
2683 while (*unit != '\0' && !isspace((unsigned char) *unit) &&
2684 unitlen < MAX_UNIT_LEN)
2685 unitstr[unitlen++] = *(unit++);
2686 unitstr[unitlen] = '\0';
2687 /* allow whitespace after unit */
2688 while (isspace((unsigned char) *unit))
2689 unit++;
2690 if (*unit != '\0')
2691 return false; /* unit too long, or garbage after it */
2693 /* now search the appropriate table */
2694 if (base_unit & GUC_UNIT_MEMORY)
2695 table = memory_unit_conversion_table;
2696 else
2697 table = time_unit_conversion_table;
2699 for (i = 0; *table[i].unit; i++)
2701 if (base_unit == table[i].base_unit &&
2702 strcmp(unitstr, table[i].unit) == 0)
2704 double cvalue = value * table[i].multiplier;
2707 * If the user gave a fractional value such as "30.1GB", round it
2708 * off to the nearest multiple of the next smaller unit, if there
2709 * is one.
2711 if (*table[i + 1].unit &&
2712 base_unit == table[i + 1].base_unit)
2713 cvalue = rint(cvalue / table[i + 1].multiplier) *
2714 table[i + 1].multiplier;
2716 *base_value = cvalue;
2717 return true;
2720 return false;
2724 * Convert an integer value in some base unit to a human-friendly unit.
2726 * The output unit is chosen so that it's the greatest unit that can represent
2727 * the value without loss. For example, if the base unit is GUC_UNIT_KB, 1024
2728 * is converted to 1 MB, but 1025 is represented as 1025 kB.
2730 static void
2731 convert_int_from_base_unit(int64 base_value, int base_unit,
2732 int64 *value, const char **unit)
2734 const unit_conversion *table;
2735 int i;
2737 *unit = NULL;
2739 if (base_unit & GUC_UNIT_MEMORY)
2740 table = memory_unit_conversion_table;
2741 else
2742 table = time_unit_conversion_table;
2744 for (i = 0; *table[i].unit; i++)
2746 if (base_unit == table[i].base_unit)
2749 * Accept the first conversion that divides the value evenly. We
2750 * assume that the conversions for each base unit are ordered from
2751 * greatest unit to the smallest!
2753 if (table[i].multiplier <= 1.0 ||
2754 base_value % (int64) table[i].multiplier == 0)
2756 *value = (int64) rint(base_value / table[i].multiplier);
2757 *unit = table[i].unit;
2758 break;
2763 Assert(*unit != NULL);
2767 * Convert a floating-point value in some base unit to a human-friendly unit.
2769 * Same as above, except we have to do the math a bit differently, and
2770 * there's a possibility that we don't find any exact divisor.
2772 static void
2773 convert_real_from_base_unit(double base_value, int base_unit,
2774 double *value, const char **unit)
2776 const unit_conversion *table;
2777 int i;
2779 *unit = NULL;
2781 if (base_unit & GUC_UNIT_MEMORY)
2782 table = memory_unit_conversion_table;
2783 else
2784 table = time_unit_conversion_table;
2786 for (i = 0; *table[i].unit; i++)
2788 if (base_unit == table[i].base_unit)
2791 * Accept the first conversion that divides the value evenly; or
2792 * if there is none, use the smallest (last) target unit.
2794 * What we actually care about here is whether snprintf with "%g"
2795 * will print the value as an integer, so the obvious test of
2796 * "*value == rint(*value)" is too strict; roundoff error might
2797 * make us choose an unreasonably small unit. As a compromise,
2798 * accept a divisor that is within 1e-8 of producing an integer.
2800 *value = base_value / table[i].multiplier;
2801 *unit = table[i].unit;
2802 if (*value > 0 &&
2803 fabs((rint(*value) / *value) - 1.0) <= 1e-8)
2804 break;
2808 Assert(*unit != NULL);
2812 * Return the name of a GUC's base unit (e.g. "ms") given its flags.
2813 * Return NULL if the GUC is unitless.
2815 const char *
2816 get_config_unit_name(int flags)
2818 switch (flags & GUC_UNIT)
2820 case 0:
2821 return NULL; /* GUC has no units */
2822 case GUC_UNIT_BYTE:
2823 return "B";
2824 case GUC_UNIT_KB:
2825 return "kB";
2826 case GUC_UNIT_MB:
2827 return "MB";
2828 case GUC_UNIT_BLOCKS:
2830 static char bbuf[8];
2832 /* initialize if first time through */
2833 if (bbuf[0] == '\0')
2834 snprintf(bbuf, sizeof(bbuf), "%dkB", BLCKSZ / 1024);
2835 return bbuf;
2837 case GUC_UNIT_XBLOCKS:
2839 static char xbuf[8];
2841 /* initialize if first time through */
2842 if (xbuf[0] == '\0')
2843 snprintf(xbuf, sizeof(xbuf), "%dkB", XLOG_BLCKSZ / 1024);
2844 return xbuf;
2846 case GUC_UNIT_MS:
2847 return "ms";
2848 case GUC_UNIT_S:
2849 return "s";
2850 case GUC_UNIT_MIN:
2851 return "min";
2852 default:
2853 elog(ERROR, "unrecognized GUC units value: %d",
2854 flags & GUC_UNIT);
2855 return NULL;
2861 * Try to parse value as an integer. The accepted formats are the
2862 * usual decimal, octal, or hexadecimal formats, as well as floating-point
2863 * formats (which will be rounded to integer after any units conversion).
2864 * Optionally, the value can be followed by a unit name if "flags" indicates
2865 * a unit is allowed.
2867 * If the string parses okay, return true, else false.
2868 * If okay and result is not NULL, return the value in *result.
2869 * If not okay and hintmsg is not NULL, *hintmsg is set to a suitable
2870 * HINT message, or NULL if no hint provided.
2872 bool
2873 parse_int(const char *value, int *result, int flags, const char **hintmsg)
2876 * We assume here that double is wide enough to represent any integer
2877 * value with adequate precision.
2879 double val;
2880 char *endptr;
2882 /* To suppress compiler warnings, always set output params */
2883 if (result)
2884 *result = 0;
2885 if (hintmsg)
2886 *hintmsg = NULL;
2889 * Try to parse as an integer (allowing octal or hex input). If the
2890 * conversion stops at a decimal point or 'e', or overflows, re-parse as
2891 * float. This should work fine as long as we have no unit names starting
2892 * with 'e'. If we ever do, the test could be extended to check for a
2893 * sign or digit after 'e', but for now that's unnecessary.
2895 errno = 0;
2896 val = strtol(value, &endptr, 0);
2897 if (*endptr == '.' || *endptr == 'e' || *endptr == 'E' ||
2898 errno == ERANGE)
2900 errno = 0;
2901 val = strtod(value, &endptr);
2904 if (endptr == value || errno == ERANGE)
2905 return false; /* no HINT for these cases */
2907 /* reject NaN (infinities will fail range check below) */
2908 if (isnan(val))
2909 return false; /* treat same as syntax error; no HINT */
2911 /* allow whitespace between number and unit */
2912 while (isspace((unsigned char) *endptr))
2913 endptr++;
2915 /* Handle possible unit */
2916 if (*endptr != '\0')
2918 if ((flags & GUC_UNIT) == 0)
2919 return false; /* this setting does not accept a unit */
2921 if (!convert_to_base_unit(val,
2922 endptr, (flags & GUC_UNIT),
2923 &val))
2925 /* invalid unit, or garbage after the unit; set hint and fail. */
2926 if (hintmsg)
2928 if (flags & GUC_UNIT_MEMORY)
2929 *hintmsg = memory_units_hint;
2930 else
2931 *hintmsg = time_units_hint;
2933 return false;
2937 /* Round to int, then check for overflow */
2938 val = rint(val);
2940 if (val > INT_MAX || val < INT_MIN)
2942 if (hintmsg)
2943 *hintmsg = gettext_noop("Value exceeds integer range.");
2944 return false;
2947 if (result)
2948 *result = (int) val;
2949 return true;
2953 * Try to parse value as a floating point number in the usual format.
2954 * Optionally, the value can be followed by a unit name if "flags" indicates
2955 * a unit is allowed.
2957 * If the string parses okay, return true, else false.
2958 * If okay and result is not NULL, return the value in *result.
2959 * If not okay and hintmsg is not NULL, *hintmsg is set to a suitable
2960 * HINT message, or NULL if no hint provided.
2962 bool
2963 parse_real(const char *value, double *result, int flags, const char **hintmsg)
2965 double val;
2966 char *endptr;
2968 /* To suppress compiler warnings, always set output params */
2969 if (result)
2970 *result = 0;
2971 if (hintmsg)
2972 *hintmsg = NULL;
2974 errno = 0;
2975 val = strtod(value, &endptr);
2977 if (endptr == value || errno == ERANGE)
2978 return false; /* no HINT for these cases */
2980 /* reject NaN (infinities will fail range checks later) */
2981 if (isnan(val))
2982 return false; /* treat same as syntax error; no HINT */
2984 /* allow whitespace between number and unit */
2985 while (isspace((unsigned char) *endptr))
2986 endptr++;
2988 /* Handle possible unit */
2989 if (*endptr != '\0')
2991 if ((flags & GUC_UNIT) == 0)
2992 return false; /* this setting does not accept a unit */
2994 if (!convert_to_base_unit(val,
2995 endptr, (flags & GUC_UNIT),
2996 &val))
2998 /* invalid unit, or garbage after the unit; set hint and fail. */
2999 if (hintmsg)
3001 if (flags & GUC_UNIT_MEMORY)
3002 *hintmsg = memory_units_hint;
3003 else
3004 *hintmsg = time_units_hint;
3006 return false;
3010 if (result)
3011 *result = val;
3012 return true;
3017 * Lookup the name for an enum option with the selected value.
3018 * Should only ever be called with known-valid values, so throws
3019 * an elog(ERROR) if the enum option is not found.
3021 * The returned string is a pointer to static data and not
3022 * allocated for modification.
3024 const char *
3025 config_enum_lookup_by_value(struct config_enum *record, int val)
3027 const struct config_enum_entry *entry;
3029 for (entry = record->options; entry && entry->name; entry++)
3031 if (entry->val == val)
3032 return entry->name;
3035 elog(ERROR, "could not find enum option %d for %s",
3036 val, record->gen.name);
3037 return NULL; /* silence compiler */
3042 * Lookup the value for an enum option with the selected name
3043 * (case-insensitive).
3044 * If the enum option is found, sets the retval value and returns
3045 * true. If it's not found, return false and retval is set to 0.
3047 bool
3048 config_enum_lookup_by_name(struct config_enum *record, const char *value,
3049 int *retval)
3051 const struct config_enum_entry *entry;
3053 for (entry = record->options; entry && entry->name; entry++)
3055 if (pg_strcasecmp(value, entry->name) == 0)
3057 *retval = entry->val;
3058 return true;
3062 *retval = 0;
3063 return false;
3068 * Return a palloc'd string listing all the available options for an enum GUC
3069 * (excluding hidden ones), separated by the given separator.
3070 * If prefix is non-NULL, it is added before the first enum value.
3071 * If suffix is non-NULL, it is added to the end of the string.
3073 char *
3074 config_enum_get_options(struct config_enum *record, const char *prefix,
3075 const char *suffix, const char *separator)
3077 const struct config_enum_entry *entry;
3078 StringInfoData retstr;
3079 int seplen;
3081 initStringInfo(&retstr);
3082 appendStringInfoString(&retstr, prefix);
3084 seplen = strlen(separator);
3085 for (entry = record->options; entry && entry->name; entry++)
3087 if (!entry->hidden)
3089 appendStringInfoString(&retstr, entry->name);
3090 appendBinaryStringInfo(&retstr, separator, seplen);
3095 * All the entries may have been hidden, leaving the string empty if no
3096 * prefix was given. This indicates a broken GUC setup, since there is no
3097 * use for an enum without any values, so we just check to make sure we
3098 * don't write to invalid memory instead of actually trying to do
3099 * something smart with it.
3101 if (retstr.len >= seplen)
3103 /* Replace final separator */
3104 retstr.data[retstr.len - seplen] = '\0';
3105 retstr.len -= seplen;
3108 appendStringInfoString(&retstr, suffix);
3110 return retstr.data;
3114 * Parse and validate a proposed value for the specified configuration
3115 * parameter.
3117 * This does built-in checks (such as range limits for an integer parameter)
3118 * and also calls any check hook the parameter may have.
3120 * record: GUC variable's info record
3121 * name: variable name (should match the record of course)
3122 * value: proposed value, as a string
3123 * source: identifies source of value (check hooks may need this)
3124 * elevel: level to log any error reports at
3125 * newval: on success, converted parameter value is returned here
3126 * newextra: on success, receives any "extra" data returned by check hook
3127 * (caller must initialize *newextra to NULL)
3129 * Returns true if OK, false if not (or throws error, if elevel >= ERROR)
3131 static bool
3132 parse_and_validate_value(struct config_generic *record,
3133 const char *name, const char *value,
3134 GucSource source, int elevel,
3135 union config_var_val *newval, void **newextra)
3137 switch (record->vartype)
3139 case PGC_BOOL:
3141 struct config_bool *conf = (struct config_bool *) record;
3143 if (!parse_bool(value, &newval->boolval))
3145 ereport(elevel,
3146 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3147 errmsg("parameter \"%s\" requires a Boolean value",
3148 name)));
3149 return false;
3152 if (!call_bool_check_hook(conf, &newval->boolval, newextra,
3153 source, elevel))
3154 return false;
3156 break;
3157 case PGC_INT:
3159 struct config_int *conf = (struct config_int *) record;
3160 const char *hintmsg;
3162 if (!parse_int(value, &newval->intval,
3163 conf->gen.flags, &hintmsg))
3165 ereport(elevel,
3166 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3167 errmsg("invalid value for parameter \"%s\": \"%s\"",
3168 name, value),
3169 hintmsg ? errhint("%s", _(hintmsg)) : 0));
3170 return false;
3173 if (newval->intval < conf->min || newval->intval > conf->max)
3175 const char *unit = get_config_unit_name(conf->gen.flags);
3176 const char *unitspace;
3178 if (unit)
3179 unitspace = " ";
3180 else
3181 unit = unitspace = "";
3183 ereport(elevel,
3184 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3185 errmsg("%d%s%s is outside the valid range for parameter \"%s\" (%d%s%s .. %d%s%s)",
3186 newval->intval, unitspace, unit,
3187 name,
3188 conf->min, unitspace, unit,
3189 conf->max, unitspace, unit)));
3190 return false;
3193 if (!call_int_check_hook(conf, &newval->intval, newextra,
3194 source, elevel))
3195 return false;
3197 break;
3198 case PGC_REAL:
3200 struct config_real *conf = (struct config_real *) record;
3201 const char *hintmsg;
3203 if (!parse_real(value, &newval->realval,
3204 conf->gen.flags, &hintmsg))
3206 ereport(elevel,
3207 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3208 errmsg("invalid value for parameter \"%s\": \"%s\"",
3209 name, value),
3210 hintmsg ? errhint("%s", _(hintmsg)) : 0));
3211 return false;
3214 if (newval->realval < conf->min || newval->realval > conf->max)
3216 const char *unit = get_config_unit_name(conf->gen.flags);
3217 const char *unitspace;
3219 if (unit)
3220 unitspace = " ";
3221 else
3222 unit = unitspace = "";
3224 ereport(elevel,
3225 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3226 errmsg("%g%s%s is outside the valid range for parameter \"%s\" (%g%s%s .. %g%s%s)",
3227 newval->realval, unitspace, unit,
3228 name,
3229 conf->min, unitspace, unit,
3230 conf->max, unitspace, unit)));
3231 return false;
3234 if (!call_real_check_hook(conf, &newval->realval, newextra,
3235 source, elevel))
3236 return false;
3238 break;
3239 case PGC_STRING:
3241 struct config_string *conf = (struct config_string *) record;
3244 * The value passed by the caller could be transient, so we
3245 * always strdup it.
3247 newval->stringval = guc_strdup(elevel, value);
3248 if (newval->stringval == NULL)
3249 return false;
3252 * The only built-in "parsing" check we have is to apply
3253 * truncation if GUC_IS_NAME.
3255 if (conf->gen.flags & GUC_IS_NAME)
3256 truncate_identifier(newval->stringval,
3257 strlen(newval->stringval),
3258 true);
3260 if (!call_string_check_hook(conf, &newval->stringval, newextra,
3261 source, elevel))
3263 guc_free(newval->stringval);
3264 newval->stringval = NULL;
3265 return false;
3268 break;
3269 case PGC_ENUM:
3271 struct config_enum *conf = (struct config_enum *) record;
3273 if (!config_enum_lookup_by_name(conf, value, &newval->enumval))
3275 char *hintmsg;
3277 hintmsg = config_enum_get_options(conf,
3278 "Available values: ",
3279 ".", ", ");
3281 ereport(elevel,
3282 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3283 errmsg("invalid value for parameter \"%s\": \"%s\"",
3284 name, value),
3285 hintmsg ? errhint("%s", _(hintmsg)) : 0));
3287 if (hintmsg)
3288 pfree(hintmsg);
3289 return false;
3292 if (!call_enum_check_hook(conf, &newval->enumval, newextra,
3293 source, elevel))
3294 return false;
3296 break;
3299 return true;
3304 * set_config_option: sets option `name' to given value.
3306 * The value should be a string, which will be parsed and converted to
3307 * the appropriate data type. The context and source parameters indicate
3308 * in which context this function is being called, so that it can apply the
3309 * access restrictions properly.
3311 * If value is NULL, set the option to its default value (normally the
3312 * reset_val, but if source == PGC_S_DEFAULT we instead use the boot_val).
3314 * action indicates whether to set the value globally in the session, locally
3315 * to the current top transaction, or just for the duration of a function call.
3317 * If changeVal is false then don't really set the option but do all
3318 * the checks to see if it would work.
3320 * elevel should normally be passed as zero, allowing this function to make
3321 * its standard choice of ereport level. However some callers need to be
3322 * able to override that choice; they should pass the ereport level to use.
3324 * is_reload should be true only when called from read_nondefault_variables()
3325 * or RestoreGUCState(), where we are trying to load some other process's
3326 * GUC settings into a new process.
3328 * Return value:
3329 * +1: the value is valid and was successfully applied.
3330 * 0: the name or value is invalid, or it's invalid to try to set
3331 * this GUC now; but elevel was less than ERROR (see below).
3332 * -1: no error detected, but the value was not applied, either
3333 * because changeVal is false or there is some overriding setting.
3335 * If there is an error (non-existing option, invalid value, etc) then an
3336 * ereport(ERROR) is thrown *unless* this is called for a source for which
3337 * we don't want an ERROR (currently, those are defaults, the config file,
3338 * and per-database or per-user settings, as well as callers who specify
3339 * a less-than-ERROR elevel). In those cases we write a suitable error
3340 * message via ereport() and return 0.
3342 * See also SetConfigOption for an external interface.
3345 set_config_option(const char *name, const char *value,
3346 GucContext context, GucSource source,
3347 GucAction action, bool changeVal, int elevel,
3348 bool is_reload)
3350 Oid srole;
3353 * Non-interactive sources should be treated as having all privileges,
3354 * except for PGC_S_CLIENT. Note in particular that this is true for
3355 * pg_db_role_setting sources (PGC_S_GLOBAL etc): we assume a suitable
3356 * privilege check was done when the pg_db_role_setting entry was made.
3358 if (source >= PGC_S_INTERACTIVE || source == PGC_S_CLIENT)
3359 srole = GetUserId();
3360 else
3361 srole = BOOTSTRAP_SUPERUSERID;
3363 return set_config_with_handle(name, NULL, value,
3364 context, source, srole,
3365 action, changeVal, elevel,
3366 is_reload);
3370 * set_config_option_ext: sets option `name' to given value.
3372 * This API adds the ability to explicitly specify which role OID
3373 * is considered to be setting the value. Most external callers can use
3374 * set_config_option() and let it determine that based on the GucSource,
3375 * but there are a few that are supplying a value that was determined
3376 * in some special way and need to override the decision. Also, when
3377 * restoring a previously-assigned value, it's important to supply the
3378 * same role OID that set the value originally; so all guc.c callers
3379 * that are doing that type of thing need to call this directly.
3381 * Generally, srole should be GetUserId() when the source is a SQL operation,
3382 * or BOOTSTRAP_SUPERUSERID if the source is a config file or similar.
3385 set_config_option_ext(const char *name, const char *value,
3386 GucContext context, GucSource source, Oid srole,
3387 GucAction action, bool changeVal, int elevel,
3388 bool is_reload)
3390 return set_config_with_handle(name, NULL, value,
3391 context, source, srole,
3392 action, changeVal, elevel,
3393 is_reload);
3398 * set_config_with_handle: sets option `name' to given value.
3400 * This API adds the ability to pass a 'handle' argument, which can be
3401 * obtained by the caller from get_config_handle(). NULL has no effect,
3402 * but a non-null value avoids the need to search the GUC tables.
3404 * This should be used by callers which repeatedly set the same config
3405 * option(s), and want to avoid the overhead of a hash lookup each time.
3408 set_config_with_handle(const char *name, config_handle *handle,
3409 const char *value,
3410 GucContext context, GucSource source, Oid srole,
3411 GucAction action, bool changeVal, int elevel,
3412 bool is_reload)
3414 struct config_generic *record;
3415 union config_var_val newval_union;
3416 void *newextra = NULL;
3417 bool prohibitValueChange = false;
3418 bool makeDefault;
3420 if (elevel == 0)
3422 if (source == PGC_S_DEFAULT || source == PGC_S_FILE)
3425 * To avoid cluttering the log, only the postmaster bleats loudly
3426 * about problems with the config file.
3428 elevel = IsUnderPostmaster ? DEBUG3 : LOG;
3430 else if (source == PGC_S_GLOBAL ||
3431 source == PGC_S_DATABASE ||
3432 source == PGC_S_USER ||
3433 source == PGC_S_DATABASE_USER)
3434 elevel = WARNING;
3435 else
3436 elevel = ERROR;
3439 /* if handle is specified, no need to look up option */
3440 if (!handle)
3442 record = find_option(name, true, false, elevel);
3443 if (record == NULL)
3444 return 0;
3446 else
3447 record = handle;
3450 * GUC_ACTION_SAVE changes are acceptable during a parallel operation,
3451 * because the current worker will also pop the change. We're probably
3452 * dealing with a function having a proconfig entry. Only the function's
3453 * body should observe the change, and peer workers do not share in the
3454 * execution of a function call started by this worker.
3456 * Also allow normal setting if the GUC is marked GUC_ALLOW_IN_PARALLEL.
3458 * Other changes might need to affect other workers, so forbid them.
3460 if (IsInParallelMode() && changeVal && action != GUC_ACTION_SAVE &&
3461 (record->flags & GUC_ALLOW_IN_PARALLEL) == 0)
3463 ereport(elevel,
3464 (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
3465 errmsg("parameter \"%s\" cannot be set during a parallel operation",
3466 name)));
3467 return 0;
3471 * Check if the option can be set at this time. See guc.h for the precise
3472 * rules.
3474 switch (record->context)
3476 case PGC_INTERNAL:
3477 if (context != PGC_INTERNAL)
3479 ereport(elevel,
3480 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
3481 errmsg("parameter \"%s\" cannot be changed",
3482 name)));
3483 return 0;
3485 break;
3486 case PGC_POSTMASTER:
3487 if (context == PGC_SIGHUP)
3490 * We are re-reading a PGC_POSTMASTER variable from
3491 * postgresql.conf. We can't change the setting, so we should
3492 * give a warning if the DBA tries to change it. However,
3493 * because of variant formats, canonicalization by check
3494 * hooks, etc, we can't just compare the given string directly
3495 * to what's stored. Set a flag to check below after we have
3496 * the final storable value.
3498 prohibitValueChange = true;
3500 else if (context != PGC_POSTMASTER)
3502 ereport(elevel,
3503 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
3504 errmsg("parameter \"%s\" cannot be changed without restarting the server",
3505 name)));
3506 return 0;
3508 break;
3509 case PGC_SIGHUP:
3510 if (context != PGC_SIGHUP && context != PGC_POSTMASTER)
3512 ereport(elevel,
3513 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
3514 errmsg("parameter \"%s\" cannot be changed now",
3515 name)));
3516 return 0;
3520 * Hmm, the idea of the SIGHUP context is "ought to be global, but
3521 * can be changed after postmaster start". But there's nothing
3522 * that prevents a crafty administrator from sending SIGHUP
3523 * signals to individual backends only.
3525 break;
3526 case PGC_SU_BACKEND:
3527 if (context == PGC_BACKEND)
3530 * Check whether the requesting user has been granted
3531 * privilege to set this GUC.
3533 AclResult aclresult;
3535 aclresult = pg_parameter_aclcheck(name, srole, ACL_SET);
3536 if (aclresult != ACLCHECK_OK)
3538 /* No granted privilege */
3539 ereport(elevel,
3540 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3541 errmsg("permission denied to set parameter \"%s\"",
3542 name)));
3543 return 0;
3546 /* fall through to process the same as PGC_BACKEND */
3547 /* FALLTHROUGH */
3548 case PGC_BACKEND:
3549 if (context == PGC_SIGHUP)
3552 * If a PGC_BACKEND or PGC_SU_BACKEND parameter is changed in
3553 * the config file, we want to accept the new value in the
3554 * postmaster (whence it will propagate to
3555 * subsequently-started backends), but ignore it in existing
3556 * backends. This is a tad klugy, but necessary because we
3557 * don't re-read the config file during backend start.
3559 * However, if changeVal is false then plow ahead anyway since
3560 * we are trying to find out if the value is potentially good,
3561 * not actually use it.
3563 * In EXEC_BACKEND builds, this works differently: we load all
3564 * non-default settings from the CONFIG_EXEC_PARAMS file
3565 * during backend start. In that case we must accept
3566 * PGC_SIGHUP settings, so as to have the same value as if
3567 * we'd forked from the postmaster. This can also happen when
3568 * using RestoreGUCState() within a background worker that
3569 * needs to have the same settings as the user backend that
3570 * started it. is_reload will be true when either situation
3571 * applies.
3573 if (IsUnderPostmaster && changeVal && !is_reload)
3574 return -1;
3576 else if (context != PGC_POSTMASTER &&
3577 context != PGC_BACKEND &&
3578 context != PGC_SU_BACKEND &&
3579 source != PGC_S_CLIENT)
3581 ereport(elevel,
3582 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
3583 errmsg("parameter \"%s\" cannot be set after connection start",
3584 name)));
3585 return 0;
3587 break;
3588 case PGC_SUSET:
3589 if (context == PGC_USERSET || context == PGC_BACKEND)
3592 * Check whether the requesting user has been granted
3593 * privilege to set this GUC.
3595 AclResult aclresult;
3597 aclresult = pg_parameter_aclcheck(name, srole, ACL_SET);
3598 if (aclresult != ACLCHECK_OK)
3600 /* No granted privilege */
3601 ereport(elevel,
3602 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3603 errmsg("permission denied to set parameter \"%s\"",
3604 name)));
3605 return 0;
3608 break;
3609 case PGC_USERSET:
3610 /* always okay */
3611 break;
3615 * Disallow changing GUC_NOT_WHILE_SEC_REST values if we are inside a
3616 * security restriction context. We can reject this regardless of the GUC
3617 * context or source, mainly because sources that it might be reasonable
3618 * to override for won't be seen while inside a function.
3620 * Note: variables marked GUC_NOT_WHILE_SEC_REST should usually be marked
3621 * GUC_NO_RESET_ALL as well, because ResetAllOptions() doesn't check this.
3622 * An exception might be made if the reset value is assumed to be "safe".
3624 * Note: this flag is currently used for "session_authorization" and
3625 * "role". We need to prohibit changing these inside a local userid
3626 * context because when we exit it, GUC won't be notified, leaving things
3627 * out of sync. (This could be fixed by forcing a new GUC nesting level,
3628 * but that would change behavior in possibly-undesirable ways.) Also, we
3629 * prohibit changing these in a security-restricted operation because
3630 * otherwise RESET could be used to regain the session user's privileges.
3632 if (record->flags & GUC_NOT_WHILE_SEC_REST)
3634 if (InLocalUserIdChange())
3637 * Phrasing of this error message is historical, but it's the most
3638 * common case.
3640 ereport(elevel,
3641 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3642 errmsg("cannot set parameter \"%s\" within security-definer function",
3643 name)));
3644 return 0;
3646 if (InSecurityRestrictedOperation())
3648 ereport(elevel,
3649 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3650 errmsg("cannot set parameter \"%s\" within security-restricted operation",
3651 name)));
3652 return 0;
3656 /* Disallow resetting and saving GUC_NO_RESET values */
3657 if (record->flags & GUC_NO_RESET)
3659 if (value == NULL)
3661 ereport(elevel,
3662 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3663 errmsg("parameter \"%s\" cannot be reset", name)));
3664 return 0;
3666 if (action == GUC_ACTION_SAVE)
3668 ereport(elevel,
3669 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3670 errmsg("parameter \"%s\" cannot be set locally in functions",
3671 name)));
3672 return 0;
3677 * Should we set reset/stacked values? (If so, the behavior is not
3678 * transactional.) This is done either when we get a default value from
3679 * the database's/user's/client's default settings or when we reset a
3680 * value to its default.
3682 makeDefault = changeVal && (source <= PGC_S_OVERRIDE) &&
3683 ((value != NULL) || source == PGC_S_DEFAULT);
3686 * Ignore attempted set if overridden by previously processed setting.
3687 * However, if changeVal is false then plow ahead anyway since we are
3688 * trying to find out if the value is potentially good, not actually use
3689 * it. Also keep going if makeDefault is true, since we may want to set
3690 * the reset/stacked values even if we can't set the variable itself.
3692 if (record->source > source)
3694 if (changeVal && !makeDefault)
3696 elog(DEBUG3, "\"%s\": setting ignored because previous source is higher priority",
3697 name);
3698 return -1;
3700 changeVal = false;
3704 * Evaluate value and set variable.
3706 switch (record->vartype)
3708 case PGC_BOOL:
3710 struct config_bool *conf = (struct config_bool *) record;
3712 #define newval (newval_union.boolval)
3714 if (value)
3716 if (!parse_and_validate_value(record, name, value,
3717 source, elevel,
3718 &newval_union, &newextra))
3719 return 0;
3721 else if (source == PGC_S_DEFAULT)
3723 newval = conf->boot_val;
3724 if (!call_bool_check_hook(conf, &newval, &newextra,
3725 source, elevel))
3726 return 0;
3728 else
3730 newval = conf->reset_val;
3731 newextra = conf->reset_extra;
3732 source = conf->gen.reset_source;
3733 context = conf->gen.reset_scontext;
3734 srole = conf->gen.reset_srole;
3737 if (prohibitValueChange)
3739 /* Release newextra, unless it's reset_extra */
3740 if (newextra && !extra_field_used(&conf->gen, newextra))
3741 guc_free(newextra);
3743 if (*conf->variable != newval)
3745 record->status |= GUC_PENDING_RESTART;
3746 ereport(elevel,
3747 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
3748 errmsg("parameter \"%s\" cannot be changed without restarting the server",
3749 name)));
3750 return 0;
3752 record->status &= ~GUC_PENDING_RESTART;
3753 return -1;
3756 if (changeVal)
3758 /* Save old value to support transaction abort */
3759 if (!makeDefault)
3760 push_old_value(&conf->gen, action);
3762 if (conf->assign_hook)
3763 conf->assign_hook(newval, newextra);
3764 *conf->variable = newval;
3765 set_extra_field(&conf->gen, &conf->gen.extra,
3766 newextra);
3767 set_guc_source(&conf->gen, source);
3768 conf->gen.scontext = context;
3769 conf->gen.srole = srole;
3771 if (makeDefault)
3773 GucStack *stack;
3775 if (conf->gen.reset_source <= source)
3777 conf->reset_val = newval;
3778 set_extra_field(&conf->gen, &conf->reset_extra,
3779 newextra);
3780 conf->gen.reset_source = source;
3781 conf->gen.reset_scontext = context;
3782 conf->gen.reset_srole = srole;
3784 for (stack = conf->gen.stack; stack; stack = stack->prev)
3786 if (stack->source <= source)
3788 stack->prior.val.boolval = newval;
3789 set_extra_field(&conf->gen, &stack->prior.extra,
3790 newextra);
3791 stack->source = source;
3792 stack->scontext = context;
3793 stack->srole = srole;
3798 /* Perhaps we didn't install newextra anywhere */
3799 if (newextra && !extra_field_used(&conf->gen, newextra))
3800 guc_free(newextra);
3801 break;
3803 #undef newval
3806 case PGC_INT:
3808 struct config_int *conf = (struct config_int *) record;
3810 #define newval (newval_union.intval)
3812 if (value)
3814 if (!parse_and_validate_value(record, name, value,
3815 source, elevel,
3816 &newval_union, &newextra))
3817 return 0;
3819 else if (source == PGC_S_DEFAULT)
3821 newval = conf->boot_val;
3822 if (!call_int_check_hook(conf, &newval, &newextra,
3823 source, elevel))
3824 return 0;
3826 else
3828 newval = conf->reset_val;
3829 newextra = conf->reset_extra;
3830 source = conf->gen.reset_source;
3831 context = conf->gen.reset_scontext;
3832 srole = conf->gen.reset_srole;
3835 if (prohibitValueChange)
3837 /* Release newextra, unless it's reset_extra */
3838 if (newextra && !extra_field_used(&conf->gen, newextra))
3839 guc_free(newextra);
3841 if (*conf->variable != newval)
3843 record->status |= GUC_PENDING_RESTART;
3844 ereport(elevel,
3845 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
3846 errmsg("parameter \"%s\" cannot be changed without restarting the server",
3847 name)));
3848 return 0;
3850 record->status &= ~GUC_PENDING_RESTART;
3851 return -1;
3854 if (changeVal)
3856 /* Save old value to support transaction abort */
3857 if (!makeDefault)
3858 push_old_value(&conf->gen, action);
3860 if (conf->assign_hook)
3861 conf->assign_hook(newval, newextra);
3862 *conf->variable = newval;
3863 set_extra_field(&conf->gen, &conf->gen.extra,
3864 newextra);
3865 set_guc_source(&conf->gen, source);
3866 conf->gen.scontext = context;
3867 conf->gen.srole = srole;
3869 if (makeDefault)
3871 GucStack *stack;
3873 if (conf->gen.reset_source <= source)
3875 conf->reset_val = newval;
3876 set_extra_field(&conf->gen, &conf->reset_extra,
3877 newextra);
3878 conf->gen.reset_source = source;
3879 conf->gen.reset_scontext = context;
3880 conf->gen.reset_srole = srole;
3882 for (stack = conf->gen.stack; stack; stack = stack->prev)
3884 if (stack->source <= source)
3886 stack->prior.val.intval = newval;
3887 set_extra_field(&conf->gen, &stack->prior.extra,
3888 newextra);
3889 stack->source = source;
3890 stack->scontext = context;
3891 stack->srole = srole;
3896 /* Perhaps we didn't install newextra anywhere */
3897 if (newextra && !extra_field_used(&conf->gen, newextra))
3898 guc_free(newextra);
3899 break;
3901 #undef newval
3904 case PGC_REAL:
3906 struct config_real *conf = (struct config_real *) record;
3908 #define newval (newval_union.realval)
3910 if (value)
3912 if (!parse_and_validate_value(record, name, value,
3913 source, elevel,
3914 &newval_union, &newextra))
3915 return 0;
3917 else if (source == PGC_S_DEFAULT)
3919 newval = conf->boot_val;
3920 if (!call_real_check_hook(conf, &newval, &newextra,
3921 source, elevel))
3922 return 0;
3924 else
3926 newval = conf->reset_val;
3927 newextra = conf->reset_extra;
3928 source = conf->gen.reset_source;
3929 context = conf->gen.reset_scontext;
3930 srole = conf->gen.reset_srole;
3933 if (prohibitValueChange)
3935 /* Release newextra, unless it's reset_extra */
3936 if (newextra && !extra_field_used(&conf->gen, newextra))
3937 guc_free(newextra);
3939 if (*conf->variable != newval)
3941 record->status |= GUC_PENDING_RESTART;
3942 ereport(elevel,
3943 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
3944 errmsg("parameter \"%s\" cannot be changed without restarting the server",
3945 name)));
3946 return 0;
3948 record->status &= ~GUC_PENDING_RESTART;
3949 return -1;
3952 if (changeVal)
3954 /* Save old value to support transaction abort */
3955 if (!makeDefault)
3956 push_old_value(&conf->gen, action);
3958 if (conf->assign_hook)
3959 conf->assign_hook(newval, newextra);
3960 *conf->variable = newval;
3961 set_extra_field(&conf->gen, &conf->gen.extra,
3962 newextra);
3963 set_guc_source(&conf->gen, source);
3964 conf->gen.scontext = context;
3965 conf->gen.srole = srole;
3967 if (makeDefault)
3969 GucStack *stack;
3971 if (conf->gen.reset_source <= source)
3973 conf->reset_val = newval;
3974 set_extra_field(&conf->gen, &conf->reset_extra,
3975 newextra);
3976 conf->gen.reset_source = source;
3977 conf->gen.reset_scontext = context;
3978 conf->gen.reset_srole = srole;
3980 for (stack = conf->gen.stack; stack; stack = stack->prev)
3982 if (stack->source <= source)
3984 stack->prior.val.realval = newval;
3985 set_extra_field(&conf->gen, &stack->prior.extra,
3986 newextra);
3987 stack->source = source;
3988 stack->scontext = context;
3989 stack->srole = srole;
3994 /* Perhaps we didn't install newextra anywhere */
3995 if (newextra && !extra_field_used(&conf->gen, newextra))
3996 guc_free(newextra);
3997 break;
3999 #undef newval
4002 case PGC_STRING:
4004 struct config_string *conf = (struct config_string *) record;
4006 #define newval (newval_union.stringval)
4008 if (value)
4010 if (!parse_and_validate_value(record, name, value,
4011 source, elevel,
4012 &newval_union, &newextra))
4013 return 0;
4015 else if (source == PGC_S_DEFAULT)
4017 /* non-NULL boot_val must always get strdup'd */
4018 if (conf->boot_val != NULL)
4020 newval = guc_strdup(elevel, conf->boot_val);
4021 if (newval == NULL)
4022 return 0;
4024 else
4025 newval = NULL;
4027 if (!call_string_check_hook(conf, &newval, &newextra,
4028 source, elevel))
4030 guc_free(newval);
4031 return 0;
4034 else
4037 * strdup not needed, since reset_val is already under
4038 * guc.c's control
4040 newval = conf->reset_val;
4041 newextra = conf->reset_extra;
4042 source = conf->gen.reset_source;
4043 context = conf->gen.reset_scontext;
4044 srole = conf->gen.reset_srole;
4047 if (prohibitValueChange)
4049 bool newval_different;
4051 /* newval shouldn't be NULL, so we're a bit sloppy here */
4052 newval_different = (*conf->variable == NULL ||
4053 newval == NULL ||
4054 strcmp(*conf->variable, newval) != 0);
4056 /* Release newval, unless it's reset_val */
4057 if (newval && !string_field_used(conf, newval))
4058 guc_free(newval);
4059 /* Release newextra, unless it's reset_extra */
4060 if (newextra && !extra_field_used(&conf->gen, newextra))
4061 guc_free(newextra);
4063 if (newval_different)
4065 record->status |= GUC_PENDING_RESTART;
4066 ereport(elevel,
4067 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
4068 errmsg("parameter \"%s\" cannot be changed without restarting the server",
4069 name)));
4070 return 0;
4072 record->status &= ~GUC_PENDING_RESTART;
4073 return -1;
4076 if (changeVal)
4078 /* Save old value to support transaction abort */
4079 if (!makeDefault)
4080 push_old_value(&conf->gen, action);
4082 if (conf->assign_hook)
4083 conf->assign_hook(newval, newextra);
4084 set_string_field(conf, conf->variable, newval);
4085 set_extra_field(&conf->gen, &conf->gen.extra,
4086 newextra);
4087 set_guc_source(&conf->gen, source);
4088 conf->gen.scontext = context;
4089 conf->gen.srole = srole;
4092 if (makeDefault)
4094 GucStack *stack;
4096 if (conf->gen.reset_source <= source)
4098 set_string_field(conf, &conf->reset_val, newval);
4099 set_extra_field(&conf->gen, &conf->reset_extra,
4100 newextra);
4101 conf->gen.reset_source = source;
4102 conf->gen.reset_scontext = context;
4103 conf->gen.reset_srole = srole;
4105 for (stack = conf->gen.stack; stack; stack = stack->prev)
4107 if (stack->source <= source)
4109 set_string_field(conf, &stack->prior.val.stringval,
4110 newval);
4111 set_extra_field(&conf->gen, &stack->prior.extra,
4112 newextra);
4113 stack->source = source;
4114 stack->scontext = context;
4115 stack->srole = srole;
4120 /* Perhaps we didn't install newval anywhere */
4121 if (newval && !string_field_used(conf, newval))
4122 guc_free(newval);
4123 /* Perhaps we didn't install newextra anywhere */
4124 if (newextra && !extra_field_used(&conf->gen, newextra))
4125 guc_free(newextra);
4126 break;
4128 #undef newval
4131 case PGC_ENUM:
4133 struct config_enum *conf = (struct config_enum *) record;
4135 #define newval (newval_union.enumval)
4137 if (value)
4139 if (!parse_and_validate_value(record, name, value,
4140 source, elevel,
4141 &newval_union, &newextra))
4142 return 0;
4144 else if (source == PGC_S_DEFAULT)
4146 newval = conf->boot_val;
4147 if (!call_enum_check_hook(conf, &newval, &newextra,
4148 source, elevel))
4149 return 0;
4151 else
4153 newval = conf->reset_val;
4154 newextra = conf->reset_extra;
4155 source = conf->gen.reset_source;
4156 context = conf->gen.reset_scontext;
4157 srole = conf->gen.reset_srole;
4160 if (prohibitValueChange)
4162 /* Release newextra, unless it's reset_extra */
4163 if (newextra && !extra_field_used(&conf->gen, newextra))
4164 guc_free(newextra);
4166 if (*conf->variable != newval)
4168 record->status |= GUC_PENDING_RESTART;
4169 ereport(elevel,
4170 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
4171 errmsg("parameter \"%s\" cannot be changed without restarting the server",
4172 name)));
4173 return 0;
4175 record->status &= ~GUC_PENDING_RESTART;
4176 return -1;
4179 if (changeVal)
4181 /* Save old value to support transaction abort */
4182 if (!makeDefault)
4183 push_old_value(&conf->gen, action);
4185 if (conf->assign_hook)
4186 conf->assign_hook(newval, newextra);
4187 *conf->variable = newval;
4188 set_extra_field(&conf->gen, &conf->gen.extra,
4189 newextra);
4190 set_guc_source(&conf->gen, source);
4191 conf->gen.scontext = context;
4192 conf->gen.srole = srole;
4194 if (makeDefault)
4196 GucStack *stack;
4198 if (conf->gen.reset_source <= source)
4200 conf->reset_val = newval;
4201 set_extra_field(&conf->gen, &conf->reset_extra,
4202 newextra);
4203 conf->gen.reset_source = source;
4204 conf->gen.reset_scontext = context;
4205 conf->gen.reset_srole = srole;
4207 for (stack = conf->gen.stack; stack; stack = stack->prev)
4209 if (stack->source <= source)
4211 stack->prior.val.enumval = newval;
4212 set_extra_field(&conf->gen, &stack->prior.extra,
4213 newextra);
4214 stack->source = source;
4215 stack->scontext = context;
4216 stack->srole = srole;
4221 /* Perhaps we didn't install newextra anywhere */
4222 if (newextra && !extra_field_used(&conf->gen, newextra))
4223 guc_free(newextra);
4224 break;
4226 #undef newval
4230 if (changeVal && (record->flags & GUC_REPORT) &&
4231 !(record->status & GUC_NEEDS_REPORT))
4233 record->status |= GUC_NEEDS_REPORT;
4234 slist_push_head(&guc_report_list, &record->report_link);
4237 return changeVal ? 1 : -1;
4242 * Retrieve a config_handle for the given name, suitable for calling
4243 * set_config_with_handle(). Only return handle to permanent GUC.
4245 config_handle *
4246 get_config_handle(const char *name)
4248 struct config_generic *gen = find_option(name, false, false, 0);
4250 if (gen && ((gen->flags & GUC_CUSTOM_PLACEHOLDER) == 0))
4251 return gen;
4253 return NULL;
4258 * Set the fields for source file and line number the setting came from.
4260 static void
4261 set_config_sourcefile(const char *name, char *sourcefile, int sourceline)
4263 struct config_generic *record;
4264 int elevel;
4267 * To avoid cluttering the log, only the postmaster bleats loudly about
4268 * problems with the config file.
4270 elevel = IsUnderPostmaster ? DEBUG3 : LOG;
4272 record = find_option(name, true, false, elevel);
4273 /* should not happen */
4274 if (record == NULL)
4275 return;
4277 sourcefile = guc_strdup(elevel, sourcefile);
4278 guc_free(record->sourcefile);
4279 record->sourcefile = sourcefile;
4280 record->sourceline = sourceline;
4284 * Set a config option to the given value.
4286 * See also set_config_option; this is just the wrapper to be called from
4287 * outside GUC. (This function should be used when possible, because its API
4288 * is more stable than set_config_option's.)
4290 * Note: there is no support here for setting source file/line, as it
4291 * is currently not needed.
4293 void
4294 SetConfigOption(const char *name, const char *value,
4295 GucContext context, GucSource source)
4297 (void) set_config_option(name, value, context, source,
4298 GUC_ACTION_SET, true, 0, false);
4304 * Fetch the current value of the option `name', as a string.
4306 * If the option doesn't exist, return NULL if missing_ok is true,
4307 * otherwise throw an ereport and don't return.
4309 * If restrict_privileged is true, we also enforce that only superusers and
4310 * members of the pg_read_all_settings role can see GUC_SUPERUSER_ONLY
4311 * variables. This should only be passed as true in user-driven calls.
4313 * The string is *not* allocated for modification and is really only
4314 * valid until the next call to configuration related functions.
4316 const char *
4317 GetConfigOption(const char *name, bool missing_ok, bool restrict_privileged)
4319 struct config_generic *record;
4320 static char buffer[256];
4322 record = find_option(name, false, missing_ok, ERROR);
4323 if (record == NULL)
4324 return NULL;
4325 if (restrict_privileged &&
4326 !ConfigOptionIsVisible(record))
4327 ereport(ERROR,
4328 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
4329 errmsg("permission denied to examine \"%s\"", name),
4330 errdetail("Only roles with privileges of the \"%s\" role may examine this parameter.",
4331 "pg_read_all_settings")));
4333 switch (record->vartype)
4335 case PGC_BOOL:
4336 return *((struct config_bool *) record)->variable ? "on" : "off";
4338 case PGC_INT:
4339 snprintf(buffer, sizeof(buffer), "%d",
4340 *((struct config_int *) record)->variable);
4341 return buffer;
4343 case PGC_REAL:
4344 snprintf(buffer, sizeof(buffer), "%g",
4345 *((struct config_real *) record)->variable);
4346 return buffer;
4348 case PGC_STRING:
4349 return *((struct config_string *) record)->variable ?
4350 *((struct config_string *) record)->variable : "";
4352 case PGC_ENUM:
4353 return config_enum_lookup_by_value((struct config_enum *) record,
4354 *((struct config_enum *) record)->variable);
4356 return NULL;
4360 * Get the RESET value associated with the given option.
4362 * Note: this is not re-entrant, due to use of static result buffer;
4363 * not to mention that a string variable could have its reset_val changed.
4364 * Beware of assuming the result value is good for very long.
4366 const char *
4367 GetConfigOptionResetString(const char *name)
4369 struct config_generic *record;
4370 static char buffer[256];
4372 record = find_option(name, false, false, ERROR);
4373 Assert(record != NULL);
4374 if (!ConfigOptionIsVisible(record))
4375 ereport(ERROR,
4376 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
4377 errmsg("permission denied to examine \"%s\"", name),
4378 errdetail("Only roles with privileges of the \"%s\" role may examine this parameter.",
4379 "pg_read_all_settings")));
4381 switch (record->vartype)
4383 case PGC_BOOL:
4384 return ((struct config_bool *) record)->reset_val ? "on" : "off";
4386 case PGC_INT:
4387 snprintf(buffer, sizeof(buffer), "%d",
4388 ((struct config_int *) record)->reset_val);
4389 return buffer;
4391 case PGC_REAL:
4392 snprintf(buffer, sizeof(buffer), "%g",
4393 ((struct config_real *) record)->reset_val);
4394 return buffer;
4396 case PGC_STRING:
4397 return ((struct config_string *) record)->reset_val ?
4398 ((struct config_string *) record)->reset_val : "";
4400 case PGC_ENUM:
4401 return config_enum_lookup_by_value((struct config_enum *) record,
4402 ((struct config_enum *) record)->reset_val);
4404 return NULL;
4408 * Get the GUC flags associated with the given option.
4410 * If the option doesn't exist, return 0 if missing_ok is true,
4411 * otherwise throw an ereport and don't return.
4414 GetConfigOptionFlags(const char *name, bool missing_ok)
4416 struct config_generic *record;
4418 record = find_option(name, false, missing_ok, ERROR);
4419 if (record == NULL)
4420 return 0;
4421 return record->flags;
4426 * Write updated configuration parameter values into a temporary file.
4427 * This function traverses the list of parameters and quotes the string
4428 * values before writing them.
4430 static void
4431 write_auto_conf_file(int fd, const char *filename, ConfigVariable *head)
4433 StringInfoData buf;
4434 ConfigVariable *item;
4436 initStringInfo(&buf);
4438 /* Emit file header containing warning comment */
4439 appendStringInfoString(&buf, "# Do not edit this file manually!\n");
4440 appendStringInfoString(&buf, "# It will be overwritten by the ALTER SYSTEM command.\n");
4442 errno = 0;
4443 if (write(fd, buf.data, buf.len) != buf.len)
4445 /* if write didn't set errno, assume problem is no disk space */
4446 if (errno == 0)
4447 errno = ENOSPC;
4448 ereport(ERROR,
4449 (errcode_for_file_access(),
4450 errmsg("could not write to file \"%s\": %m", filename)));
4453 /* Emit each parameter, properly quoting the value */
4454 for (item = head; item != NULL; item = item->next)
4456 char *escaped;
4458 resetStringInfo(&buf);
4460 appendStringInfoString(&buf, item->name);
4461 appendStringInfoString(&buf, " = '");
4463 escaped = escape_single_quotes_ascii(item->value);
4464 if (!escaped)
4465 ereport(ERROR,
4466 (errcode(ERRCODE_OUT_OF_MEMORY),
4467 errmsg("out of memory")));
4468 appendStringInfoString(&buf, escaped);
4469 free(escaped);
4471 appendStringInfoString(&buf, "'\n");
4473 errno = 0;
4474 if (write(fd, buf.data, buf.len) != buf.len)
4476 /* if write didn't set errno, assume problem is no disk space */
4477 if (errno == 0)
4478 errno = ENOSPC;
4479 ereport(ERROR,
4480 (errcode_for_file_access(),
4481 errmsg("could not write to file \"%s\": %m", filename)));
4485 /* fsync before considering the write to be successful */
4486 if (pg_fsync(fd) != 0)
4487 ereport(ERROR,
4488 (errcode_for_file_access(),
4489 errmsg("could not fsync file \"%s\": %m", filename)));
4491 pfree(buf.data);
4495 * Update the given list of configuration parameters, adding, replacing
4496 * or deleting the entry for item "name" (delete if "value" == NULL).
4498 static void
4499 replace_auto_config_value(ConfigVariable **head_p, ConfigVariable **tail_p,
4500 const char *name, const char *value)
4502 ConfigVariable *item,
4503 *next,
4504 *prev = NULL;
4507 * Remove any existing match(es) for "name". Normally there'd be at most
4508 * one, but if external tools have modified the config file, there could
4509 * be more.
4511 for (item = *head_p; item != NULL; item = next)
4513 next = item->next;
4514 if (guc_name_compare(item->name, name) == 0)
4516 /* found a match, delete it */
4517 if (prev)
4518 prev->next = next;
4519 else
4520 *head_p = next;
4521 if (next == NULL)
4522 *tail_p = prev;
4524 pfree(item->name);
4525 pfree(item->value);
4526 pfree(item->filename);
4527 pfree(item);
4529 else
4530 prev = item;
4533 /* Done if we're trying to delete it */
4534 if (value == NULL)
4535 return;
4537 /* OK, append a new entry */
4538 item = palloc(sizeof *item);
4539 item->name = pstrdup(name);
4540 item->value = pstrdup(value);
4541 item->errmsg = NULL;
4542 item->filename = pstrdup(""); /* new item has no location */
4543 item->sourceline = 0;
4544 item->ignore = false;
4545 item->applied = false;
4546 item->next = NULL;
4548 if (*head_p == NULL)
4549 *head_p = item;
4550 else
4551 (*tail_p)->next = item;
4552 *tail_p = item;
4557 * Execute ALTER SYSTEM statement.
4559 * Read the old PG_AUTOCONF_FILENAME file, merge in the new variable value,
4560 * and write out an updated file. If the command is ALTER SYSTEM RESET ALL,
4561 * we can skip reading the old file and just write an empty file.
4563 * An LWLock is used to serialize updates of the configuration file.
4565 * In case of an error, we leave the original automatic
4566 * configuration file (PG_AUTOCONF_FILENAME) intact.
4568 void
4569 AlterSystemSetConfigFile(AlterSystemStmt *altersysstmt)
4571 char *name;
4572 char *value;
4573 bool resetall = false;
4574 ConfigVariable *head = NULL;
4575 ConfigVariable *tail = NULL;
4576 volatile int Tmpfd;
4577 char AutoConfFileName[MAXPGPATH];
4578 char AutoConfTmpFileName[MAXPGPATH];
4581 * Extract statement arguments
4583 name = altersysstmt->setstmt->name;
4585 if (!AllowAlterSystem)
4586 ereport(ERROR,
4587 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4588 errmsg("ALTER SYSTEM is not allowed in this environment")));
4590 switch (altersysstmt->setstmt->kind)
4592 case VAR_SET_VALUE:
4593 value = ExtractSetVariableArgs(altersysstmt->setstmt);
4594 break;
4596 case VAR_SET_DEFAULT:
4597 case VAR_RESET:
4598 value = NULL;
4599 break;
4601 case VAR_RESET_ALL:
4602 value = NULL;
4603 resetall = true;
4604 break;
4606 default:
4607 elog(ERROR, "unrecognized alter system stmt type: %d",
4608 altersysstmt->setstmt->kind);
4609 break;
4613 * Check permission to run ALTER SYSTEM on the target variable
4615 if (!superuser())
4617 if (resetall)
4618 ereport(ERROR,
4619 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
4620 errmsg("permission denied to perform ALTER SYSTEM RESET ALL")));
4621 else
4623 AclResult aclresult;
4625 aclresult = pg_parameter_aclcheck(name, GetUserId(),
4626 ACL_ALTER_SYSTEM);
4627 if (aclresult != ACLCHECK_OK)
4628 ereport(ERROR,
4629 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
4630 errmsg("permission denied to set parameter \"%s\"",
4631 name)));
4636 * Unless it's RESET_ALL, validate the target variable and value
4638 if (!resetall)
4640 struct config_generic *record;
4642 /* We don't want to create a placeholder if there's not one already */
4643 record = find_option(name, false, true, DEBUG5);
4644 if (record != NULL)
4647 * Don't allow parameters that can't be set in configuration files
4648 * to be set in PG_AUTOCONF_FILENAME file.
4650 if ((record->context == PGC_INTERNAL) ||
4651 (record->flags & GUC_DISALLOW_IN_FILE) ||
4652 (record->flags & GUC_DISALLOW_IN_AUTO_FILE))
4653 ereport(ERROR,
4654 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
4655 errmsg("parameter \"%s\" cannot be changed",
4656 name)));
4659 * If a value is specified, verify that it's sane.
4661 if (value)
4663 union config_var_val newval;
4664 void *newextra = NULL;
4666 if (!parse_and_validate_value(record, name, value,
4667 PGC_S_FILE, ERROR,
4668 &newval, &newextra))
4669 ereport(ERROR,
4670 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4671 errmsg("invalid value for parameter \"%s\": \"%s\"",
4672 name, value)));
4674 if (record->vartype == PGC_STRING && newval.stringval != NULL)
4675 guc_free(newval.stringval);
4676 guc_free(newextra);
4679 else
4682 * Variable not known; check we'd be allowed to create it. (We
4683 * cannot validate the value, but that's fine. A non-core GUC in
4684 * the config file cannot cause postmaster start to fail, so we
4685 * don't have to be too tense about possibly installing a bad
4686 * value.)
4688 (void) assignable_custom_variable_name(name, false, ERROR);
4692 * We must also reject values containing newlines, because the grammar
4693 * for config files doesn't support embedded newlines in string
4694 * literals.
4696 if (value && strchr(value, '\n'))
4697 ereport(ERROR,
4698 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4699 errmsg("parameter value for ALTER SYSTEM must not contain a newline")));
4703 * PG_AUTOCONF_FILENAME and its corresponding temporary file are always in
4704 * the data directory, so we can reference them by simple relative paths.
4706 snprintf(AutoConfFileName, sizeof(AutoConfFileName), "%s",
4707 PG_AUTOCONF_FILENAME);
4708 snprintf(AutoConfTmpFileName, sizeof(AutoConfTmpFileName), "%s.%s",
4709 AutoConfFileName,
4710 "tmp");
4713 * Only one backend is allowed to operate on PG_AUTOCONF_FILENAME at a
4714 * time. Use AutoFileLock to ensure that. We must hold the lock while
4715 * reading the old file contents.
4717 LWLockAcquire(AutoFileLock, LW_EXCLUSIVE);
4720 * If we're going to reset everything, then no need to open or parse the
4721 * old file. We'll just write out an empty list.
4723 if (!resetall)
4725 struct stat st;
4727 if (stat(AutoConfFileName, &st) == 0)
4729 /* open old file PG_AUTOCONF_FILENAME */
4730 FILE *infile;
4732 infile = AllocateFile(AutoConfFileName, "r");
4733 if (infile == NULL)
4734 ereport(ERROR,
4735 (errcode_for_file_access(),
4736 errmsg("could not open file \"%s\": %m",
4737 AutoConfFileName)));
4739 /* parse it */
4740 if (!ParseConfigFp(infile, AutoConfFileName, CONF_FILE_START_DEPTH,
4741 LOG, &head, &tail))
4742 ereport(ERROR,
4743 (errcode(ERRCODE_CONFIG_FILE_ERROR),
4744 errmsg("could not parse contents of file \"%s\"",
4745 AutoConfFileName)));
4747 FreeFile(infile);
4751 * Now, replace any existing entry with the new value, or add it if
4752 * not present.
4754 replace_auto_config_value(&head, &tail, name, value);
4758 * Invoke the post-alter hook for setting this GUC variable. GUCs
4759 * typically do not have corresponding entries in pg_parameter_acl, so we
4760 * call the hook using the name rather than a potentially-non-existent
4761 * OID. Nonetheless, we pass ParameterAclRelationId so that this call
4762 * context can be distinguished from others. (Note that "name" will be
4763 * NULL in the RESET ALL case.)
4765 * We do this here rather than at the end, because ALTER SYSTEM is not
4766 * transactional. If the hook aborts our transaction, it will be cleaner
4767 * to do so before we touch any files.
4769 InvokeObjectPostAlterHookArgStr(ParameterAclRelationId, name,
4770 ACL_ALTER_SYSTEM,
4771 altersysstmt->setstmt->kind,
4772 false);
4775 * To ensure crash safety, first write the new file data to a temp file,
4776 * then atomically rename it into place.
4778 * If there is a temp file left over due to a previous crash, it's okay to
4779 * truncate and reuse it.
4781 Tmpfd = BasicOpenFile(AutoConfTmpFileName,
4782 O_CREAT | O_RDWR | O_TRUNC);
4783 if (Tmpfd < 0)
4784 ereport(ERROR,
4785 (errcode_for_file_access(),
4786 errmsg("could not open file \"%s\": %m",
4787 AutoConfTmpFileName)));
4790 * Use a TRY block to clean up the file if we fail. Since we need a TRY
4791 * block anyway, OK to use BasicOpenFile rather than OpenTransientFile.
4793 PG_TRY();
4795 /* Write and sync the new contents to the temporary file */
4796 write_auto_conf_file(Tmpfd, AutoConfTmpFileName, head);
4798 /* Close before renaming; may be required on some platforms */
4799 close(Tmpfd);
4800 Tmpfd = -1;
4803 * As the rename is atomic operation, if any problem occurs after this
4804 * at worst it can lose the parameters set by last ALTER SYSTEM
4805 * command.
4807 durable_rename(AutoConfTmpFileName, AutoConfFileName, ERROR);
4809 PG_CATCH();
4811 /* Close file first, else unlink might fail on some platforms */
4812 if (Tmpfd >= 0)
4813 close(Tmpfd);
4815 /* Unlink, but ignore any error */
4816 (void) unlink(AutoConfTmpFileName);
4818 PG_RE_THROW();
4820 PG_END_TRY();
4822 FreeConfigVariables(head);
4824 LWLockRelease(AutoFileLock);
4829 * Common code for DefineCustomXXXVariable subroutines: allocate the
4830 * new variable's config struct and fill in generic fields.
4832 static struct config_generic *
4833 init_custom_variable(const char *name,
4834 const char *short_desc,
4835 const char *long_desc,
4836 GucContext context,
4837 int flags,
4838 enum config_type type,
4839 size_t sz)
4841 struct config_generic *gen;
4844 * Only allow custom PGC_POSTMASTER variables to be created during shared
4845 * library preload; any later than that, we can't ensure that the value
4846 * doesn't change after startup. This is a fatal elog if it happens; just
4847 * erroring out isn't safe because we don't know what the calling loadable
4848 * module might already have hooked into.
4850 if (context == PGC_POSTMASTER &&
4851 !process_shared_preload_libraries_in_progress)
4852 elog(FATAL, "cannot create PGC_POSTMASTER variables after startup");
4855 * We can't support custom GUC_LIST_QUOTE variables, because the wrong
4856 * things would happen if such a variable were set or pg_dump'd when the
4857 * defining extension isn't loaded. Again, treat this as fatal because
4858 * the loadable module may be partly initialized already.
4860 if (flags & GUC_LIST_QUOTE)
4861 elog(FATAL, "extensions cannot define GUC_LIST_QUOTE variables");
4864 * Before pljava commit 398f3b876ed402bdaec8bc804f29e2be95c75139
4865 * (2015-12-15), two of that module's PGC_USERSET variables facilitated
4866 * trivial escalation to superuser privileges. Restrict the variables to
4867 * protect sites that have yet to upgrade pljava.
4869 if (context == PGC_USERSET &&
4870 (strcmp(name, "pljava.classpath") == 0 ||
4871 strcmp(name, "pljava.vmoptions") == 0))
4872 context = PGC_SUSET;
4874 gen = (struct config_generic *) guc_malloc(ERROR, sz);
4875 memset(gen, 0, sz);
4877 gen->name = guc_strdup(ERROR, name);
4878 gen->context = context;
4879 gen->group = CUSTOM_OPTIONS;
4880 gen->short_desc = short_desc;
4881 gen->long_desc = long_desc;
4882 gen->flags = flags;
4883 gen->vartype = type;
4885 return gen;
4889 * Common code for DefineCustomXXXVariable subroutines: insert the new
4890 * variable into the GUC variable hash, replacing any placeholder.
4892 static void
4893 define_custom_variable(struct config_generic *variable)
4895 const char *name = variable->name;
4896 GUCHashEntry *hentry;
4897 struct config_string *pHolder;
4899 /* Check mapping between initial and default value */
4900 Assert(check_GUC_init(variable));
4903 * See if there's a placeholder by the same name.
4905 hentry = (GUCHashEntry *) hash_search(guc_hashtab,
4906 &name,
4907 HASH_FIND,
4908 NULL);
4909 if (hentry == NULL)
4912 * No placeholder to replace, so we can just add it ... but first,
4913 * make sure it's initialized to its default value.
4915 InitializeOneGUCOption(variable);
4916 add_guc_variable(variable, ERROR);
4917 return;
4921 * This better be a placeholder
4923 if ((hentry->gucvar->flags & GUC_CUSTOM_PLACEHOLDER) == 0)
4924 ereport(ERROR,
4925 (errcode(ERRCODE_INTERNAL_ERROR),
4926 errmsg("attempt to redefine parameter \"%s\"", name)));
4928 Assert(hentry->gucvar->vartype == PGC_STRING);
4929 pHolder = (struct config_string *) hentry->gucvar;
4932 * First, set the variable to its default value. We must do this even
4933 * though we intend to immediately apply a new value, since it's possible
4934 * that the new value is invalid.
4936 InitializeOneGUCOption(variable);
4939 * Replace the placeholder in the hash table. We aren't changing the name
4940 * (at least up to case-folding), so the hash value is unchanged.
4942 hentry->gucname = name;
4943 hentry->gucvar = variable;
4946 * Remove the placeholder from any lists it's in, too.
4948 RemoveGUCFromLists(&pHolder->gen);
4951 * Assign the string value(s) stored in the placeholder to the real
4952 * variable. Essentially, we need to duplicate all the active and stacked
4953 * values, but with appropriate validation and datatype adjustment.
4955 * If an assignment fails, we report a WARNING and keep going. We don't
4956 * want to throw ERROR for bad values, because it'd bollix the add-on
4957 * module that's presumably halfway through getting loaded. In such cases
4958 * the default or previous state will become active instead.
4961 /* First, apply the reset value if any */
4962 if (pHolder->reset_val)
4963 (void) set_config_option_ext(name, pHolder->reset_val,
4964 pHolder->gen.reset_scontext,
4965 pHolder->gen.reset_source,
4966 pHolder->gen.reset_srole,
4967 GUC_ACTION_SET, true, WARNING, false);
4968 /* That should not have resulted in stacking anything */
4969 Assert(variable->stack == NULL);
4971 /* Now, apply current and stacked values, in the order they were stacked */
4972 reapply_stacked_values(variable, pHolder, pHolder->gen.stack,
4973 *(pHolder->variable),
4974 pHolder->gen.scontext, pHolder->gen.source,
4975 pHolder->gen.srole);
4977 /* Also copy over any saved source-location information */
4978 if (pHolder->gen.sourcefile)
4979 set_config_sourcefile(name, pHolder->gen.sourcefile,
4980 pHolder->gen.sourceline);
4983 * Free up as much as we conveniently can of the placeholder structure.
4984 * (This neglects any stack items, so it's possible for some memory to be
4985 * leaked. Since this can only happen once per session per variable, it
4986 * doesn't seem worth spending much code on.)
4988 set_string_field(pHolder, pHolder->variable, NULL);
4989 set_string_field(pHolder, &pHolder->reset_val, NULL);
4991 guc_free(pHolder);
4995 * Recursive subroutine for define_custom_variable: reapply non-reset values
4997 * We recurse so that the values are applied in the same order as originally.
4998 * At each recursion level, apply the upper-level value (passed in) in the
4999 * fashion implied by the stack entry.
5001 static void
5002 reapply_stacked_values(struct config_generic *variable,
5003 struct config_string *pHolder,
5004 GucStack *stack,
5005 const char *curvalue,
5006 GucContext curscontext, GucSource cursource,
5007 Oid cursrole)
5009 const char *name = variable->name;
5010 GucStack *oldvarstack = variable->stack;
5012 if (stack != NULL)
5014 /* First, recurse, so that stack items are processed bottom to top */
5015 reapply_stacked_values(variable, pHolder, stack->prev,
5016 stack->prior.val.stringval,
5017 stack->scontext, stack->source, stack->srole);
5019 /* See how to apply the passed-in value */
5020 switch (stack->state)
5022 case GUC_SAVE:
5023 (void) set_config_option_ext(name, curvalue,
5024 curscontext, cursource, cursrole,
5025 GUC_ACTION_SAVE, true,
5026 WARNING, false);
5027 break;
5029 case GUC_SET:
5030 (void) set_config_option_ext(name, curvalue,
5031 curscontext, cursource, cursrole,
5032 GUC_ACTION_SET, true,
5033 WARNING, false);
5034 break;
5036 case GUC_LOCAL:
5037 (void) set_config_option_ext(name, curvalue,
5038 curscontext, cursource, cursrole,
5039 GUC_ACTION_LOCAL, true,
5040 WARNING, false);
5041 break;
5043 case GUC_SET_LOCAL:
5044 /* first, apply the masked value as SET */
5045 (void) set_config_option_ext(name, stack->masked.val.stringval,
5046 stack->masked_scontext,
5047 PGC_S_SESSION,
5048 stack->masked_srole,
5049 GUC_ACTION_SET, true,
5050 WARNING, false);
5051 /* then apply the current value as LOCAL */
5052 (void) set_config_option_ext(name, curvalue,
5053 curscontext, cursource, cursrole,
5054 GUC_ACTION_LOCAL, true,
5055 WARNING, false);
5056 break;
5059 /* If we successfully made a stack entry, adjust its nest level */
5060 if (variable->stack != oldvarstack)
5061 variable->stack->nest_level = stack->nest_level;
5063 else
5066 * We are at the end of the stack. If the active/previous value is
5067 * different from the reset value, it must represent a previously
5068 * committed session value. Apply it, and then drop the stack entry
5069 * that set_config_option will have created under the impression that
5070 * this is to be just a transactional assignment. (We leak the stack
5071 * entry.)
5073 if (curvalue != pHolder->reset_val ||
5074 curscontext != pHolder->gen.reset_scontext ||
5075 cursource != pHolder->gen.reset_source ||
5076 cursrole != pHolder->gen.reset_srole)
5078 (void) set_config_option_ext(name, curvalue,
5079 curscontext, cursource, cursrole,
5080 GUC_ACTION_SET, true, WARNING, false);
5081 if (variable->stack != NULL)
5083 slist_delete(&guc_stack_list, &variable->stack_link);
5084 variable->stack = NULL;
5091 * Functions for extensions to call to define their custom GUC variables.
5093 void
5094 DefineCustomBoolVariable(const char *name,
5095 const char *short_desc,
5096 const char *long_desc,
5097 bool *valueAddr,
5098 bool bootValue,
5099 GucContext context,
5100 int flags,
5101 GucBoolCheckHook check_hook,
5102 GucBoolAssignHook assign_hook,
5103 GucShowHook show_hook)
5105 struct config_bool *var;
5107 var = (struct config_bool *)
5108 init_custom_variable(name, short_desc, long_desc, context, flags,
5109 PGC_BOOL, sizeof(struct config_bool));
5110 var->variable = valueAddr;
5111 var->boot_val = bootValue;
5112 var->reset_val = bootValue;
5113 var->check_hook = check_hook;
5114 var->assign_hook = assign_hook;
5115 var->show_hook = show_hook;
5116 define_custom_variable(&var->gen);
5119 void
5120 DefineCustomIntVariable(const char *name,
5121 const char *short_desc,
5122 const char *long_desc,
5123 int *valueAddr,
5124 int bootValue,
5125 int minValue,
5126 int maxValue,
5127 GucContext context,
5128 int flags,
5129 GucIntCheckHook check_hook,
5130 GucIntAssignHook assign_hook,
5131 GucShowHook show_hook)
5133 struct config_int *var;
5135 var = (struct config_int *)
5136 init_custom_variable(name, short_desc, long_desc, context, flags,
5137 PGC_INT, sizeof(struct config_int));
5138 var->variable = valueAddr;
5139 var->boot_val = bootValue;
5140 var->reset_val = bootValue;
5141 var->min = minValue;
5142 var->max = maxValue;
5143 var->check_hook = check_hook;
5144 var->assign_hook = assign_hook;
5145 var->show_hook = show_hook;
5146 define_custom_variable(&var->gen);
5149 void
5150 DefineCustomRealVariable(const char *name,
5151 const char *short_desc,
5152 const char *long_desc,
5153 double *valueAddr,
5154 double bootValue,
5155 double minValue,
5156 double maxValue,
5157 GucContext context,
5158 int flags,
5159 GucRealCheckHook check_hook,
5160 GucRealAssignHook assign_hook,
5161 GucShowHook show_hook)
5163 struct config_real *var;
5165 var = (struct config_real *)
5166 init_custom_variable(name, short_desc, long_desc, context, flags,
5167 PGC_REAL, sizeof(struct config_real));
5168 var->variable = valueAddr;
5169 var->boot_val = bootValue;
5170 var->reset_val = bootValue;
5171 var->min = minValue;
5172 var->max = maxValue;
5173 var->check_hook = check_hook;
5174 var->assign_hook = assign_hook;
5175 var->show_hook = show_hook;
5176 define_custom_variable(&var->gen);
5179 void
5180 DefineCustomStringVariable(const char *name,
5181 const char *short_desc,
5182 const char *long_desc,
5183 char **valueAddr,
5184 const char *bootValue,
5185 GucContext context,
5186 int flags,
5187 GucStringCheckHook check_hook,
5188 GucStringAssignHook assign_hook,
5189 GucShowHook show_hook)
5191 struct config_string *var;
5193 var = (struct config_string *)
5194 init_custom_variable(name, short_desc, long_desc, context, flags,
5195 PGC_STRING, sizeof(struct config_string));
5196 var->variable = valueAddr;
5197 var->boot_val = bootValue;
5198 var->check_hook = check_hook;
5199 var->assign_hook = assign_hook;
5200 var->show_hook = show_hook;
5201 define_custom_variable(&var->gen);
5204 void
5205 DefineCustomEnumVariable(const char *name,
5206 const char *short_desc,
5207 const char *long_desc,
5208 int *valueAddr,
5209 int bootValue,
5210 const struct config_enum_entry *options,
5211 GucContext context,
5212 int flags,
5213 GucEnumCheckHook check_hook,
5214 GucEnumAssignHook assign_hook,
5215 GucShowHook show_hook)
5217 struct config_enum *var;
5219 var = (struct config_enum *)
5220 init_custom_variable(name, short_desc, long_desc, context, flags,
5221 PGC_ENUM, sizeof(struct config_enum));
5222 var->variable = valueAddr;
5223 var->boot_val = bootValue;
5224 var->reset_val = bootValue;
5225 var->options = options;
5226 var->check_hook = check_hook;
5227 var->assign_hook = assign_hook;
5228 var->show_hook = show_hook;
5229 define_custom_variable(&var->gen);
5233 * Mark the given GUC prefix as "reserved".
5235 * This deletes any existing placeholders matching the prefix,
5236 * and then prevents new ones from being created.
5237 * Extensions should call this after they've defined all of their custom
5238 * GUCs, to help catch misspelled config-file entries.
5240 void
5241 MarkGUCPrefixReserved(const char *className)
5243 int classLen = strlen(className);
5244 HASH_SEQ_STATUS status;
5245 GUCHashEntry *hentry;
5246 MemoryContext oldcontext;
5249 * Check for existing placeholders. We must actually remove invalid
5250 * placeholders, else future parallel worker startups will fail. (We
5251 * don't bother trying to free associated memory, since this shouldn't
5252 * happen often.)
5254 hash_seq_init(&status, guc_hashtab);
5255 while ((hentry = (GUCHashEntry *) hash_seq_search(&status)) != NULL)
5257 struct config_generic *var = hentry->gucvar;
5259 if ((var->flags & GUC_CUSTOM_PLACEHOLDER) != 0 &&
5260 strncmp(className, var->name, classLen) == 0 &&
5261 var->name[classLen] == GUC_QUALIFIER_SEPARATOR)
5263 ereport(WARNING,
5264 (errcode(ERRCODE_INVALID_NAME),
5265 errmsg("invalid configuration parameter name \"%s\", removing it",
5266 var->name),
5267 errdetail("\"%s\" is now a reserved prefix.",
5268 className)));
5269 /* Remove it from the hash table */
5270 hash_search(guc_hashtab,
5271 &var->name,
5272 HASH_REMOVE,
5273 NULL);
5274 /* Remove it from any lists it's in, too */
5275 RemoveGUCFromLists(var);
5279 /* And remember the name so we can prevent future mistakes. */
5280 oldcontext = MemoryContextSwitchTo(GUCMemoryContext);
5281 reserved_class_prefix = lappend(reserved_class_prefix, pstrdup(className));
5282 MemoryContextSwitchTo(oldcontext);
5287 * Return an array of modified GUC options to show in EXPLAIN.
5289 * We only report options related to query planning (marked with GUC_EXPLAIN),
5290 * with values different from their built-in defaults.
5292 struct config_generic **
5293 get_explain_guc_options(int *num)
5295 struct config_generic **result;
5296 dlist_iter iter;
5298 *num = 0;
5301 * While only a fraction of all the GUC variables are marked GUC_EXPLAIN,
5302 * it doesn't seem worth dynamically resizing this array.
5304 result = palloc(sizeof(struct config_generic *) * hash_get_num_entries(guc_hashtab));
5306 /* We need only consider GUCs with source not PGC_S_DEFAULT */
5307 dlist_foreach(iter, &guc_nondef_list)
5309 struct config_generic *conf = dlist_container(struct config_generic,
5310 nondef_link, iter.cur);
5311 bool modified;
5313 /* return only parameters marked for inclusion in explain */
5314 if (!(conf->flags & GUC_EXPLAIN))
5315 continue;
5317 /* return only options visible to the current user */
5318 if (!ConfigOptionIsVisible(conf))
5319 continue;
5321 /* return only options that are different from their boot values */
5322 modified = false;
5324 switch (conf->vartype)
5326 case PGC_BOOL:
5328 struct config_bool *lconf = (struct config_bool *) conf;
5330 modified = (lconf->boot_val != *(lconf->variable));
5332 break;
5334 case PGC_INT:
5336 struct config_int *lconf = (struct config_int *) conf;
5338 modified = (lconf->boot_val != *(lconf->variable));
5340 break;
5342 case PGC_REAL:
5344 struct config_real *lconf = (struct config_real *) conf;
5346 modified = (lconf->boot_val != *(lconf->variable));
5348 break;
5350 case PGC_STRING:
5352 struct config_string *lconf = (struct config_string *) conf;
5354 if (lconf->boot_val == NULL &&
5355 *lconf->variable == NULL)
5356 modified = false;
5357 else if (lconf->boot_val == NULL ||
5358 *lconf->variable == NULL)
5359 modified = true;
5360 else
5361 modified = (strcmp(lconf->boot_val, *(lconf->variable)) != 0);
5363 break;
5365 case PGC_ENUM:
5367 struct config_enum *lconf = (struct config_enum *) conf;
5369 modified = (lconf->boot_val != *(lconf->variable));
5371 break;
5373 default:
5374 elog(ERROR, "unexpected GUC type: %d", conf->vartype);
5377 if (!modified)
5378 continue;
5380 /* OK, report it */
5381 result[*num] = conf;
5382 *num = *num + 1;
5385 return result;
5389 * Return GUC variable value by name; optionally return canonical form of
5390 * name. If the GUC is unset, then throw an error unless missing_ok is true,
5391 * in which case return NULL. Return value is palloc'd (but *varname isn't).
5393 char *
5394 GetConfigOptionByName(const char *name, const char **varname, bool missing_ok)
5396 struct config_generic *record;
5398 record = find_option(name, false, missing_ok, ERROR);
5399 if (record == NULL)
5401 if (varname)
5402 *varname = NULL;
5403 return NULL;
5406 if (!ConfigOptionIsVisible(record))
5407 ereport(ERROR,
5408 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
5409 errmsg("permission denied to examine \"%s\"", name),
5410 errdetail("Only roles with privileges of the \"%s\" role may examine this parameter.",
5411 "pg_read_all_settings")));
5413 if (varname)
5414 *varname = record->name;
5416 return ShowGUCOption(record, true);
5420 * ShowGUCOption: get string value of variable
5422 * We express a numeric value in appropriate units if it has units and
5423 * use_units is true; else you just get the raw number.
5424 * The result string is palloc'd.
5426 char *
5427 ShowGUCOption(struct config_generic *record, bool use_units)
5429 char buffer[256];
5430 const char *val;
5432 switch (record->vartype)
5434 case PGC_BOOL:
5436 struct config_bool *conf = (struct config_bool *) record;
5438 if (conf->show_hook)
5439 val = conf->show_hook();
5440 else
5441 val = *conf->variable ? "on" : "off";
5443 break;
5445 case PGC_INT:
5447 struct config_int *conf = (struct config_int *) record;
5449 if (conf->show_hook)
5450 val = conf->show_hook();
5451 else
5454 * Use int64 arithmetic to avoid overflows in units
5455 * conversion.
5457 int64 result = *conf->variable;
5458 const char *unit;
5460 if (use_units && result > 0 && (record->flags & GUC_UNIT))
5461 convert_int_from_base_unit(result,
5462 record->flags & GUC_UNIT,
5463 &result, &unit);
5464 else
5465 unit = "";
5467 snprintf(buffer, sizeof(buffer), INT64_FORMAT "%s",
5468 result, unit);
5469 val = buffer;
5472 break;
5474 case PGC_REAL:
5476 struct config_real *conf = (struct config_real *) record;
5478 if (conf->show_hook)
5479 val = conf->show_hook();
5480 else
5482 double result = *conf->variable;
5483 const char *unit;
5485 if (use_units && result > 0 && (record->flags & GUC_UNIT))
5486 convert_real_from_base_unit(result,
5487 record->flags & GUC_UNIT,
5488 &result, &unit);
5489 else
5490 unit = "";
5492 snprintf(buffer, sizeof(buffer), "%g%s",
5493 result, unit);
5494 val = buffer;
5497 break;
5499 case PGC_STRING:
5501 struct config_string *conf = (struct config_string *) record;
5503 if (conf->show_hook)
5504 val = conf->show_hook();
5505 else if (*conf->variable && **conf->variable)
5506 val = *conf->variable;
5507 else
5508 val = "";
5510 break;
5512 case PGC_ENUM:
5514 struct config_enum *conf = (struct config_enum *) record;
5516 if (conf->show_hook)
5517 val = conf->show_hook();
5518 else
5519 val = config_enum_lookup_by_value(conf, *conf->variable);
5521 break;
5523 default:
5524 /* just to keep compiler quiet */
5525 val = "???";
5526 break;
5529 return pstrdup(val);
5533 #ifdef EXEC_BACKEND
5536 * These routines dump out all non-default GUC options into a binary
5537 * file that is read by all exec'ed backends. The format is:
5539 * variable name, string, null terminated
5540 * variable value, string, null terminated
5541 * variable sourcefile, string, null terminated (empty if none)
5542 * variable sourceline, integer
5543 * variable source, integer
5544 * variable scontext, integer
5545 * variable srole, OID
5547 static void
5548 write_one_nondefault_variable(FILE *fp, struct config_generic *gconf)
5550 Assert(gconf->source != PGC_S_DEFAULT);
5552 fprintf(fp, "%s", gconf->name);
5553 fputc(0, fp);
5555 switch (gconf->vartype)
5557 case PGC_BOOL:
5559 struct config_bool *conf = (struct config_bool *) gconf;
5561 if (*conf->variable)
5562 fprintf(fp, "true");
5563 else
5564 fprintf(fp, "false");
5566 break;
5568 case PGC_INT:
5570 struct config_int *conf = (struct config_int *) gconf;
5572 fprintf(fp, "%d", *conf->variable);
5574 break;
5576 case PGC_REAL:
5578 struct config_real *conf = (struct config_real *) gconf;
5580 fprintf(fp, "%.17g", *conf->variable);
5582 break;
5584 case PGC_STRING:
5586 struct config_string *conf = (struct config_string *) gconf;
5588 if (*conf->variable)
5589 fprintf(fp, "%s", *conf->variable);
5591 break;
5593 case PGC_ENUM:
5595 struct config_enum *conf = (struct config_enum *) gconf;
5597 fprintf(fp, "%s",
5598 config_enum_lookup_by_value(conf, *conf->variable));
5600 break;
5603 fputc(0, fp);
5605 if (gconf->sourcefile)
5606 fprintf(fp, "%s", gconf->sourcefile);
5607 fputc(0, fp);
5609 fwrite(&gconf->sourceline, 1, sizeof(gconf->sourceline), fp);
5610 fwrite(&gconf->source, 1, sizeof(gconf->source), fp);
5611 fwrite(&gconf->scontext, 1, sizeof(gconf->scontext), fp);
5612 fwrite(&gconf->srole, 1, sizeof(gconf->srole), fp);
5615 void
5616 write_nondefault_variables(GucContext context)
5618 int elevel;
5619 FILE *fp;
5620 dlist_iter iter;
5622 Assert(context == PGC_POSTMASTER || context == PGC_SIGHUP);
5624 elevel = (context == PGC_SIGHUP) ? LOG : ERROR;
5627 * Open file
5629 fp = AllocateFile(CONFIG_EXEC_PARAMS_NEW, "w");
5630 if (!fp)
5632 ereport(elevel,
5633 (errcode_for_file_access(),
5634 errmsg("could not write to file \"%s\": %m",
5635 CONFIG_EXEC_PARAMS_NEW)));
5636 return;
5639 /* We need only consider GUCs with source not PGC_S_DEFAULT */
5640 dlist_foreach(iter, &guc_nondef_list)
5642 struct config_generic *gconf = dlist_container(struct config_generic,
5643 nondef_link, iter.cur);
5645 write_one_nondefault_variable(fp, gconf);
5648 if (FreeFile(fp))
5650 ereport(elevel,
5651 (errcode_for_file_access(),
5652 errmsg("could not write to file \"%s\": %m",
5653 CONFIG_EXEC_PARAMS_NEW)));
5654 return;
5658 * Put new file in place. This could delay on Win32, but we don't hold
5659 * any exclusive locks.
5661 rename(CONFIG_EXEC_PARAMS_NEW, CONFIG_EXEC_PARAMS);
5666 * Read string, including null byte from file
5668 * Return NULL on EOF and nothing read
5670 static char *
5671 read_string_with_null(FILE *fp)
5673 int i = 0,
5675 maxlen = 256;
5676 char *str = NULL;
5680 if ((ch = fgetc(fp)) == EOF)
5682 if (i == 0)
5683 return NULL;
5684 else
5685 elog(FATAL, "invalid format of exec config params file");
5687 if (i == 0)
5688 str = guc_malloc(FATAL, maxlen);
5689 else if (i == maxlen)
5690 str = guc_realloc(FATAL, str, maxlen *= 2);
5691 str[i++] = ch;
5692 } while (ch != 0);
5694 return str;
5699 * This routine loads a previous postmaster dump of its non-default
5700 * settings.
5702 void
5703 read_nondefault_variables(void)
5705 FILE *fp;
5706 char *varname,
5707 *varvalue,
5708 *varsourcefile;
5709 int varsourceline;
5710 GucSource varsource;
5711 GucContext varscontext;
5712 Oid varsrole;
5715 * Open file
5717 fp = AllocateFile(CONFIG_EXEC_PARAMS, "r");
5718 if (!fp)
5720 /* File not found is fine */
5721 if (errno != ENOENT)
5722 ereport(FATAL,
5723 (errcode_for_file_access(),
5724 errmsg("could not read from file \"%s\": %m",
5725 CONFIG_EXEC_PARAMS)));
5726 return;
5729 for (;;)
5731 if ((varname = read_string_with_null(fp)) == NULL)
5732 break;
5734 if (find_option(varname, true, false, FATAL) == NULL)
5735 elog(FATAL, "failed to locate variable \"%s\" in exec config params file", varname);
5737 if ((varvalue = read_string_with_null(fp)) == NULL)
5738 elog(FATAL, "invalid format of exec config params file");
5739 if ((varsourcefile = read_string_with_null(fp)) == NULL)
5740 elog(FATAL, "invalid format of exec config params file");
5741 if (fread(&varsourceline, 1, sizeof(varsourceline), fp) != sizeof(varsourceline))
5742 elog(FATAL, "invalid format of exec config params file");
5743 if (fread(&varsource, 1, sizeof(varsource), fp) != sizeof(varsource))
5744 elog(FATAL, "invalid format of exec config params file");
5745 if (fread(&varscontext, 1, sizeof(varscontext), fp) != sizeof(varscontext))
5746 elog(FATAL, "invalid format of exec config params file");
5747 if (fread(&varsrole, 1, sizeof(varsrole), fp) != sizeof(varsrole))
5748 elog(FATAL, "invalid format of exec config params file");
5750 (void) set_config_option_ext(varname, varvalue,
5751 varscontext, varsource, varsrole,
5752 GUC_ACTION_SET, true, 0, true);
5753 if (varsourcefile[0])
5754 set_config_sourcefile(varname, varsourcefile, varsourceline);
5756 guc_free(varname);
5757 guc_free(varvalue);
5758 guc_free(varsourcefile);
5761 FreeFile(fp);
5763 #endif /* EXEC_BACKEND */
5766 * can_skip_gucvar:
5767 * Decide whether SerializeGUCState can skip sending this GUC variable,
5768 * or whether RestoreGUCState can skip resetting this GUC to default.
5770 * It is somewhat magical and fragile that the same test works for both cases.
5771 * Realize in particular that we are very likely selecting different sets of
5772 * GUCs on the leader and worker sides! Be sure you've understood the
5773 * comments here and in RestoreGUCState thoroughly before changing this.
5775 static bool
5776 can_skip_gucvar(struct config_generic *gconf)
5779 * We can skip GUCs that are guaranteed to have the same values in leaders
5780 * and workers. (Note it is critical that the leader and worker have the
5781 * same idea of which GUCs fall into this category. It's okay to consider
5782 * context and name for this purpose, since those are unchanging
5783 * properties of a GUC.)
5785 * PGC_POSTMASTER variables always have the same value in every child of a
5786 * particular postmaster, so the worker will certainly have the right
5787 * value already. Likewise, PGC_INTERNAL variables are set by special
5788 * mechanisms (if indeed they aren't compile-time constants). So we may
5789 * always skip these.
5791 * Role must be handled specially because its current value can be an
5792 * invalid value (for instance, if someone dropped the role since we set
5793 * it). So if we tried to serialize it normally, we might get a failure.
5794 * We skip it here, and use another mechanism to ensure the worker has the
5795 * right value.
5797 * For all other GUCs, we skip if the GUC has its compiled-in default
5798 * value (i.e., source == PGC_S_DEFAULT). On the leader side, this means
5799 * we don't send GUCs that have their default values, which typically
5800 * saves lots of work. On the worker side, this means we don't need to
5801 * reset the GUC to default because it already has that value. See
5802 * comments in RestoreGUCState for more info.
5804 return gconf->context == PGC_POSTMASTER ||
5805 gconf->context == PGC_INTERNAL || gconf->source == PGC_S_DEFAULT ||
5806 strcmp(gconf->name, "role") == 0;
5810 * estimate_variable_size:
5811 * Compute space needed for dumping the given GUC variable.
5813 * It's OK to overestimate, but not to underestimate.
5815 static Size
5816 estimate_variable_size(struct config_generic *gconf)
5818 Size size;
5819 Size valsize = 0;
5821 /* Skippable GUCs consume zero space. */
5822 if (can_skip_gucvar(gconf))
5823 return 0;
5825 /* Name, plus trailing zero byte. */
5826 size = strlen(gconf->name) + 1;
5828 /* Get the maximum display length of the GUC value. */
5829 switch (gconf->vartype)
5831 case PGC_BOOL:
5833 valsize = 5; /* max(strlen('true'), strlen('false')) */
5835 break;
5837 case PGC_INT:
5839 struct config_int *conf = (struct config_int *) gconf;
5842 * Instead of getting the exact display length, use max
5843 * length. Also reduce the max length for typical ranges of
5844 * small values. Maximum value is 2147483647, i.e. 10 chars.
5845 * Include one byte for sign.
5847 if (abs(*conf->variable) < 1000)
5848 valsize = 3 + 1;
5849 else
5850 valsize = 10 + 1;
5852 break;
5854 case PGC_REAL:
5857 * We are going to print it with %e with REALTYPE_PRECISION
5858 * fractional digits. Account for sign, leading digit,
5859 * decimal point, and exponent with up to 3 digits. E.g.
5860 * -3.99329042340000021e+110
5862 valsize = 1 + 1 + 1 + REALTYPE_PRECISION + 5;
5864 break;
5866 case PGC_STRING:
5868 struct config_string *conf = (struct config_string *) gconf;
5871 * If the value is NULL, we transmit it as an empty string.
5872 * Although this is not physically the same value, GUC
5873 * generally treats a NULL the same as empty string.
5875 if (*conf->variable)
5876 valsize = strlen(*conf->variable);
5877 else
5878 valsize = 0;
5880 break;
5882 case PGC_ENUM:
5884 struct config_enum *conf = (struct config_enum *) gconf;
5886 valsize = strlen(config_enum_lookup_by_value(conf, *conf->variable));
5888 break;
5891 /* Allow space for terminating zero-byte for value */
5892 size = add_size(size, valsize + 1);
5894 if (gconf->sourcefile)
5895 size = add_size(size, strlen(gconf->sourcefile));
5897 /* Allow space for terminating zero-byte for sourcefile */
5898 size = add_size(size, 1);
5900 /* Include line whenever file is nonempty. */
5901 if (gconf->sourcefile && gconf->sourcefile[0])
5902 size = add_size(size, sizeof(gconf->sourceline));
5904 size = add_size(size, sizeof(gconf->source));
5905 size = add_size(size, sizeof(gconf->scontext));
5906 size = add_size(size, sizeof(gconf->srole));
5908 return size;
5912 * EstimateGUCStateSpace:
5913 * Returns the size needed to store the GUC state for the current process
5915 Size
5916 EstimateGUCStateSpace(void)
5918 Size size;
5919 dlist_iter iter;
5921 /* Add space reqd for saving the data size of the guc state */
5922 size = sizeof(Size);
5925 * Add up the space needed for each GUC variable.
5927 * We need only process non-default GUCs.
5929 dlist_foreach(iter, &guc_nondef_list)
5931 struct config_generic *gconf = dlist_container(struct config_generic,
5932 nondef_link, iter.cur);
5934 size = add_size(size, estimate_variable_size(gconf));
5937 return size;
5941 * do_serialize:
5942 * Copies the formatted string into the destination. Moves ahead the
5943 * destination pointer, and decrements the maxbytes by that many bytes. If
5944 * maxbytes is not sufficient to copy the string, error out.
5946 static void
5947 do_serialize(char **destptr, Size *maxbytes, const char *fmt,...)
5949 va_list vargs;
5950 int n;
5952 if (*maxbytes <= 0)
5953 elog(ERROR, "not enough space to serialize GUC state");
5955 va_start(vargs, fmt);
5956 n = vsnprintf(*destptr, *maxbytes, fmt, vargs);
5957 va_end(vargs);
5959 if (n < 0)
5961 /* Shouldn't happen. Better show errno description. */
5962 elog(ERROR, "vsnprintf failed: %m with format string \"%s\"", fmt);
5964 if (n >= *maxbytes)
5966 /* This shouldn't happen either, really. */
5967 elog(ERROR, "not enough space to serialize GUC state");
5970 /* Shift the destptr ahead of the null terminator */
5971 *destptr += n + 1;
5972 *maxbytes -= n + 1;
5975 /* Binary copy version of do_serialize() */
5976 static void
5977 do_serialize_binary(char **destptr, Size *maxbytes, void *val, Size valsize)
5979 if (valsize > *maxbytes)
5980 elog(ERROR, "not enough space to serialize GUC state");
5982 memcpy(*destptr, val, valsize);
5983 *destptr += valsize;
5984 *maxbytes -= valsize;
5988 * serialize_variable:
5989 * Dumps name, value and other information of a GUC variable into destptr.
5991 static void
5992 serialize_variable(char **destptr, Size *maxbytes,
5993 struct config_generic *gconf)
5995 /* Ignore skippable GUCs. */
5996 if (can_skip_gucvar(gconf))
5997 return;
5999 do_serialize(destptr, maxbytes, "%s", gconf->name);
6001 switch (gconf->vartype)
6003 case PGC_BOOL:
6005 struct config_bool *conf = (struct config_bool *) gconf;
6007 do_serialize(destptr, maxbytes,
6008 (*conf->variable ? "true" : "false"));
6010 break;
6012 case PGC_INT:
6014 struct config_int *conf = (struct config_int *) gconf;
6016 do_serialize(destptr, maxbytes, "%d", *conf->variable);
6018 break;
6020 case PGC_REAL:
6022 struct config_real *conf = (struct config_real *) gconf;
6024 do_serialize(destptr, maxbytes, "%.*e",
6025 REALTYPE_PRECISION, *conf->variable);
6027 break;
6029 case PGC_STRING:
6031 struct config_string *conf = (struct config_string *) gconf;
6033 /* NULL becomes empty string, see estimate_variable_size() */
6034 do_serialize(destptr, maxbytes, "%s",
6035 *conf->variable ? *conf->variable : "");
6037 break;
6039 case PGC_ENUM:
6041 struct config_enum *conf = (struct config_enum *) gconf;
6043 do_serialize(destptr, maxbytes, "%s",
6044 config_enum_lookup_by_value(conf, *conf->variable));
6046 break;
6049 do_serialize(destptr, maxbytes, "%s",
6050 (gconf->sourcefile ? gconf->sourcefile : ""));
6052 if (gconf->sourcefile && gconf->sourcefile[0])
6053 do_serialize_binary(destptr, maxbytes, &gconf->sourceline,
6054 sizeof(gconf->sourceline));
6056 do_serialize_binary(destptr, maxbytes, &gconf->source,
6057 sizeof(gconf->source));
6058 do_serialize_binary(destptr, maxbytes, &gconf->scontext,
6059 sizeof(gconf->scontext));
6060 do_serialize_binary(destptr, maxbytes, &gconf->srole,
6061 sizeof(gconf->srole));
6065 * SerializeGUCState:
6066 * Dumps the complete GUC state onto the memory location at start_address.
6068 void
6069 SerializeGUCState(Size maxsize, char *start_address)
6071 char *curptr;
6072 Size actual_size;
6073 Size bytes_left;
6074 dlist_iter iter;
6076 /* Reserve space for saving the actual size of the guc state */
6077 Assert(maxsize > sizeof(actual_size));
6078 curptr = start_address + sizeof(actual_size);
6079 bytes_left = maxsize - sizeof(actual_size);
6081 /* We need only consider GUCs with source not PGC_S_DEFAULT */
6082 dlist_foreach(iter, &guc_nondef_list)
6084 struct config_generic *gconf = dlist_container(struct config_generic,
6085 nondef_link, iter.cur);
6087 serialize_variable(&curptr, &bytes_left, gconf);
6090 /* Store actual size without assuming alignment of start_address. */
6091 actual_size = maxsize - bytes_left - sizeof(actual_size);
6092 memcpy(start_address, &actual_size, sizeof(actual_size));
6096 * read_gucstate:
6097 * Actually it does not read anything, just returns the srcptr. But it does
6098 * move the srcptr past the terminating zero byte, so that the caller is ready
6099 * to read the next string.
6101 static char *
6102 read_gucstate(char **srcptr, char *srcend)
6104 char *retptr = *srcptr;
6105 char *ptr;
6107 if (*srcptr >= srcend)
6108 elog(ERROR, "incomplete GUC state");
6110 /* The string variables are all null terminated */
6111 for (ptr = *srcptr; ptr < srcend && *ptr != '\0'; ptr++)
6114 if (ptr >= srcend)
6115 elog(ERROR, "could not find null terminator in GUC state");
6117 /* Set the new position to the byte following the terminating NUL */
6118 *srcptr = ptr + 1;
6120 return retptr;
6123 /* Binary read version of read_gucstate(). Copies into dest */
6124 static void
6125 read_gucstate_binary(char **srcptr, char *srcend, void *dest, Size size)
6127 if (*srcptr + size > srcend)
6128 elog(ERROR, "incomplete GUC state");
6130 memcpy(dest, *srcptr, size);
6131 *srcptr += size;
6135 * Callback used to add a context message when reporting errors that occur
6136 * while trying to restore GUCs in parallel workers.
6138 static void
6139 guc_restore_error_context_callback(void *arg)
6141 char **error_context_name_and_value = (char **) arg;
6143 if (error_context_name_and_value)
6144 errcontext("while setting parameter \"%s\" to \"%s\"",
6145 error_context_name_and_value[0],
6146 error_context_name_and_value[1]);
6150 * RestoreGUCState:
6151 * Reads the GUC state at the specified address and sets this process's
6152 * GUCs to match.
6154 * Note that this provides the worker with only a very shallow view of the
6155 * leader's GUC state: we'll know about the currently active values, but not
6156 * about stacked or reset values. That's fine since the worker is just
6157 * executing one part of a query, within which the active values won't change
6158 * and the stacked values are invisible.
6160 void
6161 RestoreGUCState(void *gucstate)
6163 char *varname,
6164 *varvalue,
6165 *varsourcefile;
6166 int varsourceline;
6167 GucSource varsource;
6168 GucContext varscontext;
6169 Oid varsrole;
6170 char *srcptr = (char *) gucstate;
6171 char *srcend;
6172 Size len;
6173 dlist_mutable_iter iter;
6174 ErrorContextCallback error_context_callback;
6177 * First, ensure that all potentially-shippable GUCs are reset to their
6178 * default values. We must not touch those GUCs that the leader will
6179 * never ship, while there is no need to touch those that are shippable
6180 * but already have their default values. Thus, this ends up being the
6181 * same test that SerializeGUCState uses, even though the sets of
6182 * variables involved may well be different since the leader's set of
6183 * variables-not-at-default-values can differ from the set that are
6184 * not-default in this freshly started worker.
6186 * Once we have set all the potentially-shippable GUCs to default values,
6187 * restoring the GUCs that the leader sent (because they had non-default
6188 * values over there) leads us to exactly the set of GUC values that the
6189 * leader has. This is true even though the worker may have initially
6190 * absorbed postgresql.conf settings that the leader hasn't yet seen, or
6191 * ALTER USER/DATABASE SET settings that were established after the leader
6192 * started.
6194 * Note that ensuring all the potential target GUCs are at PGC_S_DEFAULT
6195 * also ensures that set_config_option won't refuse to set them because of
6196 * source-priority comparisons.
6198 dlist_foreach_modify(iter, &guc_nondef_list)
6200 struct config_generic *gconf = dlist_container(struct config_generic,
6201 nondef_link, iter.cur);
6203 /* Do nothing if non-shippable or if already at PGC_S_DEFAULT. */
6204 if (can_skip_gucvar(gconf))
6205 continue;
6208 * We can use InitializeOneGUCOption to reset the GUC to default, but
6209 * first we must free any existing subsidiary data to avoid leaking
6210 * memory. The stack must be empty, but we have to clean up all other
6211 * fields. Beware that there might be duplicate value or "extra"
6212 * pointers. We also have to be sure to take it out of any lists it's
6213 * in.
6215 Assert(gconf->stack == NULL);
6216 guc_free(gconf->extra);
6217 guc_free(gconf->last_reported);
6218 guc_free(gconf->sourcefile);
6219 switch (gconf->vartype)
6221 case PGC_BOOL:
6223 struct config_bool *conf = (struct config_bool *) gconf;
6225 if (conf->reset_extra && conf->reset_extra != gconf->extra)
6226 guc_free(conf->reset_extra);
6227 break;
6229 case PGC_INT:
6231 struct config_int *conf = (struct config_int *) gconf;
6233 if (conf->reset_extra && conf->reset_extra != gconf->extra)
6234 guc_free(conf->reset_extra);
6235 break;
6237 case PGC_REAL:
6239 struct config_real *conf = (struct config_real *) gconf;
6241 if (conf->reset_extra && conf->reset_extra != gconf->extra)
6242 guc_free(conf->reset_extra);
6243 break;
6245 case PGC_STRING:
6247 struct config_string *conf = (struct config_string *) gconf;
6249 guc_free(*conf->variable);
6250 if (conf->reset_val && conf->reset_val != *conf->variable)
6251 guc_free(conf->reset_val);
6252 if (conf->reset_extra && conf->reset_extra != gconf->extra)
6253 guc_free(conf->reset_extra);
6254 break;
6256 case PGC_ENUM:
6258 struct config_enum *conf = (struct config_enum *) gconf;
6260 if (conf->reset_extra && conf->reset_extra != gconf->extra)
6261 guc_free(conf->reset_extra);
6262 break;
6265 /* Remove it from any lists it's in. */
6266 RemoveGUCFromLists(gconf);
6267 /* Now we can reset the struct to PGS_S_DEFAULT state. */
6268 InitializeOneGUCOption(gconf);
6271 /* First item is the length of the subsequent data */
6272 memcpy(&len, gucstate, sizeof(len));
6274 srcptr += sizeof(len);
6275 srcend = srcptr + len;
6277 /* If the GUC value check fails, we want errors to show useful context. */
6278 error_context_callback.callback = guc_restore_error_context_callback;
6279 error_context_callback.previous = error_context_stack;
6280 error_context_callback.arg = NULL;
6281 error_context_stack = &error_context_callback;
6283 /* Restore all the listed GUCs. */
6284 while (srcptr < srcend)
6286 int result;
6287 char *error_context_name_and_value[2];
6289 varname = read_gucstate(&srcptr, srcend);
6290 varvalue = read_gucstate(&srcptr, srcend);
6291 varsourcefile = read_gucstate(&srcptr, srcend);
6292 if (varsourcefile[0])
6293 read_gucstate_binary(&srcptr, srcend,
6294 &varsourceline, sizeof(varsourceline));
6295 else
6296 varsourceline = 0;
6297 read_gucstate_binary(&srcptr, srcend,
6298 &varsource, sizeof(varsource));
6299 read_gucstate_binary(&srcptr, srcend,
6300 &varscontext, sizeof(varscontext));
6301 read_gucstate_binary(&srcptr, srcend,
6302 &varsrole, sizeof(varsrole));
6304 error_context_name_and_value[0] = varname;
6305 error_context_name_and_value[1] = varvalue;
6306 error_context_callback.arg = &error_context_name_and_value[0];
6307 result = set_config_option_ext(varname, varvalue,
6308 varscontext, varsource, varsrole,
6309 GUC_ACTION_SET, true, ERROR, true);
6310 if (result <= 0)
6311 ereport(ERROR,
6312 (errcode(ERRCODE_INTERNAL_ERROR),
6313 errmsg("parameter \"%s\" could not be set", varname)));
6314 if (varsourcefile[0])
6315 set_config_sourcefile(varname, varsourcefile, varsourceline);
6316 error_context_callback.arg = NULL;
6319 error_context_stack = error_context_callback.previous;
6323 * A little "long argument" simulation, although not quite GNU
6324 * compliant. Takes a string of the form "some-option=some value" and
6325 * returns name = "some_option" and value = "some value" in palloc'ed
6326 * storage. Note that '-' is converted to '_' in the option name. If
6327 * there is no '=' in the input string then value will be NULL.
6329 void
6330 ParseLongOption(const char *string, char **name, char **value)
6332 size_t equal_pos;
6333 char *cp;
6335 Assert(string);
6336 Assert(name);
6337 Assert(value);
6339 equal_pos = strcspn(string, "=");
6341 if (string[equal_pos] == '=')
6343 *name = palloc(equal_pos + 1);
6344 strlcpy(*name, string, equal_pos + 1);
6346 *value = pstrdup(&string[equal_pos + 1]);
6348 else
6350 /* no equal sign in string */
6351 *name = pstrdup(string);
6352 *value = NULL;
6355 for (cp = *name; *cp; cp++)
6356 if (*cp == '-')
6357 *cp = '_';
6362 * Transform array of GUC settings into lists of names and values. The lists
6363 * are faster to process in cases where the settings must be applied
6364 * repeatedly (e.g. for each function invocation).
6366 void
6367 TransformGUCArray(ArrayType *array, List **names, List **values)
6369 int i;
6371 Assert(array != NULL);
6372 Assert(ARR_ELEMTYPE(array) == TEXTOID);
6373 Assert(ARR_NDIM(array) == 1);
6374 Assert(ARR_LBOUND(array)[0] == 1);
6376 *names = NIL;
6377 *values = NIL;
6378 for (i = 1; i <= ARR_DIMS(array)[0]; i++)
6380 Datum d;
6381 bool isnull;
6382 char *s;
6383 char *name;
6384 char *value;
6386 d = array_ref(array, 1, &i,
6387 -1 /* varlenarray */ ,
6388 -1 /* TEXT's typlen */ ,
6389 false /* TEXT's typbyval */ ,
6390 TYPALIGN_INT /* TEXT's typalign */ ,
6391 &isnull);
6393 if (isnull)
6394 continue;
6396 s = TextDatumGetCString(d);
6398 ParseLongOption(s, &name, &value);
6399 if (!value)
6401 ereport(WARNING,
6402 (errcode(ERRCODE_SYNTAX_ERROR),
6403 errmsg("could not parse setting for parameter \"%s\"",
6404 name)));
6405 pfree(name);
6406 continue;
6409 *names = lappend(*names, name);
6410 *values = lappend(*values, value);
6412 pfree(s);
6418 * Handle options fetched from pg_db_role_setting.setconfig,
6419 * pg_proc.proconfig, etc. Caller must specify proper context/source/action.
6421 * The array parameter must be an array of TEXT (it must not be NULL).
6423 void
6424 ProcessGUCArray(ArrayType *array,
6425 GucContext context, GucSource source, GucAction action)
6427 List *gucNames;
6428 List *gucValues;
6429 ListCell *lc1;
6430 ListCell *lc2;
6432 TransformGUCArray(array, &gucNames, &gucValues);
6433 forboth(lc1, gucNames, lc2, gucValues)
6435 char *name = lfirst(lc1);
6436 char *value = lfirst(lc2);
6438 (void) set_config_option(name, value,
6439 context, source,
6440 action, true, 0, false);
6442 pfree(name);
6443 pfree(value);
6446 list_free(gucNames);
6447 list_free(gucValues);
6452 * Add an entry to an option array. The array parameter may be NULL
6453 * to indicate the current table entry is NULL.
6455 ArrayType *
6456 GUCArrayAdd(ArrayType *array, const char *name, const char *value)
6458 struct config_generic *record;
6459 Datum datum;
6460 char *newval;
6461 ArrayType *a;
6463 Assert(name);
6464 Assert(value);
6466 /* test if the option is valid and we're allowed to set it */
6467 (void) validate_option_array_item(name, value, false);
6469 /* normalize name (converts obsolete GUC names to modern spellings) */
6470 record = find_option(name, false, true, WARNING);
6471 if (record)
6472 name = record->name;
6474 /* build new item for array */
6475 newval = psprintf("%s=%s", name, value);
6476 datum = CStringGetTextDatum(newval);
6478 if (array)
6480 int index;
6481 bool isnull;
6482 int i;
6484 Assert(ARR_ELEMTYPE(array) == TEXTOID);
6485 Assert(ARR_NDIM(array) == 1);
6486 Assert(ARR_LBOUND(array)[0] == 1);
6488 index = ARR_DIMS(array)[0] + 1; /* add after end */
6490 for (i = 1; i <= ARR_DIMS(array)[0]; i++)
6492 Datum d;
6493 char *current;
6495 d = array_ref(array, 1, &i,
6496 -1 /* varlenarray */ ,
6497 -1 /* TEXT's typlen */ ,
6498 false /* TEXT's typbyval */ ,
6499 TYPALIGN_INT /* TEXT's typalign */ ,
6500 &isnull);
6501 if (isnull)
6502 continue;
6503 current = TextDatumGetCString(d);
6505 /* check for match up through and including '=' */
6506 if (strncmp(current, newval, strlen(name) + 1) == 0)
6508 index = i;
6509 break;
6513 a = array_set(array, 1, &index,
6514 datum,
6515 false,
6516 -1 /* varlena array */ ,
6517 -1 /* TEXT's typlen */ ,
6518 false /* TEXT's typbyval */ ,
6519 TYPALIGN_INT /* TEXT's typalign */ );
6521 else
6522 a = construct_array_builtin(&datum, 1, TEXTOID);
6524 return a;
6529 * Delete an entry from an option array. The array parameter may be NULL
6530 * to indicate the current table entry is NULL. Also, if the return value
6531 * is NULL then a null should be stored.
6533 ArrayType *
6534 GUCArrayDelete(ArrayType *array, const char *name)
6536 struct config_generic *record;
6537 ArrayType *newarray;
6538 int i;
6539 int index;
6541 Assert(name);
6543 /* test if the option is valid and we're allowed to set it */
6544 (void) validate_option_array_item(name, NULL, false);
6546 /* normalize name (converts obsolete GUC names to modern spellings) */
6547 record = find_option(name, false, true, WARNING);
6548 if (record)
6549 name = record->name;
6551 /* if array is currently null, then surely nothing to delete */
6552 if (!array)
6553 return NULL;
6555 newarray = NULL;
6556 index = 1;
6558 for (i = 1; i <= ARR_DIMS(array)[0]; i++)
6560 Datum d;
6561 char *val;
6562 bool isnull;
6564 d = array_ref(array, 1, &i,
6565 -1 /* varlenarray */ ,
6566 -1 /* TEXT's typlen */ ,
6567 false /* TEXT's typbyval */ ,
6568 TYPALIGN_INT /* TEXT's typalign */ ,
6569 &isnull);
6570 if (isnull)
6571 continue;
6572 val = TextDatumGetCString(d);
6574 /* ignore entry if it's what we want to delete */
6575 if (strncmp(val, name, strlen(name)) == 0
6576 && val[strlen(name)] == '=')
6577 continue;
6579 /* else add it to the output array */
6580 if (newarray)
6581 newarray = array_set(newarray, 1, &index,
6583 false,
6584 -1 /* varlenarray */ ,
6585 -1 /* TEXT's typlen */ ,
6586 false /* TEXT's typbyval */ ,
6587 TYPALIGN_INT /* TEXT's typalign */ );
6588 else
6589 newarray = construct_array_builtin(&d, 1, TEXTOID);
6591 index++;
6594 return newarray;
6599 * Given a GUC array, delete all settings from it that our permission
6600 * level allows: if superuser, delete them all; if regular user, only
6601 * those that are PGC_USERSET or we have permission to set
6603 ArrayType *
6604 GUCArrayReset(ArrayType *array)
6606 ArrayType *newarray;
6607 int i;
6608 int index;
6610 /* if array is currently null, nothing to do */
6611 if (!array)
6612 return NULL;
6614 /* if we're superuser, we can delete everything, so just do it */
6615 if (superuser())
6616 return NULL;
6618 newarray = NULL;
6619 index = 1;
6621 for (i = 1; i <= ARR_DIMS(array)[0]; i++)
6623 Datum d;
6624 char *val;
6625 char *eqsgn;
6626 bool isnull;
6628 d = array_ref(array, 1, &i,
6629 -1 /* varlenarray */ ,
6630 -1 /* TEXT's typlen */ ,
6631 false /* TEXT's typbyval */ ,
6632 TYPALIGN_INT /* TEXT's typalign */ ,
6633 &isnull);
6634 if (isnull)
6635 continue;
6636 val = TextDatumGetCString(d);
6638 eqsgn = strchr(val, '=');
6639 *eqsgn = '\0';
6641 /* skip if we have permission to delete it */
6642 if (validate_option_array_item(val, NULL, true))
6643 continue;
6645 /* else add it to the output array */
6646 if (newarray)
6647 newarray = array_set(newarray, 1, &index,
6649 false,
6650 -1 /* varlenarray */ ,
6651 -1 /* TEXT's typlen */ ,
6652 false /* TEXT's typbyval */ ,
6653 TYPALIGN_INT /* TEXT's typalign */ );
6654 else
6655 newarray = construct_array_builtin(&d, 1, TEXTOID);
6657 index++;
6658 pfree(val);
6661 return newarray;
6665 * Validate a proposed option setting for GUCArrayAdd/Delete/Reset.
6667 * name is the option name. value is the proposed value for the Add case,
6668 * or NULL for the Delete/Reset cases. If skipIfNoPermissions is true, it's
6669 * not an error to have no permissions to set the option.
6671 * Returns true if OK, false if skipIfNoPermissions is true and user does not
6672 * have permission to change this option (all other error cases result in an
6673 * error being thrown).
6675 static bool
6676 validate_option_array_item(const char *name, const char *value,
6677 bool skipIfNoPermissions)
6680 struct config_generic *gconf;
6683 * There are three cases to consider:
6685 * name is a known GUC variable. Check the value normally, check
6686 * permissions normally (i.e., allow if variable is USERSET, or if it's
6687 * SUSET and user is superuser or holds ACL_SET permissions).
6689 * name is not known, but exists or can be created as a placeholder (i.e.,
6690 * it has a valid custom name). We allow this case if you're a superuser,
6691 * otherwise not. Superusers are assumed to know what they're doing. We
6692 * can't allow it for other users, because when the placeholder is
6693 * resolved it might turn out to be a SUSET variable. (With currently
6694 * available infrastructure, we can actually handle such cases within the
6695 * current session --- but once an entry is made in pg_db_role_setting,
6696 * it's assumed to be fully validated.)
6698 * name is not known and can't be created as a placeholder. Throw error,
6699 * unless skipIfNoPermissions is true, in which case return false.
6701 gconf = find_option(name, true, skipIfNoPermissions, ERROR);
6702 if (!gconf)
6704 /* not known, failed to make a placeholder */
6705 return false;
6708 if (gconf->flags & GUC_CUSTOM_PLACEHOLDER)
6711 * We cannot do any meaningful check on the value, so only permissions
6712 * are useful to check.
6714 if (superuser() ||
6715 pg_parameter_aclcheck(name, GetUserId(), ACL_SET) == ACLCHECK_OK)
6716 return true;
6717 if (skipIfNoPermissions)
6718 return false;
6719 ereport(ERROR,
6720 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6721 errmsg("permission denied to set parameter \"%s\"", name)));
6724 /* manual permissions check so we can avoid an error being thrown */
6725 if (gconf->context == PGC_USERSET)
6726 /* ok */ ;
6727 else if (gconf->context == PGC_SUSET &&
6728 (superuser() ||
6729 pg_parameter_aclcheck(name, GetUserId(), ACL_SET) == ACLCHECK_OK))
6730 /* ok */ ;
6731 else if (skipIfNoPermissions)
6732 return false;
6733 /* if a permissions error should be thrown, let set_config_option do it */
6735 /* test for permissions and valid option value */
6736 (void) set_config_option(name, value,
6737 superuser() ? PGC_SUSET : PGC_USERSET,
6738 PGC_S_TEST, GUC_ACTION_SET, false, 0, false);
6740 return true;
6745 * Called by check_hooks that want to override the normal
6746 * ERRCODE_INVALID_PARAMETER_VALUE SQLSTATE for check hook failures.
6748 * Note that GUC_check_errmsg() etc are just macros that result in a direct
6749 * assignment to the associated variables. That is ugly, but forced by the
6750 * limitations of C's macro mechanisms.
6752 void
6753 GUC_check_errcode(int sqlerrcode)
6755 GUC_check_errcode_value = sqlerrcode;
6760 * Convenience functions to manage calling a variable's check_hook.
6761 * These mostly take care of the protocol for letting check hooks supply
6762 * portions of the error report on failure.
6765 static bool
6766 call_bool_check_hook(struct config_bool *conf, bool *newval, void **extra,
6767 GucSource source, int elevel)
6769 /* Quick success if no hook */
6770 if (!conf->check_hook)
6771 return true;
6773 /* Reset variables that might be set by hook */
6774 GUC_check_errcode_value = ERRCODE_INVALID_PARAMETER_VALUE;
6775 GUC_check_errmsg_string = NULL;
6776 GUC_check_errdetail_string = NULL;
6777 GUC_check_errhint_string = NULL;
6779 if (!conf->check_hook(newval, extra, source))
6781 ereport(elevel,
6782 (errcode(GUC_check_errcode_value),
6783 GUC_check_errmsg_string ?
6784 errmsg_internal("%s", GUC_check_errmsg_string) :
6785 errmsg("invalid value for parameter \"%s\": %d",
6786 conf->gen.name, (int) *newval),
6787 GUC_check_errdetail_string ?
6788 errdetail_internal("%s", GUC_check_errdetail_string) : 0,
6789 GUC_check_errhint_string ?
6790 errhint("%s", GUC_check_errhint_string) : 0));
6791 /* Flush any strings created in ErrorContext */
6792 FlushErrorState();
6793 return false;
6796 return true;
6799 static bool
6800 call_int_check_hook(struct config_int *conf, int *newval, void **extra,
6801 GucSource source, int elevel)
6803 /* Quick success if no hook */
6804 if (!conf->check_hook)
6805 return true;
6807 /* Reset variables that might be set by hook */
6808 GUC_check_errcode_value = ERRCODE_INVALID_PARAMETER_VALUE;
6809 GUC_check_errmsg_string = NULL;
6810 GUC_check_errdetail_string = NULL;
6811 GUC_check_errhint_string = NULL;
6813 if (!conf->check_hook(newval, extra, source))
6815 ereport(elevel,
6816 (errcode(GUC_check_errcode_value),
6817 GUC_check_errmsg_string ?
6818 errmsg_internal("%s", GUC_check_errmsg_string) :
6819 errmsg("invalid value for parameter \"%s\": %d",
6820 conf->gen.name, *newval),
6821 GUC_check_errdetail_string ?
6822 errdetail_internal("%s", GUC_check_errdetail_string) : 0,
6823 GUC_check_errhint_string ?
6824 errhint("%s", GUC_check_errhint_string) : 0));
6825 /* Flush any strings created in ErrorContext */
6826 FlushErrorState();
6827 return false;
6830 return true;
6833 static bool
6834 call_real_check_hook(struct config_real *conf, double *newval, void **extra,
6835 GucSource source, int elevel)
6837 /* Quick success if no hook */
6838 if (!conf->check_hook)
6839 return true;
6841 /* Reset variables that might be set by hook */
6842 GUC_check_errcode_value = ERRCODE_INVALID_PARAMETER_VALUE;
6843 GUC_check_errmsg_string = NULL;
6844 GUC_check_errdetail_string = NULL;
6845 GUC_check_errhint_string = NULL;
6847 if (!conf->check_hook(newval, extra, source))
6849 ereport(elevel,
6850 (errcode(GUC_check_errcode_value),
6851 GUC_check_errmsg_string ?
6852 errmsg_internal("%s", GUC_check_errmsg_string) :
6853 errmsg("invalid value for parameter \"%s\": %g",
6854 conf->gen.name, *newval),
6855 GUC_check_errdetail_string ?
6856 errdetail_internal("%s", GUC_check_errdetail_string) : 0,
6857 GUC_check_errhint_string ?
6858 errhint("%s", GUC_check_errhint_string) : 0));
6859 /* Flush any strings created in ErrorContext */
6860 FlushErrorState();
6861 return false;
6864 return true;
6867 static bool
6868 call_string_check_hook(struct config_string *conf, char **newval, void **extra,
6869 GucSource source, int elevel)
6871 volatile bool result = true;
6873 /* Quick success if no hook */
6874 if (!conf->check_hook)
6875 return true;
6878 * If elevel is ERROR, or if the check_hook itself throws an elog
6879 * (undesirable, but not always avoidable), make sure we don't leak the
6880 * already-malloc'd newval string.
6882 PG_TRY();
6884 /* Reset variables that might be set by hook */
6885 GUC_check_errcode_value = ERRCODE_INVALID_PARAMETER_VALUE;
6886 GUC_check_errmsg_string = NULL;
6887 GUC_check_errdetail_string = NULL;
6888 GUC_check_errhint_string = NULL;
6890 if (!conf->check_hook(newval, extra, source))
6892 ereport(elevel,
6893 (errcode(GUC_check_errcode_value),
6894 GUC_check_errmsg_string ?
6895 errmsg_internal("%s", GUC_check_errmsg_string) :
6896 errmsg("invalid value for parameter \"%s\": \"%s\"",
6897 conf->gen.name, *newval ? *newval : ""),
6898 GUC_check_errdetail_string ?
6899 errdetail_internal("%s", GUC_check_errdetail_string) : 0,
6900 GUC_check_errhint_string ?
6901 errhint("%s", GUC_check_errhint_string) : 0));
6902 /* Flush any strings created in ErrorContext */
6903 FlushErrorState();
6904 result = false;
6907 PG_CATCH();
6909 guc_free(*newval);
6910 PG_RE_THROW();
6912 PG_END_TRY();
6914 return result;
6917 static bool
6918 call_enum_check_hook(struct config_enum *conf, int *newval, void **extra,
6919 GucSource source, int elevel)
6921 /* Quick success if no hook */
6922 if (!conf->check_hook)
6923 return true;
6925 /* Reset variables that might be set by hook */
6926 GUC_check_errcode_value = ERRCODE_INVALID_PARAMETER_VALUE;
6927 GUC_check_errmsg_string = NULL;
6928 GUC_check_errdetail_string = NULL;
6929 GUC_check_errhint_string = NULL;
6931 if (!conf->check_hook(newval, extra, source))
6933 ereport(elevel,
6934 (errcode(GUC_check_errcode_value),
6935 GUC_check_errmsg_string ?
6936 errmsg_internal("%s", GUC_check_errmsg_string) :
6937 errmsg("invalid value for parameter \"%s\": \"%s\"",
6938 conf->gen.name,
6939 config_enum_lookup_by_value(conf, *newval)),
6940 GUC_check_errdetail_string ?
6941 errdetail_internal("%s", GUC_check_errdetail_string) : 0,
6942 GUC_check_errhint_string ?
6943 errhint("%s", GUC_check_errhint_string) : 0));
6944 /* Flush any strings created in ErrorContext */
6945 FlushErrorState();
6946 return false;
6949 return true;