PostgreSQL Source Code  git master
guc.c
Go to the documentation of this file.
1 /*--------------------------------------------------------------------
2  * guc.c
3  *
4  * Support for grand unified configuration scheme, including SET
5  * command, configuration file, and command line options.
6  *
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.
13  *
14  * See src/backend/utils/misc/README for more information.
15  *
16  *
17  * Copyright (c) 2000-2023, PostgreSQL Global Development Group
18  * Written by Peter Eisentraut <peter_e@gmx.net>.
19  *
20  * IDENTIFICATION
21  * src/backend/utils/misc/guc.c
22  *
23  *--------------------------------------------------------------------
24  */
25 #include "postgres.h"
26 
27 #include <limits.h>
28 #include <sys/stat.h>
29 #include <unistd.h>
30 
31 #include "access/xact.h"
32 #include "access/xlog.h"
33 #include "catalog/objectaccess.h"
34 #include "catalog/pg_authid.h"
36 #include "guc_internal.h"
37 #include "libpq/pqformat.h"
38 #include "parser/scansup.h"
39 #include "port/pg_bitutils.h"
40 #include "storage/fd.h"
41 #include "storage/lwlock.h"
42 #include "storage/shmem.h"
43 #include "tcop/tcopprot.h"
44 #include "utils/acl.h"
45 #include "utils/backend_status.h"
46 #include "utils/builtins.h"
47 #include "utils/conffiles.h"
48 #include "utils/float.h"
49 #include "utils/guc_tables.h"
50 #include "utils/memutils.h"
51 #include "utils/timestamp.h"
52 
53 
54 #define CONFIG_FILENAME "postgresql.conf"
55 #define HBA_FILENAME "pg_hba.conf"
56 #define IDENT_FILENAME "pg_ident.conf"
57 
58 #ifdef EXEC_BACKEND
59 #define CONFIG_EXEC_PARAMS "global/config_exec_params"
60 #define CONFIG_EXEC_PARAMS_NEW "global/config_exec_params.new"
61 #endif
62 
63 /*
64  * Precision with which REAL type guc values are to be printed for GUC
65  * serialization.
66  */
67 #define REALTYPE_PRECISION 17
68 
70 
72 
73 /* global variables for check hook support */
77 
78 /* Kluge: for speed, we examine this GUC variable's value directly */
79 extern bool in_hot_standby_guc;
80 
81 
82 /*
83  * Unit conversion tables.
84  *
85  * There are two tables, one for memory units, and another for time units.
86  * For each supported conversion from one unit to another, we have an entry
87  * in the table.
88  *
89  * To keep things simple, and to avoid possible roundoff error,
90  * conversions are never chained. There needs to be a direct conversion
91  * between all units (of the same type).
92  *
93  * The conversions for each base unit must be kept in order from greatest to
94  * smallest human-friendly unit; convert_xxx_from_base_unit() rely on that.
95  * (The order of the base-unit groups does not matter.)
96  */
97 #define MAX_UNIT_LEN 3 /* length of longest recognized unit string */
98 
99 typedef struct
100 {
101  char unit[MAX_UNIT_LEN + 1]; /* unit, as a string, like "kB" or
102  * "min" */
103  int base_unit; /* GUC_UNIT_XXX */
104  double multiplier; /* Factor for converting unit -> base_unit */
106 
107 /* Ensure that the constants in the tables don't overflow or underflow */
108 #if BLCKSZ < 1024 || BLCKSZ > (1024*1024)
109 #error BLCKSZ must be between 1KB and 1MB
110 #endif
111 #if XLOG_BLCKSZ < 1024 || XLOG_BLCKSZ > (1024*1024)
112 #error XLOG_BLCKSZ must be between 1KB and 1MB
113 #endif
114 
115 static const char *memory_units_hint = gettext_noop("Valid units for this parameter are \"B\", \"kB\", \"MB\", \"GB\", and \"TB\".");
116 
118 {
119  {"TB", GUC_UNIT_BYTE, 1024.0 * 1024.0 * 1024.0 * 1024.0},
120  {"GB", GUC_UNIT_BYTE, 1024.0 * 1024.0 * 1024.0},
121  {"MB", GUC_UNIT_BYTE, 1024.0 * 1024.0},
122  {"kB", GUC_UNIT_BYTE, 1024.0},
123  {"B", GUC_UNIT_BYTE, 1.0},
124 
125  {"TB", GUC_UNIT_KB, 1024.0 * 1024.0 * 1024.0},
126  {"GB", GUC_UNIT_KB, 1024.0 * 1024.0},
127  {"MB", GUC_UNIT_KB, 1024.0},
128  {"kB", GUC_UNIT_KB, 1.0},
129  {"B", GUC_UNIT_KB, 1.0 / 1024.0},
130 
131  {"TB", GUC_UNIT_MB, 1024.0 * 1024.0},
132  {"GB", GUC_UNIT_MB, 1024.0},
133  {"MB", GUC_UNIT_MB, 1.0},
134  {"kB", GUC_UNIT_MB, 1.0 / 1024.0},
135  {"B", GUC_UNIT_MB, 1.0 / (1024.0 * 1024.0)},
136 
137  {"TB", GUC_UNIT_BLOCKS, (1024.0 * 1024.0 * 1024.0) / (BLCKSZ / 1024)},
138  {"GB", GUC_UNIT_BLOCKS, (1024.0 * 1024.0) / (BLCKSZ / 1024)},
139  {"MB", GUC_UNIT_BLOCKS, 1024.0 / (BLCKSZ / 1024)},
140  {"kB", GUC_UNIT_BLOCKS, 1.0 / (BLCKSZ / 1024)},
141  {"B", GUC_UNIT_BLOCKS, 1.0 / BLCKSZ},
142 
143  {"TB", GUC_UNIT_XBLOCKS, (1024.0 * 1024.0 * 1024.0) / (XLOG_BLCKSZ / 1024)},
144  {"GB", GUC_UNIT_XBLOCKS, (1024.0 * 1024.0) / (XLOG_BLCKSZ / 1024)},
145  {"MB", GUC_UNIT_XBLOCKS, 1024.0 / (XLOG_BLCKSZ / 1024)},
146  {"kB", GUC_UNIT_XBLOCKS, 1.0 / (XLOG_BLCKSZ / 1024)},
147  {"B", GUC_UNIT_XBLOCKS, 1.0 / XLOG_BLCKSZ},
148 
149  {""} /* end of table marker */
150 };
151 
152 static const char *time_units_hint = gettext_noop("Valid units for this parameter are \"us\", \"ms\", \"s\", \"min\", \"h\", and \"d\".");
153 
155 {
156  {"d", GUC_UNIT_MS, 1000 * 60 * 60 * 24},
157  {"h", GUC_UNIT_MS, 1000 * 60 * 60},
158  {"min", GUC_UNIT_MS, 1000 * 60},
159  {"s", GUC_UNIT_MS, 1000},
160  {"ms", GUC_UNIT_MS, 1},
161  {"us", GUC_UNIT_MS, 1.0 / 1000},
162 
163  {"d", GUC_UNIT_S, 60 * 60 * 24},
164  {"h", GUC_UNIT_S, 60 * 60},
165  {"min", GUC_UNIT_S, 60},
166  {"s", GUC_UNIT_S, 1},
167  {"ms", GUC_UNIT_S, 1.0 / 1000},
168  {"us", GUC_UNIT_S, 1.0 / (1000 * 1000)},
169 
170  {"d", GUC_UNIT_MIN, 60 * 24},
171  {"h", GUC_UNIT_MIN, 60},
172  {"min", GUC_UNIT_MIN, 1},
173  {"s", GUC_UNIT_MIN, 1.0 / 60},
174  {"ms", GUC_UNIT_MIN, 1.0 / (1000 * 60)},
175  {"us", GUC_UNIT_MIN, 1.0 / (1000 * 1000 * 60)},
176 
177  {""} /* end of table marker */
178 };
179 
180 /*
181  * To allow continued support of obsolete names for GUC variables, we apply
182  * the following mappings to any unrecognized name. Note that an old name
183  * should be mapped to a new one only if the new variable has very similar
184  * semantics to the old.
185  */
186 static const char *const map_old_guc_names[] = {
187  "sort_mem", "work_mem",
188  "vacuum_mem", "maintenance_work_mem",
189  NULL
190 };
191 
192 
193 /* Memory context holding all GUC-related data */
195 
196 /*
197  * We use a dynahash table to look up GUCs by name, or to iterate through
198  * all the GUCs. The gucname field is redundant with gucvar->name, but
199  * dynahash makes it too painful to not store the hash key separately.
200  */
201 typedef struct
202 {
203  const char *gucname; /* hash key */
204  struct config_generic *gucvar; /* -> GUC's defining structure */
205 } GUCHashEntry;
206 
207 static HTAB *guc_hashtab; /* entries are GUCHashEntrys */
208 
209 /*
210  * In addition to the hash table, variables having certain properties are
211  * linked into these lists, so that we can find them without scanning the
212  * whole hash table. In most applications, only a small fraction of the
213  * GUCs appear in these lists at any given time. The usage of the stack
214  * and report lists is stylized enough that they can be slists, but the
215  * nondef list has to be a dlist to avoid O(N) deletes in common cases.
216  */
217 static dlist_head guc_nondef_list; /* list of variables that have source
218  * different from PGC_S_DEFAULT */
219 static slist_head guc_stack_list; /* list of variables that have non-NULL
220  * stack */
221 static slist_head guc_report_list; /* list of variables that have the
222  * GUC_NEEDS_REPORT bit set in status */
223 
224 static bool reporting_enabled; /* true to enable GUC_REPORT */
225 
226 static int GUCNestLevel = 0; /* 1 when in main transaction */
227 
228 static int guc_var_compare(const void *a, const void *b);
229 static uint32 guc_name_hash(const void *key, Size keysize);
230 static int guc_name_match(const void *key1, const void *key2, Size keysize);
231 static void InitializeGUCOptionsFromEnvironment(void);
232 static void InitializeOneGUCOption(struct config_generic *gconf);
233 static void RemoveGUCFromLists(struct config_generic *gconf);
234 static void set_guc_source(struct config_generic *gconf, GucSource newsource);
235 static void pg_timezone_abbrev_initialize(void);
236 static void push_old_value(struct config_generic *gconf, GucAction action);
237 static void ReportGUCOption(struct config_generic *record);
238 static void set_config_sourcefile(const char *name, char *sourcefile,
239  int sourceline);
241  struct config_string *pHolder,
242  GucStack *stack,
243  const char *curvalue,
244  GucContext curscontext, GucSource cursource,
245  Oid cursrole);
246 static bool validate_option_array_item(const char *name, const char *value,
247  bool user_set, bool skipIfNoPermissions);
248 static void write_auto_conf_file(int fd, const char *filename, ConfigVariable *head);
249 static void replace_auto_config_value(ConfigVariable **head_p, ConfigVariable **tail_p,
250  const char *name, const char *value);
251 static bool valid_custom_variable_name(const char *name);
252 static void do_serialize(char **destptr, Size *maxbytes,
253  const char *fmt,...) pg_attribute_printf(3, 4);
254 static bool call_bool_check_hook(struct config_bool *conf, bool *newval,
255  void **extra, GucSource source, int elevel);
256 static bool call_int_check_hook(struct config_int *conf, int *newval,
257  void **extra, GucSource source, int elevel);
258 static bool call_real_check_hook(struct config_real *conf, double *newval,
259  void **extra, GucSource source, int elevel);
260 static bool call_string_check_hook(struct config_string *conf, char **newval,
261  void **extra, GucSource source, int elevel);
262 static bool call_enum_check_hook(struct config_enum *conf, int *newval,
263  void **extra, GucSource source, int elevel);
264 
265 
266 /*
267  * This function handles both actual config file (re)loads and execution of
268  * show_all_file_settings() (i.e., the pg_file_settings view). In the latter
269  * case we don't apply any of the settings, but we make all the usual validity
270  * checks, and we return the ConfigVariable list so that it can be printed out
271  * by show_all_file_settings().
272  */
274 ProcessConfigFileInternal(GucContext context, bool applySettings, int elevel)
275 {
276  bool error = false;
277  bool applying = false;
278  const char *ConfFileWithError;
279  ConfigVariable *item,
280  *head,
281  *tail;
283  GUCHashEntry *hentry;
284 
285  /* Parse the main config file into a list of option names and values */
286  ConfFileWithError = ConfigFileName;
287  head = tail = NULL;
288 
289  if (!ParseConfigFile(ConfigFileName, true,
290  NULL, 0, CONF_FILE_START_DEPTH, elevel,
291  &head, &tail))
292  {
293  /* Syntax error(s) detected in the file, so bail out */
294  error = true;
295  goto bail_out;
296  }
297 
298  /*
299  * Parse the PG_AUTOCONF_FILENAME file, if present, after the main file to
300  * replace any parameters set by ALTER SYSTEM command. Because this file
301  * is in the data directory, we can't read it until the DataDir has been
302  * set.
303  */
304  if (DataDir)
305  {
307  NULL, 0, CONF_FILE_START_DEPTH, elevel,
308  &head, &tail))
309  {
310  /* Syntax error(s) detected in the file, so bail out */
311  error = true;
312  ConfFileWithError = PG_AUTOCONF_FILENAME;
313  goto bail_out;
314  }
315  }
316  else
317  {
318  /*
319  * If DataDir is not set, the PG_AUTOCONF_FILENAME file cannot be
320  * read. In this case, we don't want to accept any settings but
321  * data_directory from postgresql.conf, because they might be
322  * overwritten with settings in the PG_AUTOCONF_FILENAME file which
323  * will be read later. OTOH, since data_directory isn't allowed in the
324  * PG_AUTOCONF_FILENAME file, it will never be overwritten later.
325  */
326  ConfigVariable *newlist = NULL;
327 
328  /*
329  * Prune all items except the last "data_directory" from the list.
330  */
331  for (item = head; item; item = item->next)
332  {
333  if (!item->ignore &&
334  strcmp(item->name, "data_directory") == 0)
335  newlist = item;
336  }
337 
338  if (newlist)
339  newlist->next = NULL;
340  head = tail = newlist;
341 
342  /*
343  * Quick exit if data_directory is not present in file.
344  *
345  * We need not do any further processing, in particular we don't set
346  * PgReloadTime; that will be set soon by subsequent full loading of
347  * the config file.
348  */
349  if (head == NULL)
350  goto bail_out;
351  }
352 
353  /*
354  * Mark all extant GUC variables as not present in the config file. We
355  * need this so that we can tell below which ones have been removed from
356  * the file since we last processed it.
357  */
359  while ((hentry = (GUCHashEntry *) hash_seq_search(&status)) != NULL)
360  {
361  struct config_generic *gconf = hentry->gucvar;
362 
363  gconf->status &= ~GUC_IS_IN_FILE;
364  }
365 
366  /*
367  * Check if all the supplied option names are valid, as an additional
368  * quasi-syntactic check on the validity of the config file. It is
369  * important that the postmaster and all backends agree on the results of
370  * this phase, else we will have strange inconsistencies about which
371  * processes accept a config file update and which don't. Hence, unknown
372  * custom variable names have to be accepted without complaint. For the
373  * same reason, we don't attempt to validate the options' values here.
374  *
375  * In addition, the GUC_IS_IN_FILE flag is set on each existing GUC
376  * variable mentioned in the file; and we detect duplicate entries in the
377  * file and mark the earlier occurrences as ignorable.
378  */
379  for (item = head; item; item = item->next)
380  {
381  struct config_generic *record;
382 
383  /* Ignore anything already marked as ignorable */
384  if (item->ignore)
385  continue;
386 
387  /*
388  * Try to find the variable; but do not create a custom placeholder if
389  * it's not there already.
390  */
391  record = find_option(item->name, false, true, elevel);
392 
393  if (record)
394  {
395  /* If it's already marked, then this is a duplicate entry */
396  if (record->status & GUC_IS_IN_FILE)
397  {
398  /*
399  * Mark the earlier occurrence(s) as dead/ignorable. We could
400  * avoid the O(N^2) behavior here with some additional state,
401  * but it seems unlikely to be worth the trouble.
402  */
403  ConfigVariable *pitem;
404 
405  for (pitem = head; pitem != item; pitem = pitem->next)
406  {
407  if (!pitem->ignore &&
408  strcmp(pitem->name, item->name) == 0)
409  pitem->ignore = true;
410  }
411  }
412  /* Now mark it as present in file */
413  record->status |= GUC_IS_IN_FILE;
414  }
415  else if (!valid_custom_variable_name(item->name))
416  {
417  /* Invalid non-custom variable, so complain */
418  ereport(elevel,
419  (errcode(ERRCODE_UNDEFINED_OBJECT),
420  errmsg("unrecognized configuration parameter \"%s\" in file \"%s\" line %d",
421  item->name,
422  item->filename, item->sourceline)));
423  item->errmsg = pstrdup("unrecognized configuration parameter");
424  error = true;
425  ConfFileWithError = item->filename;
426  }
427  }
428 
429  /*
430  * If we've detected any errors so far, we don't want to risk applying any
431  * changes.
432  */
433  if (error)
434  goto bail_out;
435 
436  /* Otherwise, set flag that we're beginning to apply changes */
437  applying = true;
438 
439  /*
440  * Check for variables having been removed from the config file, and
441  * revert their reset values (and perhaps also effective values) to the
442  * boot-time defaults. If such a variable can't be changed after startup,
443  * report that and continue.
444  */
446  while ((hentry = (GUCHashEntry *) hash_seq_search(&status)) != NULL)
447  {
448  struct config_generic *gconf = hentry->gucvar;
449  GucStack *stack;
450 
451  if (gconf->reset_source != PGC_S_FILE ||
452  (gconf->status & GUC_IS_IN_FILE))
453  continue;
454  if (gconf->context < PGC_SIGHUP)
455  {
456  /* The removal can't be effective without a restart */
457  gconf->status |= GUC_PENDING_RESTART;
458  ereport(elevel,
459  (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
460  errmsg("parameter \"%s\" cannot be changed without restarting the server",
461  gconf->name)));
462  record_config_file_error(psprintf("parameter \"%s\" cannot be changed without restarting the server",
463  gconf->name),
464  NULL, 0,
465  &head, &tail);
466  error = true;
467  continue;
468  }
469 
470  /* No more to do if we're just doing show_all_file_settings() */
471  if (!applySettings)
472  continue;
473 
474  /*
475  * Reset any "file" sources to "default", else set_config_option will
476  * not override those settings.
477  */
478  if (gconf->reset_source == PGC_S_FILE)
479  gconf->reset_source = PGC_S_DEFAULT;
480  if (gconf->source == PGC_S_FILE)
482  for (stack = gconf->stack; stack; stack = stack->prev)
483  {
484  if (stack->source == PGC_S_FILE)
486  }
487 
488  /* Now we can re-apply the wired-in default (i.e., the boot_val) */
489  if (set_config_option(gconf->name, NULL,
491  GUC_ACTION_SET, true, 0, false) > 0)
492  {
493  /* Log the change if appropriate */
494  if (context == PGC_SIGHUP)
495  ereport(elevel,
496  (errmsg("parameter \"%s\" removed from configuration file, reset to default",
497  gconf->name)));
498  }
499  }
500 
501  /*
502  * Restore any variables determined by environment variables or
503  * dynamically-computed defaults. This is a no-op except in the case
504  * where one of these had been in the config file and is now removed.
505  *
506  * In particular, we *must not* do this during the postmaster's initial
507  * loading of the file, since the timezone functions in particular should
508  * be run only after initialization is complete.
509  *
510  * XXX this is an unmaintainable crock, because we have to know how to set
511  * (or at least what to call to set) every non-PGC_INTERNAL variable that
512  * could potentially have PGC_S_DYNAMIC_DEFAULT or PGC_S_ENV_VAR source.
513  */
514  if (context == PGC_SIGHUP && applySettings)
515  {
518  /* this selects SQL_ASCII in processes not connected to a database */
519  SetConfigOption("client_encoding", GetDatabaseEncodingName(),
521  }
522 
523  /*
524  * Now apply the values from the config file.
525  */
526  for (item = head; item; item = item->next)
527  {
528  char *pre_value = NULL;
529  int scres;
530 
531  /* Ignore anything marked as ignorable */
532  if (item->ignore)
533  continue;
534 
535  /* In SIGHUP cases in the postmaster, we want to report changes */
536  if (context == PGC_SIGHUP && applySettings && !IsUnderPostmaster)
537  {
538  const char *preval = GetConfigOption(item->name, true, false);
539 
540  /* If option doesn't exist yet or is NULL, treat as empty string */
541  if (!preval)
542  preval = "";
543  /* must dup, else might have dangling pointer below */
544  pre_value = pstrdup(preval);
545  }
546 
547  scres = set_config_option(item->name, item->value,
549  GUC_ACTION_SET, applySettings, 0, false);
550  if (scres > 0)
551  {
552  /* variable was updated, so log the change if appropriate */
553  if (pre_value)
554  {
555  const char *post_value = GetConfigOption(item->name, true, false);
556 
557  if (!post_value)
558  post_value = "";
559  if (strcmp(pre_value, post_value) != 0)
560  ereport(elevel,
561  (errmsg("parameter \"%s\" changed to \"%s\"",
562  item->name, item->value)));
563  }
564  item->applied = true;
565  }
566  else if (scres == 0)
567  {
568  error = true;
569  item->errmsg = pstrdup("setting could not be applied");
570  ConfFileWithError = item->filename;
571  }
572  else
573  {
574  /* no error, but variable's active value was not changed */
575  item->applied = true;
576  }
577 
578  /*
579  * We should update source location unless there was an error, since
580  * even if the active value didn't change, the reset value might have.
581  * (In the postmaster, there won't be a difference, but it does matter
582  * in backends.)
583  */
584  if (scres != 0 && applySettings)
585  set_config_sourcefile(item->name, item->filename,
586  item->sourceline);
587 
588  if (pre_value)
589  pfree(pre_value);
590  }
591 
592  /* Remember when we last successfully loaded the config file. */
593  if (applySettings)
595 
596 bail_out:
597  if (error && applySettings)
598  {
599  /* During postmaster startup, any error is fatal */
600  if (context == PGC_POSTMASTER)
601  ereport(ERROR,
602  (errcode(ERRCODE_CONFIG_FILE_ERROR),
603  errmsg("configuration file \"%s\" contains errors",
604  ConfFileWithError)));
605  else if (applying)
606  ereport(elevel,
607  (errcode(ERRCODE_CONFIG_FILE_ERROR),
608  errmsg("configuration file \"%s\" contains errors; unaffected changes were applied",
609  ConfFileWithError)));
610  else
611  ereport(elevel,
612  (errcode(ERRCODE_CONFIG_FILE_ERROR),
613  errmsg("configuration file \"%s\" contains errors; no changes were applied",
614  ConfFileWithError)));
615  }
616 
617  /* Successful or otherwise, return the collected data list */
618  return head;
619 }
620 
621 
622 /*
623  * Some infrastructure for GUC-related memory allocation
624  *
625  * These functions are generally modeled on libc's malloc/realloc/etc,
626  * but any OOM issue is reported at the specified elevel.
627  * (Thus, control returns only if that's less than ERROR.)
628  */
629 void *
630 guc_malloc(int elevel, size_t size)
631 {
632  void *data;
633 
636  if (unlikely(data == NULL))
637  ereport(elevel,
638  (errcode(ERRCODE_OUT_OF_MEMORY),
639  errmsg("out of memory")));
640  return data;
641 }
642 
643 void *
644 guc_realloc(int elevel, void *old, size_t size)
645 {
646  void *data;
647 
648  if (old != NULL)
649  {
650  /* This is to help catch old code that malloc's GUC data. */
652  data = repalloc_extended(old, size,
654  }
655  else
656  {
657  /* Like realloc(3), but not like repalloc(), we allow old == NULL. */
660  }
661  if (unlikely(data == NULL))
662  ereport(elevel,
663  (errcode(ERRCODE_OUT_OF_MEMORY),
664  errmsg("out of memory")));
665  return data;
666 }
667 
668 char *
669 guc_strdup(int elevel, const char *src)
670 {
671  char *data;
672  size_t len = strlen(src) + 1;
673 
674  data = guc_malloc(elevel, len);
675  if (likely(data != NULL))
676  memcpy(data, src, len);
677  return data;
678 }
679 
680 void
681 guc_free(void *ptr)
682 {
683  /*
684  * Historically, GUC-related code has relied heavily on the ability to do
685  * free(NULL), so we allow that here even though pfree() doesn't.
686  */
687  if (ptr != NULL)
688  {
689  /* This is to help catch old code that malloc's GUC data. */
691  pfree(ptr);
692  }
693 }
694 
695 
696 /*
697  * Detect whether strval is referenced anywhere in a GUC string item
698  */
699 static bool
700 string_field_used(struct config_string *conf, char *strval)
701 {
702  GucStack *stack;
703 
704  if (strval == *(conf->variable) ||
705  strval == conf->reset_val ||
706  strval == conf->boot_val)
707  return true;
708  for (stack = conf->gen.stack; stack; stack = stack->prev)
709  {
710  if (strval == stack->prior.val.stringval ||
711  strval == stack->masked.val.stringval)
712  return true;
713  }
714  return false;
715 }
716 
717 /*
718  * Support for assigning to a field of a string GUC item. Free the prior
719  * value if it's not referenced anywhere else in the item (including stacked
720  * states).
721  */
722 static void
723 set_string_field(struct config_string *conf, char **field, char *newval)
724 {
725  char *oldval = *field;
726 
727  /* Do the assignment */
728  *field = newval;
729 
730  /* Free old value if it's not NULL and isn't referenced anymore */
731  if (oldval && !string_field_used(conf, oldval))
732  guc_free(oldval);
733 }
734 
735 /*
736  * Detect whether an "extra" struct is referenced anywhere in a GUC item
737  */
738 static bool
739 extra_field_used(struct config_generic *gconf, void *extra)
740 {
741  GucStack *stack;
742 
743  if (extra == gconf->extra)
744  return true;
745  switch (gconf->vartype)
746  {
747  case PGC_BOOL:
748  if (extra == ((struct config_bool *) gconf)->reset_extra)
749  return true;
750  break;
751  case PGC_INT:
752  if (extra == ((struct config_int *) gconf)->reset_extra)
753  return true;
754  break;
755  case PGC_REAL:
756  if (extra == ((struct config_real *) gconf)->reset_extra)
757  return true;
758  break;
759  case PGC_STRING:
760  if (extra == ((struct config_string *) gconf)->reset_extra)
761  return true;
762  break;
763  case PGC_ENUM:
764  if (extra == ((struct config_enum *) gconf)->reset_extra)
765  return true;
766  break;
767  }
768  for (stack = gconf->stack; stack; stack = stack->prev)
769  {
770  if (extra == stack->prior.extra ||
771  extra == stack->masked.extra)
772  return true;
773  }
774 
775  return false;
776 }
777 
778 /*
779  * Support for assigning to an "extra" field of a GUC item. Free the prior
780  * value if it's not referenced anywhere else in the item (including stacked
781  * states).
782  */
783 static void
784 set_extra_field(struct config_generic *gconf, void **field, void *newval)
785 {
786  void *oldval = *field;
787 
788  /* Do the assignment */
789  *field = newval;
790 
791  /* Free old value if it's not NULL and isn't referenced anymore */
792  if (oldval && !extra_field_used(gconf, oldval))
793  guc_free(oldval);
794 }
795 
796 /*
797  * Support for copying a variable's active value into a stack entry.
798  * The "extra" field associated with the active value is copied, too.
799  *
800  * NB: be sure stringval and extra fields of a new stack entry are
801  * initialized to NULL before this is used, else we'll try to guc_free() them.
802  */
803 static void
805 {
806  switch (gconf->vartype)
807  {
808  case PGC_BOOL:
809  val->val.boolval =
810  *((struct config_bool *) gconf)->variable;
811  break;
812  case PGC_INT:
813  val->val.intval =
814  *((struct config_int *) gconf)->variable;
815  break;
816  case PGC_REAL:
817  val->val.realval =
818  *((struct config_real *) gconf)->variable;
819  break;
820  case PGC_STRING:
821  set_string_field((struct config_string *) gconf,
822  &(val->val.stringval),
823  *((struct config_string *) gconf)->variable);
824  break;
825  case PGC_ENUM:
826  val->val.enumval =
827  *((struct config_enum *) gconf)->variable;
828  break;
829  }
830  set_extra_field(gconf, &(val->extra), gconf->extra);
831 }
832 
833 /*
834  * Support for discarding a no-longer-needed value in a stack entry.
835  * The "extra" field associated with the stack entry is cleared, too.
836  */
837 static void
839 {
840  switch (gconf->vartype)
841  {
842  case PGC_BOOL:
843  case PGC_INT:
844  case PGC_REAL:
845  case PGC_ENUM:
846  /* no need to do anything */
847  break;
848  case PGC_STRING:
849  set_string_field((struct config_string *) gconf,
850  &(val->val.stringval),
851  NULL);
852  break;
853  }
854  set_extra_field(gconf, &(val->extra), NULL);
855 }
856 
857 
858 /*
859  * Fetch a palloc'd, sorted array of GUC struct pointers
860  *
861  * The array length is returned into *num_vars.
862  */
863 struct config_generic **
864 get_guc_variables(int *num_vars)
865 {
866  struct config_generic **result;
868  GUCHashEntry *hentry;
869  int i;
870 
871  *num_vars = hash_get_num_entries(guc_hashtab);
872  result = palloc(sizeof(struct config_generic *) * *num_vars);
873 
874  /* Extract pointers from the hash table */
875  i = 0;
877  while ((hentry = (GUCHashEntry *) hash_seq_search(&status)) != NULL)
878  result[i++] = hentry->gucvar;
879  Assert(i == *num_vars);
880 
881  /* Sort by name */
882  qsort(result, *num_vars,
883  sizeof(struct config_generic *), guc_var_compare);
884 
885  return result;
886 }
887 
888 
889 /*
890  * Build the GUC hash table. This is split out so that help_config.c can
891  * extract all the variables without running all of InitializeGUCOptions.
892  * It's not meant for use anyplace else.
893  */
894 void
896 {
897  int size_vars;
898  int num_vars = 0;
899  HASHCTL hash_ctl;
900  GUCHashEntry *hentry;
901  bool found;
902  int i;
903 
904  /*
905  * Create the memory context that will hold all GUC-related data.
906  */
907  Assert(GUCMemoryContext == NULL);
909  "GUCMemoryContext",
911 
912  /*
913  * Count all the built-in variables, and set their vartypes correctly.
914  */
915  for (i = 0; ConfigureNamesBool[i].gen.name; i++)
916  {
917  struct config_bool *conf = &ConfigureNamesBool[i];
918 
919  /* Rather than requiring vartype to be filled in by hand, do this: */
920  conf->gen.vartype = PGC_BOOL;
921  num_vars++;
922  }
923 
924  for (i = 0; ConfigureNamesInt[i].gen.name; i++)
925  {
926  struct config_int *conf = &ConfigureNamesInt[i];
927 
928  conf->gen.vartype = PGC_INT;
929  num_vars++;
930  }
931 
932  for (i = 0; ConfigureNamesReal[i].gen.name; i++)
933  {
934  struct config_real *conf = &ConfigureNamesReal[i];
935 
936  conf->gen.vartype = PGC_REAL;
937  num_vars++;
938  }
939 
940  for (i = 0; ConfigureNamesString[i].gen.name; i++)
941  {
942  struct config_string *conf = &ConfigureNamesString[i];
943 
944  conf->gen.vartype = PGC_STRING;
945  num_vars++;
946  }
947 
948  for (i = 0; ConfigureNamesEnum[i].gen.name; i++)
949  {
950  struct config_enum *conf = &ConfigureNamesEnum[i];
951 
952  conf->gen.vartype = PGC_ENUM;
953  num_vars++;
954  }
955 
956  /*
957  * Create hash table with 20% slack
958  */
959  size_vars = num_vars + num_vars / 4;
960 
961  hash_ctl.keysize = sizeof(char *);
962  hash_ctl.entrysize = sizeof(GUCHashEntry);
963  hash_ctl.hash = guc_name_hash;
964  hash_ctl.match = guc_name_match;
965  hash_ctl.hcxt = GUCMemoryContext;
966  guc_hashtab = hash_create("GUC hash table",
967  size_vars,
968  &hash_ctl,
970 
971  for (i = 0; ConfigureNamesBool[i].gen.name; i++)
972  {
973  struct config_generic *gucvar = &ConfigureNamesBool[i].gen;
974 
975  hentry = (GUCHashEntry *) hash_search(guc_hashtab,
976  &gucvar->name,
977  HASH_ENTER,
978  &found);
979  Assert(!found);
980  hentry->gucvar = gucvar;
981  }
982 
983  for (i = 0; ConfigureNamesInt[i].gen.name; i++)
984  {
985  struct config_generic *gucvar = &ConfigureNamesInt[i].gen;
986 
987  hentry = (GUCHashEntry *) hash_search(guc_hashtab,
988  &gucvar->name,
989  HASH_ENTER,
990  &found);
991  Assert(!found);
992  hentry->gucvar = gucvar;
993  }
994 
995  for (i = 0; ConfigureNamesReal[i].gen.name; i++)
996  {
997  struct config_generic *gucvar = &ConfigureNamesReal[i].gen;
998 
999  hentry = (GUCHashEntry *) hash_search(guc_hashtab,
1000  &gucvar->name,
1001  HASH_ENTER,
1002  &found);
1003  Assert(!found);
1004  hentry->gucvar = gucvar;
1005  }
1006 
1007  for (i = 0; ConfigureNamesString[i].gen.name; i++)
1008  {
1009  struct config_generic *gucvar = &ConfigureNamesString[i].gen;
1010 
1011  hentry = (GUCHashEntry *) hash_search(guc_hashtab,
1012  &gucvar->name,
1013  HASH_ENTER,
1014  &found);
1015  Assert(!found);
1016  hentry->gucvar = gucvar;
1017  }
1018 
1019  for (i = 0; ConfigureNamesEnum[i].gen.name; i++)
1020  {
1021  struct config_generic *gucvar = &ConfigureNamesEnum[i].gen;
1022 
1023  hentry = (GUCHashEntry *) hash_search(guc_hashtab,
1024  &gucvar->name,
1025  HASH_ENTER,
1026  &found);
1027  Assert(!found);
1028  hentry->gucvar = gucvar;
1029  }
1030 
1031  Assert(num_vars == hash_get_num_entries(guc_hashtab));
1032 }
1033 
1034 /*
1035  * Add a new GUC variable to the hash of known variables. The
1036  * hash is expanded if needed.
1037  */
1038 static bool
1039 add_guc_variable(struct config_generic *var, int elevel)
1040 {
1041  GUCHashEntry *hentry;
1042  bool found;
1043 
1044  hentry = (GUCHashEntry *) hash_search(guc_hashtab,
1045  &var->name,
1047  &found);
1048  if (unlikely(hentry == NULL))
1049  {
1050  ereport(elevel,
1051  (errcode(ERRCODE_OUT_OF_MEMORY),
1052  errmsg("out of memory")));
1053  return false; /* out of memory */
1054  }
1055  Assert(!found);
1056  hentry->gucvar = var;
1057  return true;
1058 }
1059 
1060 /*
1061  * Decide whether a proposed custom variable name is allowed.
1062  *
1063  * It must be two or more identifiers separated by dots, where the rules
1064  * for what is an identifier agree with scan.l. (If you change this rule,
1065  * adjust the errdetail in find_option().)
1066  */
1067 static bool
1069 {
1070  bool saw_sep = false;
1071  bool name_start = true;
1072 
1073  for (const char *p = name; *p; p++)
1074  {
1075  if (*p == GUC_QUALIFIER_SEPARATOR)
1076  {
1077  if (name_start)
1078  return false; /* empty name component */
1079  saw_sep = true;
1080  name_start = true;
1081  }
1082  else if (strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1083  "abcdefghijklmnopqrstuvwxyz_", *p) != NULL ||
1084  IS_HIGHBIT_SET(*p))
1085  {
1086  /* okay as first or non-first character */
1087  name_start = false;
1088  }
1089  else if (!name_start && strchr("0123456789$", *p) != NULL)
1090  /* okay as non-first character */ ;
1091  else
1092  return false;
1093  }
1094  if (name_start)
1095  return false; /* empty name component */
1096  /* OK if we found at least one separator */
1097  return saw_sep;
1098 }
1099 
1100 /*
1101  * Create and add a placeholder variable for a custom variable name.
1102  */
1103 static struct config_generic *
1104 add_placeholder_variable(const char *name, int elevel)
1105 {
1106  size_t sz = sizeof(struct config_string) + sizeof(char *);
1107  struct config_string *var;
1108  struct config_generic *gen;
1109 
1110  var = (struct config_string *) guc_malloc(elevel, sz);
1111  if (var == NULL)
1112  return NULL;
1113  memset(var, 0, sz);
1114  gen = &var->gen;
1115 
1116  gen->name = guc_strdup(elevel, name);
1117  if (gen->name == NULL)
1118  {
1119  guc_free(var);
1120  return NULL;
1121  }
1122 
1123  gen->context = PGC_USERSET;
1125  gen->short_desc = "GUC placeholder variable";
1127  gen->vartype = PGC_STRING;
1128 
1129  /*
1130  * The char* is allocated at the end of the struct since we have no
1131  * 'static' place to point to. Note that the current value, as well as
1132  * the boot and reset values, start out NULL.
1133  */
1134  var->variable = (char **) (var + 1);
1135 
1136  if (!add_guc_variable((struct config_generic *) var, elevel))
1137  {
1138  guc_free(unconstify(char *, gen->name));
1139  guc_free(var);
1140  return NULL;
1141  }
1142 
1143  return gen;
1144 }
1145 
1146 /*
1147  * Look up option "name". If it exists, return a pointer to its record.
1148  * Otherwise, if create_placeholders is true and name is a valid-looking
1149  * custom variable name, we'll create and return a placeholder record.
1150  * Otherwise, if skip_errors is true, then we silently return NULL for
1151  * an unrecognized or invalid name. Otherwise, the error is reported at
1152  * error level elevel (and we return NULL if that's less than ERROR).
1153  *
1154  * Note: internal errors, primarily out-of-memory, draw an elevel-level
1155  * report and NULL return regardless of skip_errors. Hence, callers must
1156  * handle a NULL return whenever elevel < ERROR, but they should not need
1157  * to emit any additional error message. (In practice, internal errors
1158  * can only happen when create_placeholders is true, so callers passing
1159  * false need not think terribly hard about this.)
1160  */
1161 struct config_generic *
1162 find_option(const char *name, bool create_placeholders, bool skip_errors,
1163  int elevel)
1164 {
1165  GUCHashEntry *hentry;
1166  int i;
1167 
1168  Assert(name);
1169 
1170  /* Look it up using the hash table. */
1171  hentry = (GUCHashEntry *) hash_search(guc_hashtab,
1172  &name,
1173  HASH_FIND,
1174  NULL);
1175  if (hentry)
1176  return hentry->gucvar;
1177 
1178  /*
1179  * See if the name is an obsolete name for a variable. We assume that the
1180  * set of supported old names is short enough that a brute-force search is
1181  * the best way.
1182  */
1183  for (i = 0; map_old_guc_names[i] != NULL; i += 2)
1184  {
1186  return find_option(map_old_guc_names[i + 1], false,
1187  skip_errors, elevel);
1188  }
1189 
1190  if (create_placeholders)
1191  {
1192  /*
1193  * Check if the name is valid, and if so, add a placeholder. If it
1194  * doesn't contain a separator, don't assume that it was meant to be a
1195  * placeholder.
1196  */
1197  const char *sep = strchr(name, GUC_QUALIFIER_SEPARATOR);
1198 
1199  if (sep != NULL)
1200  {
1201  size_t classLen = sep - name;
1202  ListCell *lc;
1203 
1204  /* The name must be syntactically acceptable ... */
1206  {
1207  if (!skip_errors)
1208  ereport(elevel,
1209  (errcode(ERRCODE_INVALID_NAME),
1210  errmsg("invalid configuration parameter name \"%s\"",
1211  name),
1212  errdetail("Custom parameter names must be two or more simple identifiers separated by dots.")));
1213  return NULL;
1214  }
1215  /* ... and it must not match any previously-reserved prefix */
1216  foreach(lc, reserved_class_prefix)
1217  {
1218  const char *rcprefix = lfirst(lc);
1219 
1220  if (strlen(rcprefix) == classLen &&
1221  strncmp(name, rcprefix, classLen) == 0)
1222  {
1223  if (!skip_errors)
1224  ereport(elevel,
1225  (errcode(ERRCODE_INVALID_NAME),
1226  errmsg("invalid configuration parameter name \"%s\"",
1227  name),
1228  errdetail("\"%s\" is a reserved prefix.",
1229  rcprefix)));
1230  return NULL;
1231  }
1232  }
1233  /* OK, create it */
1234  return add_placeholder_variable(name, elevel);
1235  }
1236  }
1237 
1238  /* Unknown name */
1239  if (!skip_errors)
1240  ereport(elevel,
1241  (errcode(ERRCODE_UNDEFINED_OBJECT),
1242  errmsg("unrecognized configuration parameter \"%s\"",
1243  name)));
1244  return NULL;
1245 }
1246 
1247 
1248 /*
1249  * comparator for qsorting an array of GUC pointers
1250  */
1251 static int
1252 guc_var_compare(const void *a, const void *b)
1253 {
1254  const struct config_generic *confa = *(struct config_generic *const *) a;
1255  const struct config_generic *confb = *(struct config_generic *const *) b;
1256 
1257  return guc_name_compare(confa->name, confb->name);
1258 }
1259 
1260 /*
1261  * the bare comparison function for GUC names
1262  */
1263 int
1264 guc_name_compare(const char *namea, const char *nameb)
1265 {
1266  /*
1267  * The temptation to use strcasecmp() here must be resisted, because the
1268  * hash mapping has to remain stable across setlocale() calls. So, build
1269  * our own with a simple ASCII-only downcasing.
1270  */
1271  while (*namea && *nameb)
1272  {
1273  char cha = *namea++;
1274  char chb = *nameb++;
1275 
1276  if (cha >= 'A' && cha <= 'Z')
1277  cha += 'a' - 'A';
1278  if (chb >= 'A' && chb <= 'Z')
1279  chb += 'a' - 'A';
1280  if (cha != chb)
1281  return cha - chb;
1282  }
1283  if (*namea)
1284  return 1; /* a is longer */
1285  if (*nameb)
1286  return -1; /* b is longer */
1287  return 0;
1288 }
1289 
1290 /*
1291  * Hash function that's compatible with guc_name_compare
1292  */
1293 static uint32
1294 guc_name_hash(const void *key, Size keysize)
1295 {
1296  uint32 result = 0;
1297  const char *name = *(const char *const *) key;
1298 
1299  while (*name)
1300  {
1301  char ch = *name++;
1302 
1303  /* Case-fold in the same way as guc_name_compare */
1304  if (ch >= 'A' && ch <= 'Z')
1305  ch += 'a' - 'A';
1306 
1307  /* Merge into hash ... not very bright, but it needn't be */
1308  result = pg_rotate_left32(result, 5);
1309  result ^= (uint32) ch;
1310  }
1311  return result;
1312 }
1313 
1314 /*
1315  * Dynahash match function to use in guc_hashtab
1316  */
1317 static int
1318 guc_name_match(const void *key1, const void *key2, Size keysize)
1319 {
1320  const char *name1 = *(const char *const *) key1;
1321  const char *name2 = *(const char *const *) key2;
1322 
1323  return guc_name_compare(name1, name2);
1324 }
1325 
1326 
1327 /*
1328  * Convert a GUC name to the form that should be used in pg_parameter_acl.
1329  *
1330  * We need to canonicalize entries since, for example, case should not be
1331  * significant. In addition, we apply the map_old_guc_names[] mapping so that
1332  * any obsolete names will be converted when stored in a new PG version.
1333  * Note however that this function does not verify legality of the name.
1334  *
1335  * The result is a palloc'd string.
1336  */
1337 char *
1339 {
1340  char *result;
1341 
1342  /* Apply old-GUC-name mapping. */
1343  for (int i = 0; map_old_guc_names[i] != NULL; i += 2)
1344  {
1346  {
1347  name = map_old_guc_names[i + 1];
1348  break;
1349  }
1350  }
1351 
1352  /* Apply case-folding that matches guc_name_compare(). */
1353  result = pstrdup(name);
1354  for (char *ptr = result; *ptr != '\0'; ptr++)
1355  {
1356  char ch = *ptr;
1357 
1358  if (ch >= 'A' && ch <= 'Z')
1359  {
1360  ch += 'a' - 'A';
1361  *ptr = ch;
1362  }
1363  }
1364 
1365  return result;
1366 }
1367 
1368 /*
1369  * Check whether we should allow creation of a pg_parameter_acl entry
1370  * for the given name. (This can be applied either before or after
1371  * canonicalizing it.)
1372  */
1373 bool
1375 {
1376  /* OK if the GUC exists. */
1377  if (find_option(name, false, true, DEBUG1) != NULL)
1378  return true;
1379  /* Otherwise, it'd better be a valid custom GUC name. */
1381  return true;
1382  return false;
1383 }
1384 
1385 /*
1386  * Routine in charge of checking that the initial value of a GUC is the
1387  * same when declared and when loaded to prevent anybody looking at the
1388  * C declarations of these GUCS from being fooled by mismatched values.
1389  *
1390  * The following validation rules apply:
1391  * bool - can be false, otherwise must be same as the boot_val
1392  * int - can be 0, otherwise must be same as the boot_val
1393  * real - can be 0.0, otherwise must be same as the boot_val
1394  * string - can be NULL, otherwise must be strcmp equal to the boot_val
1395  * enum - must be same as the boot_val
1396  */
1397 #ifdef USE_ASSERT_CHECKING
1398 static bool
1399 check_GUC_init(struct config_generic *gconf)
1400 {
1401  switch (gconf->vartype)
1402  {
1403  case PGC_BOOL:
1404  {
1405  struct config_bool *conf = (struct config_bool *) gconf;
1406 
1407  if (*conf->variable && !conf->boot_val)
1408  {
1409  elog(LOG, "GUC (PGC_BOOL) %s, boot_val=%d, C-var=%d",
1410  conf->gen.name, conf->boot_val, *conf->variable);
1411  return false;
1412  }
1413  break;
1414  }
1415  case PGC_INT:
1416  {
1417  struct config_int *conf = (struct config_int *) gconf;
1418 
1419  if (*conf->variable != 0 && *conf->variable != conf->boot_val)
1420  {
1421  elog(LOG, "GUC (PGC_INT) %s, boot_val=%d, C-var=%d",
1422  conf->gen.name, conf->boot_val, *conf->variable);
1423  return false;
1424  }
1425  break;
1426  }
1427  case PGC_REAL:
1428  {
1429  struct config_real *conf = (struct config_real *) gconf;
1430 
1431  if (*conf->variable != 0.0 && *conf->variable != conf->boot_val)
1432  {
1433  elog(LOG, "GUC (PGC_REAL) %s, boot_val=%g, C-var=%g",
1434  conf->gen.name, conf->boot_val, *conf->variable);
1435  return false;
1436  }
1437  break;
1438  }
1439  case PGC_STRING:
1440  {
1441  struct config_string *conf = (struct config_string *) gconf;
1442 
1443  if (*conf->variable != NULL && strcmp(*conf->variable, conf->boot_val) != 0)
1444  {
1445  elog(LOG, "GUC (PGC_STRING) %s, boot_val=%s, C-var=%s",
1446  conf->gen.name, conf->boot_val ? conf->boot_val : "<null>", *conf->variable);
1447  return false;
1448  }
1449  break;
1450  }
1451  case PGC_ENUM:
1452  {
1453  struct config_enum *conf = (struct config_enum *) gconf;
1454 
1455  if (*conf->variable != conf->boot_val)
1456  {
1457  elog(LOG, "GUC (PGC_ENUM) %s, boot_val=%d, C-var=%d",
1458  conf->gen.name, conf->boot_val, *conf->variable);
1459  return false;
1460  }
1461  break;
1462  }
1463  }
1464 
1465  return true;
1466 }
1467 #endif
1468 
1469 /*
1470  * Initialize GUC options during program startup.
1471  *
1472  * Note that we cannot read the config file yet, since we have not yet
1473  * processed command-line switches.
1474  */
1475 void
1477 {
1479  GUCHashEntry *hentry;
1480 
1481  /*
1482  * Before log_line_prefix could possibly receive a nonempty setting, make
1483  * sure that timezone processing is minimally alive (see elog.c).
1484  */
1486 
1487  /*
1488  * Create GUCMemoryContext and build hash table of all GUC variables.
1489  */
1491 
1492  /*
1493  * Load all variables with their compiled-in defaults, and initialize
1494  * status fields as needed.
1495  */
1497  while ((hentry = (GUCHashEntry *) hash_seq_search(&status)) != NULL)
1498  {
1499  /* Check mapping between initial and default value */
1500  Assert(check_GUC_init(hentry->gucvar));
1501 
1502  InitializeOneGUCOption(hentry->gucvar);
1503  }
1504 
1505  reporting_enabled = false;
1506 
1507  /*
1508  * Prevent any attempt to override the transaction modes from
1509  * non-interactive sources.
1510  */
1511  SetConfigOption("transaction_isolation", "read committed",
1513  SetConfigOption("transaction_read_only", "no",
1515  SetConfigOption("transaction_deferrable", "no",
1517 
1518  /*
1519  * For historical reasons, some GUC parameters can receive defaults from
1520  * environment variables. Process those settings.
1521  */
1523 }
1524 
1525 /*
1526  * Assign any GUC values that can come from the server's environment.
1527  *
1528  * This is called from InitializeGUCOptions, and also from ProcessConfigFile
1529  * to deal with the possibility that a setting has been removed from
1530  * postgresql.conf and should now get a value from the environment.
1531  * (The latter is a kludge that should probably go away someday; if so,
1532  * fold this back into InitializeGUCOptions.)
1533  */
1534 static void
1536 {
1537  char *env;
1538  long stack_rlimit;
1539 
1540  env = getenv("PGPORT");
1541  if (env != NULL)
1543 
1544  env = getenv("PGDATESTYLE");
1545  if (env != NULL)
1546  SetConfigOption("datestyle", env, PGC_POSTMASTER, PGC_S_ENV_VAR);
1547 
1548  env = getenv("PGCLIENTENCODING");
1549  if (env != NULL)
1550  SetConfigOption("client_encoding", env, PGC_POSTMASTER, PGC_S_ENV_VAR);
1551 
1552  /*
1553  * rlimit isn't exactly an "environment variable", but it behaves about
1554  * the same. If we can identify the platform stack depth rlimit, increase
1555  * default stack depth setting up to whatever is safe (but at most 2MB).
1556  * Report the value's source as PGC_S_DYNAMIC_DEFAULT if it's 2MB, or as
1557  * PGC_S_ENV_VAR if it's reflecting the rlimit limit.
1558  */
1559  stack_rlimit = get_stack_depth_rlimit();
1560  if (stack_rlimit > 0)
1561  {
1562  long new_limit = (stack_rlimit - STACK_DEPTH_SLOP) / 1024L;
1563 
1564  if (new_limit > 100)
1565  {
1566  GucSource source;
1567  char limbuf[16];
1568 
1569  if (new_limit < 2048)
1571  else
1572  {
1573  new_limit = 2048;
1575  }
1576  snprintf(limbuf, sizeof(limbuf), "%ld", new_limit);
1577  SetConfigOption("max_stack_depth", limbuf,
1579  }
1580  }
1581 }
1582 
1583 /*
1584  * Initialize one GUC option variable to its compiled-in default.
1585  *
1586  * Note: the reason for calling check_hooks is not that we think the boot_val
1587  * might fail, but that the hooks might wish to compute an "extra" struct.
1588  */
1589 static void
1591 {
1592  gconf->status = 0;
1593  gconf->source = PGC_S_DEFAULT;
1594  gconf->reset_source = PGC_S_DEFAULT;
1595  gconf->scontext = PGC_INTERNAL;
1596  gconf->reset_scontext = PGC_INTERNAL;
1597  gconf->srole = BOOTSTRAP_SUPERUSERID;
1598  gconf->reset_srole = BOOTSTRAP_SUPERUSERID;
1599  gconf->stack = NULL;
1600  gconf->extra = NULL;
1601  gconf->last_reported = NULL;
1602  gconf->sourcefile = NULL;
1603  gconf->sourceline = 0;
1604 
1605  switch (gconf->vartype)
1606  {
1607  case PGC_BOOL:
1608  {
1609  struct config_bool *conf = (struct config_bool *) gconf;
1610  bool newval = conf->boot_val;
1611  void *extra = NULL;
1612 
1613  if (!call_bool_check_hook(conf, &newval, &extra,
1614  PGC_S_DEFAULT, LOG))
1615  elog(FATAL, "failed to initialize %s to %d",
1616  conf->gen.name, (int) newval);
1617  if (conf->assign_hook)
1618  conf->assign_hook(newval, extra);
1619  *conf->variable = conf->reset_val = newval;
1620  conf->gen.extra = conf->reset_extra = extra;
1621  break;
1622  }
1623  case PGC_INT:
1624  {
1625  struct config_int *conf = (struct config_int *) gconf;
1626  int newval = conf->boot_val;
1627  void *extra = NULL;
1628 
1629  Assert(newval >= conf->min);
1630  Assert(newval <= conf->max);
1631  if (!call_int_check_hook(conf, &newval, &extra,
1632  PGC_S_DEFAULT, LOG))
1633  elog(FATAL, "failed to initialize %s to %d",
1634  conf->gen.name, newval);
1635  if (conf->assign_hook)
1636  conf->assign_hook(newval, extra);
1637  *conf->variable = conf->reset_val = newval;
1638  conf->gen.extra = conf->reset_extra = extra;
1639  break;
1640  }
1641  case PGC_REAL:
1642  {
1643  struct config_real *conf = (struct config_real *) gconf;
1644  double newval = conf->boot_val;
1645  void *extra = NULL;
1646 
1647  Assert(newval >= conf->min);
1648  Assert(newval <= conf->max);
1649  if (!call_real_check_hook(conf, &newval, &extra,
1650  PGC_S_DEFAULT, LOG))
1651  elog(FATAL, "failed to initialize %s to %g",
1652  conf->gen.name, newval);
1653  if (conf->assign_hook)
1654  conf->assign_hook(newval, extra);
1655  *conf->variable = conf->reset_val = newval;
1656  conf->gen.extra = conf->reset_extra = extra;
1657  break;
1658  }
1659  case PGC_STRING:
1660  {
1661  struct config_string *conf = (struct config_string *) gconf;
1662  char *newval;
1663  void *extra = NULL;
1664 
1665  /* non-NULL boot_val must always get strdup'd */
1666  if (conf->boot_val != NULL)
1667  newval = guc_strdup(FATAL, conf->boot_val);
1668  else
1669  newval = NULL;
1670 
1671  if (!call_string_check_hook(conf, &newval, &extra,
1672  PGC_S_DEFAULT, LOG))
1673  elog(FATAL, "failed to initialize %s to \"%s\"",
1674  conf->gen.name, newval ? newval : "");
1675  if (conf->assign_hook)
1676  conf->assign_hook(newval, extra);
1677  *conf->variable = conf->reset_val = newval;
1678  conf->gen.extra = conf->reset_extra = extra;
1679  break;
1680  }
1681  case PGC_ENUM:
1682  {
1683  struct config_enum *conf = (struct config_enum *) gconf;
1684  int newval = conf->boot_val;
1685  void *extra = NULL;
1686 
1687  if (!call_enum_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;
1696  }
1697  }
1698 }
1699 
1700 /*
1701  * Summarily remove a GUC variable from any linked lists it's in.
1702  *
1703  * We use this in cases where the variable is about to be deleted or reset.
1704  * These aren't common operations, so it's okay if this is a bit slow.
1705  */
1706 static void
1708 {
1709  if (gconf->source != PGC_S_DEFAULT)
1710  dlist_delete(&gconf->nondef_link);
1711  if (gconf->stack != NULL)
1713  if (gconf->status & GUC_NEEDS_REPORT)
1715 }
1716 
1717 
1718 /*
1719  * Select the configuration files and data directory to be used, and
1720  * do the initial read of postgresql.conf.
1721  *
1722  * This is called after processing command-line switches.
1723  * userDoption is the -D switch value if any (NULL if unspecified).
1724  * progname is just for use in error messages.
1725  *
1726  * Returns true on success; on failure, prints a suitable error message
1727  * to stderr and returns false.
1728  */
1729 bool
1730 SelectConfigFiles(const char *userDoption, const char *progname)
1731 {
1732  char *configdir;
1733  char *fname;
1734  bool fname_is_malloced;
1735  struct stat stat_buf;
1736  struct config_string *data_directory_rec;
1737 
1738  /* configdir is -D option, or $PGDATA if no -D */
1739  if (userDoption)
1740  configdir = make_absolute_path(userDoption);
1741  else
1742  configdir = make_absolute_path(getenv("PGDATA"));
1743 
1744  if (configdir && stat(configdir, &stat_buf) != 0)
1745  {
1746  write_stderr("%s: could not access directory \"%s\": %s\n",
1747  progname,
1748  configdir,
1749  strerror(errno));
1750  if (errno == ENOENT)
1751  write_stderr("Run initdb or pg_basebackup to initialize a PostgreSQL data directory.\n");
1752  return false;
1753  }
1754 
1755  /*
1756  * Find the configuration file: if config_file was specified on the
1757  * command line, use it, else use configdir/postgresql.conf. In any case
1758  * ensure the result is an absolute path, so that it will be interpreted
1759  * the same way by future backends.
1760  */
1761  if (ConfigFileName)
1762  {
1764  fname_is_malloced = true;
1765  }
1766  else if (configdir)
1767  {
1768  fname = guc_malloc(FATAL,
1769  strlen(configdir) + strlen(CONFIG_FILENAME) + 2);
1770  sprintf(fname, "%s/%s", configdir, CONFIG_FILENAME);
1771  fname_is_malloced = false;
1772  }
1773  else
1774  {
1775  write_stderr("%s does not know where to find the server configuration file.\n"
1776  "You must specify the --config-file or -D invocation "
1777  "option or set the PGDATA environment variable.\n",
1778  progname);
1779  return false;
1780  }
1781 
1782  /*
1783  * Set the ConfigFileName GUC variable to its final value, ensuring that
1784  * it can't be overridden later.
1785  */
1786  SetConfigOption("config_file", fname, PGC_POSTMASTER, PGC_S_OVERRIDE);
1787 
1788  if (fname_is_malloced)
1789  free(fname);
1790  else
1791  guc_free(fname);
1792 
1793  /*
1794  * Now read the config file for the first time.
1795  */
1796  if (stat(ConfigFileName, &stat_buf) != 0)
1797  {
1798  write_stderr("%s: could not access the server configuration file \"%s\": %s\n",
1799  progname, ConfigFileName, strerror(errno));
1800  free(configdir);
1801  return false;
1802  }
1803 
1804  /*
1805  * Read the configuration file for the first time. This time only the
1806  * data_directory parameter is picked up to determine the data directory,
1807  * so that we can read the PG_AUTOCONF_FILENAME file next time.
1808  */
1810 
1811  /*
1812  * If the data_directory GUC variable has been set, use that as DataDir;
1813  * otherwise use configdir if set; else punt.
1814  *
1815  * Note: SetDataDir will copy and absolute-ize its argument, so we don't
1816  * have to.
1817  */
1818  data_directory_rec = (struct config_string *)
1819  find_option("data_directory", false, false, PANIC);
1820  if (*data_directory_rec->variable)
1821  SetDataDir(*data_directory_rec->variable);
1822  else if (configdir)
1823  SetDataDir(configdir);
1824  else
1825  {
1826  write_stderr("%s does not know where to find the database system data.\n"
1827  "This can be specified as \"data_directory\" in \"%s\", "
1828  "or by the -D invocation option, or by the "
1829  "PGDATA environment variable.\n",
1831  return false;
1832  }
1833 
1834  /*
1835  * Reflect the final DataDir value back into the data_directory GUC var.
1836  * (If you are wondering why we don't just make them a single variable,
1837  * it's because the EXEC_BACKEND case needs DataDir to be transmitted to
1838  * child backends specially. XXX is that still true? Given that we now
1839  * chdir to DataDir, EXEC_BACKEND can read the config file without knowing
1840  * DataDir in advance.)
1841  */
1843 
1844  /*
1845  * Now read the config file a second time, allowing any settings in the
1846  * PG_AUTOCONF_FILENAME file to take effect. (This is pretty ugly, but
1847  * since we have to determine the DataDir before we can find the autoconf
1848  * file, the alternatives seem worse.)
1849  */
1851 
1852  /*
1853  * If timezone_abbreviations wasn't set in the configuration file, install
1854  * the default value. We do it this way because we can't safely install a
1855  * "real" value until my_exec_path is set, which may not have happened
1856  * when InitializeGUCOptions runs, so the bootstrap default value cannot
1857  * be the real desired default.
1858  */
1860 
1861  /*
1862  * Figure out where pg_hba.conf is, and make sure the path is absolute.
1863  */
1864  if (HbaFileName)
1865  {
1867  fname_is_malloced = true;
1868  }
1869  else if (configdir)
1870  {
1871  fname = guc_malloc(FATAL,
1872  strlen(configdir) + strlen(HBA_FILENAME) + 2);
1873  sprintf(fname, "%s/%s", configdir, HBA_FILENAME);
1874  fname_is_malloced = false;
1875  }
1876  else
1877  {
1878  write_stderr("%s does not know where to find the \"hba\" configuration file.\n"
1879  "This can be specified as \"hba_file\" in \"%s\", "
1880  "or by the -D invocation option, or by the "
1881  "PGDATA environment variable.\n",
1883  return false;
1884  }
1885  SetConfigOption("hba_file", fname, PGC_POSTMASTER, PGC_S_OVERRIDE);
1886 
1887  if (fname_is_malloced)
1888  free(fname);
1889  else
1890  guc_free(fname);
1891 
1892  /*
1893  * Likewise for pg_ident.conf.
1894  */
1895  if (IdentFileName)
1896  {
1898  fname_is_malloced = true;
1899  }
1900  else if (configdir)
1901  {
1902  fname = guc_malloc(FATAL,
1903  strlen(configdir) + strlen(IDENT_FILENAME) + 2);
1904  sprintf(fname, "%s/%s", configdir, IDENT_FILENAME);
1905  fname_is_malloced = false;
1906  }
1907  else
1908  {
1909  write_stderr("%s does not know where to find the \"ident\" configuration file.\n"
1910  "This can be specified as \"ident_file\" in \"%s\", "
1911  "or by the -D invocation option, or by the "
1912  "PGDATA environment variable.\n",
1914  return false;
1915  }
1916  SetConfigOption("ident_file", fname, PGC_POSTMASTER, PGC_S_OVERRIDE);
1917 
1918  if (fname_is_malloced)
1919  free(fname);
1920  else
1921  guc_free(fname);
1922 
1923  free(configdir);
1924 
1925  return true;
1926 }
1927 
1928 /*
1929  * pg_timezone_abbrev_initialize --- set default value if not done already
1930  *
1931  * This is called after initial loading of postgresql.conf. If no
1932  * timezone_abbreviations setting was found therein, select default.
1933  * If a non-default value is already installed, nothing will happen.
1934  *
1935  * This can also be called from ProcessConfigFile to establish the default
1936  * value after a postgresql.conf entry for it is removed.
1937  */
1938 static void
1940 {
1941  SetConfigOption("timezone_abbreviations", "Default",
1943 }
1944 
1945 
1946 /*
1947  * Reset all options to their saved default values (implements RESET ALL)
1948  */
1949 void
1951 {
1952  dlist_mutable_iter iter;
1953 
1954  /* We need only consider GUCs not already at PGC_S_DEFAULT */
1956  {
1957  struct config_generic *gconf = dlist_container(struct config_generic,
1958  nondef_link, iter.cur);
1959 
1960  /* Don't reset non-SET-able values */
1961  if (gconf->context != PGC_SUSET &&
1962  gconf->context != PGC_USERSET)
1963  continue;
1964  /* Don't reset if special exclusion from RESET ALL */
1965  if (gconf->flags & GUC_NO_RESET_ALL)
1966  continue;
1967  /* No need to reset if wasn't SET */
1968  if (gconf->source <= PGC_S_OVERRIDE)
1969  continue;
1970 
1971  /* Save old value to support transaction abort */
1973 
1974  switch (gconf->vartype)
1975  {
1976  case PGC_BOOL:
1977  {
1978  struct config_bool *conf = (struct config_bool *) gconf;
1979 
1980  if (conf->assign_hook)
1981  conf->assign_hook(conf->reset_val,
1982  conf->reset_extra);
1983  *conf->variable = conf->reset_val;
1984  set_extra_field(&conf->gen, &conf->gen.extra,
1985  conf->reset_extra);
1986  break;
1987  }
1988  case PGC_INT:
1989  {
1990  struct config_int *conf = (struct config_int *) gconf;
1991 
1992  if (conf->assign_hook)
1993  conf->assign_hook(conf->reset_val,
1994  conf->reset_extra);
1995  *conf->variable = conf->reset_val;
1996  set_extra_field(&conf->gen, &conf->gen.extra,
1997  conf->reset_extra);
1998  break;
1999  }
2000  case PGC_REAL:
2001  {
2002  struct config_real *conf = (struct config_real *) gconf;
2003 
2004  if (conf->assign_hook)
2005  conf->assign_hook(conf->reset_val,
2006  conf->reset_extra);
2007  *conf->variable = conf->reset_val;
2008  set_extra_field(&conf->gen, &conf->gen.extra,
2009  conf->reset_extra);
2010  break;
2011  }
2012  case PGC_STRING:
2013  {
2014  struct config_string *conf = (struct config_string *) gconf;
2015 
2016  if (conf->assign_hook)
2017  conf->assign_hook(conf->reset_val,
2018  conf->reset_extra);
2019  set_string_field(conf, conf->variable, conf->reset_val);
2020  set_extra_field(&conf->gen, &conf->gen.extra,
2021  conf->reset_extra);
2022  break;
2023  }
2024  case PGC_ENUM:
2025  {
2026  struct config_enum *conf = (struct config_enum *) gconf;
2027 
2028  if (conf->assign_hook)
2029  conf->assign_hook(conf->reset_val,
2030  conf->reset_extra);
2031  *conf->variable = conf->reset_val;
2032  set_extra_field(&conf->gen, &conf->gen.extra,
2033  conf->reset_extra);
2034  break;
2035  }
2036  }
2037 
2038  set_guc_source(gconf, gconf->reset_source);
2039  gconf->scontext = gconf->reset_scontext;
2040  gconf->srole = gconf->reset_srole;
2041 
2042  if ((gconf->flags & GUC_REPORT) && !(gconf->status & GUC_NEEDS_REPORT))
2043  {
2044  gconf->status |= GUC_NEEDS_REPORT;
2046  }
2047  }
2048 }
2049 
2050 
2051 /*
2052  * Apply a change to a GUC variable's "source" field.
2053  *
2054  * Use this rather than just assigning, to ensure that the variable's
2055  * membership in guc_nondef_list is updated correctly.
2056  */
2057 static void
2058 set_guc_source(struct config_generic *gconf, GucSource newsource)
2059 {
2060  /* Adjust nondef list membership if appropriate for change */
2061  if (gconf->source == PGC_S_DEFAULT)
2062  {
2063  if (newsource != PGC_S_DEFAULT)
2065  }
2066  else
2067  {
2068  if (newsource == PGC_S_DEFAULT)
2069  dlist_delete(&gconf->nondef_link);
2070  }
2071  /* Now update the source field */
2072  gconf->source = newsource;
2073 }
2074 
2075 
2076 /*
2077  * push_old_value
2078  * Push previous state during transactional assignment to a GUC variable.
2079  */
2080 static void
2082 {
2083  GucStack *stack;
2084 
2085  /* If we're not inside a nest level, do nothing */
2086  if (GUCNestLevel == 0)
2087  return;
2088 
2089  /* Do we already have a stack entry of the current nest level? */
2090  stack = gconf->stack;
2091  if (stack && stack->nest_level >= GUCNestLevel)
2092  {
2093  /* Yes, so adjust its state if necessary */
2094  Assert(stack->nest_level == GUCNestLevel);
2095  switch (action)
2096  {
2097  case GUC_ACTION_SET:
2098  /* SET overrides any prior action at same nest level */
2099  if (stack->state == GUC_SET_LOCAL)
2100  {
2101  /* must discard old masked value */
2102  discard_stack_value(gconf, &stack->masked);
2103  }
2104  stack->state = GUC_SET;
2105  break;
2106  case GUC_ACTION_LOCAL:
2107  if (stack->state == GUC_SET)
2108  {
2109  /* SET followed by SET LOCAL, remember SET's value */
2110  stack->masked_scontext = gconf->scontext;
2111  stack->masked_srole = gconf->srole;
2112  set_stack_value(gconf, &stack->masked);
2113  stack->state = GUC_SET_LOCAL;
2114  }
2115  /* in all other cases, no change to stack entry */
2116  break;
2117  case GUC_ACTION_SAVE:
2118  /* Could only have a prior SAVE of same variable */
2119  Assert(stack->state == GUC_SAVE);
2120  break;
2121  }
2122  return;
2123  }
2124 
2125  /*
2126  * Push a new stack entry
2127  *
2128  * We keep all the stack entries in TopTransactionContext for simplicity.
2129  */
2131  sizeof(GucStack));
2132 
2133  stack->prev = gconf->stack;
2134  stack->nest_level = GUCNestLevel;
2135  switch (action)
2136  {
2137  case GUC_ACTION_SET:
2138  stack->state = GUC_SET;
2139  break;
2140  case GUC_ACTION_LOCAL:
2141  stack->state = GUC_LOCAL;
2142  break;
2143  case GUC_ACTION_SAVE:
2144  stack->state = GUC_SAVE;
2145  break;
2146  }
2147  stack->source = gconf->source;
2148  stack->scontext = gconf->scontext;
2149  stack->srole = gconf->srole;
2150  set_stack_value(gconf, &stack->prior);
2151 
2152  if (gconf->stack == NULL)
2154  gconf->stack = stack;
2155 }
2156 
2157 
2158 /*
2159  * Do GUC processing at main transaction start.
2160  */
2161 void
2163 {
2164  /*
2165  * The nest level should be 0 between transactions; if it isn't, somebody
2166  * didn't call AtEOXact_GUC, or called it with the wrong nestLevel. We
2167  * throw a warning but make no other effort to clean up.
2168  */
2169  if (GUCNestLevel != 0)
2170  elog(WARNING, "GUC nest level = %d at transaction start",
2171  GUCNestLevel);
2172  GUCNestLevel = 1;
2173 }
2174 
2175 /*
2176  * Enter a new nesting level for GUC values. This is called at subtransaction
2177  * start, and when entering a function that has proconfig settings, and in
2178  * some other places where we want to set GUC variables transiently.
2179  * NOTE we must not risk error here, else subtransaction start will be unhappy.
2180  */
2181 int
2183 {
2184  return ++GUCNestLevel;
2185 }
2186 
2187 /*
2188  * Do GUC processing at transaction or subtransaction commit or abort, or
2189  * when exiting a function that has proconfig settings, or when undoing a
2190  * transient assignment to some GUC variables. (The name is thus a bit of
2191  * a misnomer; perhaps it should be ExitGUCNestLevel or some such.)
2192  * During abort, we discard all GUC settings that were applied at nesting
2193  * levels >= nestLevel. nestLevel == 1 corresponds to the main transaction.
2194  */
2195 void
2196 AtEOXact_GUC(bool isCommit, int nestLevel)
2197 {
2198  slist_mutable_iter iter;
2199 
2200  /*
2201  * Note: it's possible to get here with GUCNestLevel == nestLevel-1 during
2202  * abort, if there is a failure during transaction start before
2203  * AtStart_GUC is called.
2204  */
2205  Assert(nestLevel > 0 &&
2206  (nestLevel <= GUCNestLevel ||
2207  (nestLevel == GUCNestLevel + 1 && !isCommit)));
2208 
2209  /* We need only process GUCs having nonempty stacks */
2211  {
2212  struct config_generic *gconf = slist_container(struct config_generic,
2213  stack_link, iter.cur);
2214  GucStack *stack;
2215 
2216  /*
2217  * Process and pop each stack entry within the nest level. To simplify
2218  * fmgr_security_definer() and other places that use GUC_ACTION_SAVE,
2219  * we allow failure exit from code that uses a local nest level to be
2220  * recovered at the surrounding transaction or subtransaction abort;
2221  * so there could be more than one stack entry to pop.
2222  */
2223  while ((stack = gconf->stack) != NULL &&
2224  stack->nest_level >= nestLevel)
2225  {
2226  GucStack *prev = stack->prev;
2227  bool restorePrior = false;
2228  bool restoreMasked = false;
2229  bool changed;
2230 
2231  /*
2232  * In this next bit, if we don't set either restorePrior or
2233  * restoreMasked, we must "discard" any unwanted fields of the
2234  * stack entries to avoid leaking memory. If we do set one of
2235  * those flags, unused fields will be cleaned up after restoring.
2236  */
2237  if (!isCommit) /* if abort, always restore prior value */
2238  restorePrior = true;
2239  else if (stack->state == GUC_SAVE)
2240  restorePrior = true;
2241  else if (stack->nest_level == 1)
2242  {
2243  /* transaction commit */
2244  if (stack->state == GUC_SET_LOCAL)
2245  restoreMasked = true;
2246  else if (stack->state == GUC_SET)
2247  {
2248  /* we keep the current active value */
2249  discard_stack_value(gconf, &stack->prior);
2250  }
2251  else /* must be GUC_LOCAL */
2252  restorePrior = true;
2253  }
2254  else if (prev == NULL ||
2255  prev->nest_level < stack->nest_level - 1)
2256  {
2257  /* decrement entry's level and do not pop it */
2258  stack->nest_level--;
2259  continue;
2260  }
2261  else
2262  {
2263  /*
2264  * We have to merge this stack entry into prev. See README for
2265  * discussion of this bit.
2266  */
2267  switch (stack->state)
2268  {
2269  case GUC_SAVE:
2270  Assert(false); /* can't get here */
2271  break;
2272 
2273  case GUC_SET:
2274  /* next level always becomes SET */
2275  discard_stack_value(gconf, &stack->prior);
2276  if (prev->state == GUC_SET_LOCAL)
2277  discard_stack_value(gconf, &prev->masked);
2278  prev->state = GUC_SET;
2279  break;
2280 
2281  case GUC_LOCAL:
2282  if (prev->state == GUC_SET)
2283  {
2284  /* LOCAL migrates down */
2285  prev->masked_scontext = stack->scontext;
2286  prev->masked_srole = stack->srole;
2287  prev->masked = stack->prior;
2288  prev->state = GUC_SET_LOCAL;
2289  }
2290  else
2291  {
2292  /* else just forget this stack level */
2293  discard_stack_value(gconf, &stack->prior);
2294  }
2295  break;
2296 
2297  case GUC_SET_LOCAL:
2298  /* prior state at this level no longer wanted */
2299  discard_stack_value(gconf, &stack->prior);
2300  /* copy down the masked state */
2302  prev->masked_srole = stack->masked_srole;
2303  if (prev->state == GUC_SET_LOCAL)
2304  discard_stack_value(gconf, &prev->masked);
2305  prev->masked = stack->masked;
2306  prev->state = GUC_SET_LOCAL;
2307  break;
2308  }
2309  }
2310 
2311  changed = false;
2312 
2313  if (restorePrior || restoreMasked)
2314  {
2315  /* Perform appropriate restoration of the stacked value */
2316  config_var_value newvalue;
2317  GucSource newsource;
2318  GucContext newscontext;
2319  Oid newsrole;
2320 
2321  if (restoreMasked)
2322  {
2323  newvalue = stack->masked;
2324  newsource = PGC_S_SESSION;
2325  newscontext = stack->masked_scontext;
2326  newsrole = stack->masked_srole;
2327  }
2328  else
2329  {
2330  newvalue = stack->prior;
2331  newsource = stack->source;
2332  newscontext = stack->scontext;
2333  newsrole = stack->srole;
2334  }
2335 
2336  switch (gconf->vartype)
2337  {
2338  case PGC_BOOL:
2339  {
2340  struct config_bool *conf = (struct config_bool *) gconf;
2341  bool newval = newvalue.val.boolval;
2342  void *newextra = newvalue.extra;
2343 
2344  if (*conf->variable != newval ||
2345  conf->gen.extra != newextra)
2346  {
2347  if (conf->assign_hook)
2348  conf->assign_hook(newval, newextra);
2349  *conf->variable = newval;
2350  set_extra_field(&conf->gen, &conf->gen.extra,
2351  newextra);
2352  changed = true;
2353  }
2354  break;
2355  }
2356  case PGC_INT:
2357  {
2358  struct config_int *conf = (struct config_int *) gconf;
2359  int newval = newvalue.val.intval;
2360  void *newextra = newvalue.extra;
2361 
2362  if (*conf->variable != newval ||
2363  conf->gen.extra != newextra)
2364  {
2365  if (conf->assign_hook)
2366  conf->assign_hook(newval, newextra);
2367  *conf->variable = newval;
2368  set_extra_field(&conf->gen, &conf->gen.extra,
2369  newextra);
2370  changed = true;
2371  }
2372  break;
2373  }
2374  case PGC_REAL:
2375  {
2376  struct config_real *conf = (struct config_real *) gconf;
2377  double newval = newvalue.val.realval;
2378  void *newextra = newvalue.extra;
2379 
2380  if (*conf->variable != newval ||
2381  conf->gen.extra != newextra)
2382  {
2383  if (conf->assign_hook)
2384  conf->assign_hook(newval, newextra);
2385  *conf->variable = newval;
2386  set_extra_field(&conf->gen, &conf->gen.extra,
2387  newextra);
2388  changed = true;
2389  }
2390  break;
2391  }
2392  case PGC_STRING:
2393  {
2394  struct config_string *conf = (struct config_string *) gconf;
2395  char *newval = newvalue.val.stringval;
2396  void *newextra = newvalue.extra;
2397 
2398  if (*conf->variable != newval ||
2399  conf->gen.extra != newextra)
2400  {
2401  if (conf->assign_hook)
2402  conf->assign_hook(newval, newextra);
2403  set_string_field(conf, conf->variable, newval);
2404  set_extra_field(&conf->gen, &conf->gen.extra,
2405  newextra);
2406  changed = true;
2407  }
2408 
2409  /*
2410  * Release stacked values if not used anymore. We
2411  * could use discard_stack_value() here, but since
2412  * we have type-specific code anyway, might as
2413  * well inline it.
2414  */
2415  set_string_field(conf, &stack->prior.val.stringval, NULL);
2416  set_string_field(conf, &stack->masked.val.stringval, NULL);
2417  break;
2418  }
2419  case PGC_ENUM:
2420  {
2421  struct config_enum *conf = (struct config_enum *) gconf;
2422  int newval = newvalue.val.enumval;
2423  void *newextra = newvalue.extra;
2424 
2425  if (*conf->variable != newval ||
2426  conf->gen.extra != newextra)
2427  {
2428  if (conf->assign_hook)
2429  conf->assign_hook(newval, newextra);
2430  *conf->variable = newval;
2431  set_extra_field(&conf->gen, &conf->gen.extra,
2432  newextra);
2433  changed = true;
2434  }
2435  break;
2436  }
2437  }
2438 
2439  /*
2440  * Release stacked extra values if not used anymore.
2441  */
2442  set_extra_field(gconf, &(stack->prior.extra), NULL);
2443  set_extra_field(gconf, &(stack->masked.extra), NULL);
2444 
2445  /* And restore source information */
2446  set_guc_source(gconf, newsource);
2447  gconf->scontext = newscontext;
2448  gconf->srole = newsrole;
2449  }
2450 
2451  /*
2452  * Pop the GUC's state stack; if it's now empty, remove the GUC
2453  * from guc_stack_list.
2454  */
2455  gconf->stack = prev;
2456  if (prev == NULL)
2457  slist_delete_current(&iter);
2458  pfree(stack);
2459 
2460  /* Report new value if we changed it */
2461  if (changed && (gconf->flags & GUC_REPORT) &&
2462  !(gconf->status & GUC_NEEDS_REPORT))
2463  {
2464  gconf->status |= GUC_NEEDS_REPORT;
2466  }
2467  } /* end of stack-popping loop */
2468  }
2469 
2470  /* Update nesting level */
2471  GUCNestLevel = nestLevel - 1;
2472 }
2473 
2474 
2475 /*
2476  * Start up automatic reporting of changes to variables marked GUC_REPORT.
2477  * This is executed at completion of backend startup.
2478  */
2479 void
2481 {
2483  GUCHashEntry *hentry;
2484 
2485  /*
2486  * Don't do anything unless talking to an interactive frontend.
2487  */
2489  return;
2490 
2491  reporting_enabled = true;
2492 
2493  /*
2494  * Hack for in_hot_standby: set the GUC value true if appropriate. This
2495  * is kind of an ugly place to do it, but there's few better options.
2496  *
2497  * (This could be out of date by the time we actually send it, in which
2498  * case the next ReportChangedGUCOptions call will send a duplicate
2499  * report.)
2500  */
2501  if (RecoveryInProgress())
2502  SetConfigOption("in_hot_standby", "true",
2504 
2505  /* Transmit initial values of interesting variables */
2507  while ((hentry = (GUCHashEntry *) hash_seq_search(&status)) != NULL)
2508  {
2509  struct config_generic *conf = hentry->gucvar;
2510 
2511  if (conf->flags & GUC_REPORT)
2512  ReportGUCOption(conf);
2513  }
2514 }
2515 
2516 /*
2517  * ReportChangedGUCOptions: report recently-changed GUC_REPORT variables
2518  *
2519  * This is called just before we wait for a new client query.
2520  *
2521  * By handling things this way, we ensure that a ParameterStatus message
2522  * is sent at most once per variable per query, even if the variable
2523  * changed multiple times within the query. That's quite possible when
2524  * using features such as function SET clauses. Function SET clauses
2525  * also tend to cause values to change intraquery but eventually revert
2526  * to their prevailing values; ReportGUCOption is responsible for avoiding
2527  * redundant reports in such cases.
2528  */
2529 void
2531 {
2532  slist_mutable_iter iter;
2533 
2534  /* Quick exit if not (yet) enabled */
2535  if (!reporting_enabled)
2536  return;
2537 
2538  /*
2539  * Since in_hot_standby isn't actually changed by normal GUC actions, we
2540  * need a hack to check whether a new value needs to be reported to the
2541  * client. For speed, we rely on the assumption that it can never
2542  * transition from false to true.
2543  */
2545  SetConfigOption("in_hot_standby", "false",
2547 
2548  /* Transmit new values of interesting variables */
2550  {
2551  struct config_generic *conf = slist_container(struct config_generic,
2552  report_link, iter.cur);
2553 
2554  Assert((conf->flags & GUC_REPORT) && (conf->status & GUC_NEEDS_REPORT));
2555  ReportGUCOption(conf);
2556  conf->status &= ~GUC_NEEDS_REPORT;
2557  slist_delete_current(&iter);
2558  }
2559 }
2560 
2561 /*
2562  * ReportGUCOption: if appropriate, transmit option value to frontend
2563  *
2564  * We need not transmit the value if it's the same as what we last
2565  * transmitted.
2566  */
2567 static void
2569 {
2570  char *val = ShowGUCOption(record, false);
2571 
2572  if (record->last_reported == NULL ||
2573  strcmp(val, record->last_reported) != 0)
2574  {
2575  StringInfoData msgbuf;
2576 
2577  pq_beginmessage(&msgbuf, 'S');
2578  pq_sendstring(&msgbuf, record->name);
2579  pq_sendstring(&msgbuf, val);
2580  pq_endmessage(&msgbuf);
2581 
2582  /*
2583  * We need a long-lifespan copy. If guc_strdup() fails due to OOM,
2584  * we'll set last_reported to NULL and thereby possibly make a
2585  * duplicate report later.
2586  */
2587  guc_free(record->last_reported);
2588  record->last_reported = guc_strdup(LOG, val);
2589  }
2590 
2591  pfree(val);
2592 }
2593 
2594 /*
2595  * Convert a value from one of the human-friendly units ("kB", "min" etc.)
2596  * to the given base unit. 'value' and 'unit' are the input value and unit
2597  * to convert from (there can be trailing spaces in the unit string).
2598  * The converted value is stored in *base_value.
2599  * It's caller's responsibility to round off the converted value as necessary
2600  * and check for out-of-range.
2601  *
2602  * Returns true on success, false if the input unit is not recognized.
2603  */
2604 static bool
2605 convert_to_base_unit(double value, const char *unit,
2606  int base_unit, double *base_value)
2607 {
2608  char unitstr[MAX_UNIT_LEN + 1];
2609  int unitlen;
2610  const unit_conversion *table;
2611  int i;
2612 
2613  /* extract unit string to compare to table entries */
2614  unitlen = 0;
2615  while (*unit != '\0' && !isspace((unsigned char) *unit) &&
2616  unitlen < MAX_UNIT_LEN)
2617  unitstr[unitlen++] = *(unit++);
2618  unitstr[unitlen] = '\0';
2619  /* allow whitespace after unit */
2620  while (isspace((unsigned char) *unit))
2621  unit++;
2622  if (*unit != '\0')
2623  return false; /* unit too long, or garbage after it */
2624 
2625  /* now search the appropriate table */
2626  if (base_unit & GUC_UNIT_MEMORY)
2628  else
2630 
2631  for (i = 0; *table[i].unit; i++)
2632  {
2633  if (base_unit == table[i].base_unit &&
2634  strcmp(unitstr, table[i].unit) == 0)
2635  {
2636  double cvalue = value * table[i].multiplier;
2637 
2638  /*
2639  * If the user gave a fractional value such as "30.1GB", round it
2640  * off to the nearest multiple of the next smaller unit, if there
2641  * is one.
2642  */
2643  if (*table[i + 1].unit &&
2644  base_unit == table[i + 1].base_unit)
2645  cvalue = rint(cvalue / table[i + 1].multiplier) *
2646  table[i + 1].multiplier;
2647 
2648  *base_value = cvalue;
2649  return true;
2650  }
2651  }
2652  return false;
2653 }
2654 
2655 /*
2656  * Convert an integer value in some base unit to a human-friendly unit.
2657  *
2658  * The output unit is chosen so that it's the greatest unit that can represent
2659  * the value without loss. For example, if the base unit is GUC_UNIT_KB, 1024
2660  * is converted to 1 MB, but 1025 is represented as 1025 kB.
2661  */
2662 static void
2663 convert_int_from_base_unit(int64 base_value, int base_unit,
2664  int64 *value, const char **unit)
2665 {
2666  const unit_conversion *table;
2667  int i;
2668 
2669  *unit = NULL;
2670 
2671  if (base_unit & GUC_UNIT_MEMORY)
2673  else
2675 
2676  for (i = 0; *table[i].unit; i++)
2677  {
2678  if (base_unit == table[i].base_unit)
2679  {
2680  /*
2681  * Accept the first conversion that divides the value evenly. We
2682  * assume that the conversions for each base unit are ordered from
2683  * greatest unit to the smallest!
2684  */
2685  if (table[i].multiplier <= 1.0 ||
2686  base_value % (int64) table[i].multiplier == 0)
2687  {
2688  *value = (int64) rint(base_value / table[i].multiplier);
2689  *unit = table[i].unit;
2690  break;
2691  }
2692  }
2693  }
2694 
2695  Assert(*unit != NULL);
2696 }
2697 
2698 /*
2699  * Convert a floating-point value in some base unit to a human-friendly unit.
2700  *
2701  * Same as above, except we have to do the math a bit differently, and
2702  * there's a possibility that we don't find any exact divisor.
2703  */
2704 static void
2705 convert_real_from_base_unit(double base_value, int base_unit,
2706  double *value, const char **unit)
2707 {
2708  const unit_conversion *table;
2709  int i;
2710 
2711  *unit = NULL;
2712 
2713  if (base_unit & GUC_UNIT_MEMORY)
2715  else
2717 
2718  for (i = 0; *table[i].unit; i++)
2719  {
2720  if (base_unit == table[i].base_unit)
2721  {
2722  /*
2723  * Accept the first conversion that divides the value evenly; or
2724  * if there is none, use the smallest (last) target unit.
2725  *
2726  * What we actually care about here is whether snprintf with "%g"
2727  * will print the value as an integer, so the obvious test of
2728  * "*value == rint(*value)" is too strict; roundoff error might
2729  * make us choose an unreasonably small unit. As a compromise,
2730  * accept a divisor that is within 1e-8 of producing an integer.
2731  */
2732  *value = base_value / table[i].multiplier;
2733  *unit = table[i].unit;
2734  if (*value > 0 &&
2735  fabs((rint(*value) / *value) - 1.0) <= 1e-8)
2736  break;
2737  }
2738  }
2739 
2740  Assert(*unit != NULL);
2741 }
2742 
2743 /*
2744  * Return the name of a GUC's base unit (e.g. "ms") given its flags.
2745  * Return NULL if the GUC is unitless.
2746  */
2747 const char *
2749 {
2750  switch (flags & (GUC_UNIT_MEMORY | GUC_UNIT_TIME))
2751  {
2752  case 0:
2753  return NULL; /* GUC has no units */
2754  case GUC_UNIT_BYTE:
2755  return "B";
2756  case GUC_UNIT_KB:
2757  return "kB";
2758  case GUC_UNIT_MB:
2759  return "MB";
2760  case GUC_UNIT_BLOCKS:
2761  {
2762  static char bbuf[8];
2763 
2764  /* initialize if first time through */
2765  if (bbuf[0] == '\0')
2766  snprintf(bbuf, sizeof(bbuf), "%dkB", BLCKSZ / 1024);
2767  return bbuf;
2768  }
2769  case GUC_UNIT_XBLOCKS:
2770  {
2771  static char xbuf[8];
2772 
2773  /* initialize if first time through */
2774  if (xbuf[0] == '\0')
2775  snprintf(xbuf, sizeof(xbuf), "%dkB", XLOG_BLCKSZ / 1024);
2776  return xbuf;
2777  }
2778  case GUC_UNIT_MS:
2779  return "ms";
2780  case GUC_UNIT_S:
2781  return "s";
2782  case GUC_UNIT_MIN:
2783  return "min";
2784  default:
2785  elog(ERROR, "unrecognized GUC units value: %d",
2787  return NULL;
2788  }
2789 }
2790 
2791 
2792 /*
2793  * Try to parse value as an integer. The accepted formats are the
2794  * usual decimal, octal, or hexadecimal formats, as well as floating-point
2795  * formats (which will be rounded to integer after any units conversion).
2796  * Optionally, the value can be followed by a unit name if "flags" indicates
2797  * a unit is allowed.
2798  *
2799  * If the string parses okay, return true, else false.
2800  * If okay and result is not NULL, return the value in *result.
2801  * If not okay and hintmsg is not NULL, *hintmsg is set to a suitable
2802  * HINT message, or NULL if no hint provided.
2803  */
2804 bool
2805 parse_int(const char *value, int *result, int flags, const char **hintmsg)
2806 {
2807  /*
2808  * We assume here that double is wide enough to represent any integer
2809  * value with adequate precision.
2810  */
2811  double val;
2812  char *endptr;
2813 
2814  /* To suppress compiler warnings, always set output params */
2815  if (result)
2816  *result = 0;
2817  if (hintmsg)
2818  *hintmsg = NULL;
2819 
2820  /*
2821  * Try to parse as an integer (allowing octal or hex input). If the
2822  * conversion stops at a decimal point or 'e', or overflows, re-parse as
2823  * float. This should work fine as long as we have no unit names starting
2824  * with 'e'. If we ever do, the test could be extended to check for a
2825  * sign or digit after 'e', but for now that's unnecessary.
2826  */
2827  errno = 0;
2828  val = strtol(value, &endptr, 0);
2829  if (*endptr == '.' || *endptr == 'e' || *endptr == 'E' ||
2830  errno == ERANGE)
2831  {
2832  errno = 0;
2833  val = strtod(value, &endptr);
2834  }
2835 
2836  if (endptr == value || errno == ERANGE)
2837  return false; /* no HINT for these cases */
2838 
2839  /* reject NaN (infinities will fail range check below) */
2840  if (isnan(val))
2841  return false; /* treat same as syntax error; no HINT */
2842 
2843  /* allow whitespace between number and unit */
2844  while (isspace((unsigned char) *endptr))
2845  endptr++;
2846 
2847  /* Handle possible unit */
2848  if (*endptr != '\0')
2849  {
2850  if ((flags & GUC_UNIT) == 0)
2851  return false; /* this setting does not accept a unit */
2852 
2854  endptr, (flags & GUC_UNIT),
2855  &val))
2856  {
2857  /* invalid unit, or garbage after the unit; set hint and fail. */
2858  if (hintmsg)
2859  {
2860  if (flags & GUC_UNIT_MEMORY)
2861  *hintmsg = memory_units_hint;
2862  else
2863  *hintmsg = time_units_hint;
2864  }
2865  return false;
2866  }
2867  }
2868 
2869  /* Round to int, then check for overflow */
2870  val = rint(val);
2871 
2872  if (val > INT_MAX || val < INT_MIN)
2873  {
2874  if (hintmsg)
2875  *hintmsg = gettext_noop("Value exceeds integer range.");
2876  return false;
2877  }
2878 
2879  if (result)
2880  *result = (int) val;
2881  return true;
2882 }
2883 
2884 /*
2885  * Try to parse value as a floating point number in the usual format.
2886  * Optionally, the value can be followed by a unit name if "flags" indicates
2887  * a unit is allowed.
2888  *
2889  * If the string parses okay, return true, else false.
2890  * If okay and result is not NULL, return the value in *result.
2891  * If not okay and hintmsg is not NULL, *hintmsg is set to a suitable
2892  * HINT message, or NULL if no hint provided.
2893  */
2894 bool
2895 parse_real(const char *value, double *result, int flags, const char **hintmsg)
2896 {
2897  double val;
2898  char *endptr;
2899 
2900  /* To suppress compiler warnings, always set output params */
2901  if (result)
2902  *result = 0;
2903  if (hintmsg)
2904  *hintmsg = NULL;
2905 
2906  errno = 0;
2907  val = strtod(value, &endptr);
2908 
2909  if (endptr == value || errno == ERANGE)
2910  return false; /* no HINT for these cases */
2911 
2912  /* reject NaN (infinities will fail range checks later) */
2913  if (isnan(val))
2914  return false; /* treat same as syntax error; no HINT */
2915 
2916  /* allow whitespace between number and unit */
2917  while (isspace((unsigned char) *endptr))
2918  endptr++;
2919 
2920  /* Handle possible unit */
2921  if (*endptr != '\0')
2922  {
2923  if ((flags & GUC_UNIT) == 0)
2924  return false; /* this setting does not accept a unit */
2925 
2927  endptr, (flags & GUC_UNIT),
2928  &val))
2929  {
2930  /* invalid unit, or garbage after the unit; set hint and fail. */
2931  if (hintmsg)
2932  {
2933  if (flags & GUC_UNIT_MEMORY)
2934  *hintmsg = memory_units_hint;
2935  else
2936  *hintmsg = time_units_hint;
2937  }
2938  return false;
2939  }
2940  }
2941 
2942  if (result)
2943  *result = val;
2944  return true;
2945 }
2946 
2947 
2948 /*
2949  * Lookup the name for an enum option with the selected value.
2950  * Should only ever be called with known-valid values, so throws
2951  * an elog(ERROR) if the enum option is not found.
2952  *
2953  * The returned string is a pointer to static data and not
2954  * allocated for modification.
2955  */
2956 const char *
2958 {
2959  const struct config_enum_entry *entry;
2960 
2961  for (entry = record->options; entry && entry->name; entry++)
2962  {
2963  if (entry->val == val)
2964  return entry->name;
2965  }
2966 
2967  elog(ERROR, "could not find enum option %d for %s",
2968  val, record->gen.name);
2969  return NULL; /* silence compiler */
2970 }
2971 
2972 
2973 /*
2974  * Lookup the value for an enum option with the selected name
2975  * (case-insensitive).
2976  * If the enum option is found, sets the retval value and returns
2977  * true. If it's not found, return false and retval is set to 0.
2978  */
2979 bool
2980 config_enum_lookup_by_name(struct config_enum *record, const char *value,
2981  int *retval)
2982 {
2983  const struct config_enum_entry *entry;
2984 
2985  for (entry = record->options; entry && entry->name; entry++)
2986  {
2987  if (pg_strcasecmp(value, entry->name) == 0)
2988  {
2989  *retval = entry->val;
2990  return true;
2991  }
2992  }
2993 
2994  *retval = 0;
2995  return false;
2996 }
2997 
2998 
2999 /*
3000  * Return a palloc'd string listing all the available options for an enum GUC
3001  * (excluding hidden ones), separated by the given separator.
3002  * If prefix is non-NULL, it is added before the first enum value.
3003  * If suffix is non-NULL, it is added to the end of the string.
3004  */
3005 char *
3006 config_enum_get_options(struct config_enum *record, const char *prefix,
3007  const char *suffix, const char *separator)
3008 {
3009  const struct config_enum_entry *entry;
3010  StringInfoData retstr;
3011  int seplen;
3012 
3013  initStringInfo(&retstr);
3014  appendStringInfoString(&retstr, prefix);
3015 
3016  seplen = strlen(separator);
3017  for (entry = record->options; entry && entry->name; entry++)
3018  {
3019  if (!entry->hidden)
3020  {
3021  appendStringInfoString(&retstr, entry->name);
3022  appendBinaryStringInfo(&retstr, separator, seplen);
3023  }
3024  }
3025 
3026  /*
3027  * All the entries may have been hidden, leaving the string empty if no
3028  * prefix was given. This indicates a broken GUC setup, since there is no
3029  * use for an enum without any values, so we just check to make sure we
3030  * don't write to invalid memory instead of actually trying to do
3031  * something smart with it.
3032  */
3033  if (retstr.len >= seplen)
3034  {
3035  /* Replace final separator */
3036  retstr.data[retstr.len - seplen] = '\0';
3037  retstr.len -= seplen;
3038  }
3039 
3040  appendStringInfoString(&retstr, suffix);
3041 
3042  return retstr.data;
3043 }
3044 
3045 /*
3046  * Parse and validate a proposed value for the specified configuration
3047  * parameter.
3048  *
3049  * This does built-in checks (such as range limits for an integer parameter)
3050  * and also calls any check hook the parameter may have.
3051  *
3052  * record: GUC variable's info record
3053  * name: variable name (should match the record of course)
3054  * value: proposed value, as a string
3055  * source: identifies source of value (check hooks may need this)
3056  * elevel: level to log any error reports at
3057  * newval: on success, converted parameter value is returned here
3058  * newextra: on success, receives any "extra" data returned by check hook
3059  * (caller must initialize *newextra to NULL)
3060  *
3061  * Returns true if OK, false if not (or throws error, if elevel >= ERROR)
3062  */
3063 static bool
3065  const char *name, const char *value,
3066  GucSource source, int elevel,
3067  union config_var_val *newval, void **newextra)
3068 {
3069  switch (record->vartype)
3070  {
3071  case PGC_BOOL:
3072  {
3073  struct config_bool *conf = (struct config_bool *) record;
3074 
3075  if (!parse_bool(value, &newval->boolval))
3076  {
3077  ereport(elevel,
3078  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3079  errmsg("parameter \"%s\" requires a Boolean value",
3080  name)));
3081  return false;
3082  }
3083 
3084  if (!call_bool_check_hook(conf, &newval->boolval, newextra,
3085  source, elevel))
3086  return false;
3087  }
3088  break;
3089  case PGC_INT:
3090  {
3091  struct config_int *conf = (struct config_int *) record;
3092  const char *hintmsg;
3093 
3094  if (!parse_int(value, &newval->intval,
3095  conf->gen.flags, &hintmsg))
3096  {
3097  ereport(elevel,
3098  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3099  errmsg("invalid value for parameter \"%s\": \"%s\"",
3100  name, value),
3101  hintmsg ? errhint("%s", _(hintmsg)) : 0));
3102  return false;
3103  }
3104 
3105  if (newval->intval < conf->min || newval->intval > conf->max)
3106  {
3107  const char *unit = get_config_unit_name(conf->gen.flags);
3108 
3109  ereport(elevel,
3110  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3111  errmsg("%d%s%s is outside the valid range for parameter \"%s\" (%d .. %d)",
3112  newval->intval,
3113  unit ? " " : "",
3114  unit ? unit : "",
3115  name,
3116  conf->min, conf->max)));
3117  return false;
3118  }
3119 
3120  if (!call_int_check_hook(conf, &newval->intval, newextra,
3121  source, elevel))
3122  return false;
3123  }
3124  break;
3125  case PGC_REAL:
3126  {
3127  struct config_real *conf = (struct config_real *) record;
3128  const char *hintmsg;
3129 
3130  if (!parse_real(value, &newval->realval,
3131  conf->gen.flags, &hintmsg))
3132  {
3133  ereport(elevel,
3134  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3135  errmsg("invalid value for parameter \"%s\": \"%s\"",
3136  name, value),
3137  hintmsg ? errhint("%s", _(hintmsg)) : 0));
3138  return false;
3139  }
3140 
3141  if (newval->realval < conf->min || newval->realval > conf->max)
3142  {
3143  const char *unit = get_config_unit_name(conf->gen.flags);
3144 
3145  ereport(elevel,
3146  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3147  errmsg("%g%s%s is outside the valid range for parameter \"%s\" (%g .. %g)",
3148  newval->realval,
3149  unit ? " " : "",
3150  unit ? unit : "",
3151  name,
3152  conf->min, conf->max)));
3153  return false;
3154  }
3155 
3156  if (!call_real_check_hook(conf, &newval->realval, newextra,
3157  source, elevel))
3158  return false;
3159  }
3160  break;
3161  case PGC_STRING:
3162  {
3163  struct config_string *conf = (struct config_string *) record;
3164 
3165  /*
3166  * The value passed by the caller could be transient, so we
3167  * always strdup it.
3168  */
3169  newval->stringval = guc_strdup(elevel, value);
3170  if (newval->stringval == NULL)
3171  return false;
3172 
3173  /*
3174  * The only built-in "parsing" check we have is to apply
3175  * truncation if GUC_IS_NAME.
3176  */
3177  if (conf->gen.flags & GUC_IS_NAME)
3178  truncate_identifier(newval->stringval,
3179  strlen(newval->stringval),
3180  true);
3181 
3182  if (!call_string_check_hook(conf, &newval->stringval, newextra,
3183  source, elevel))
3184  {
3185  guc_free(newval->stringval);
3186  newval->stringval = NULL;
3187  return false;
3188  }
3189  }
3190  break;
3191  case PGC_ENUM:
3192  {
3193  struct config_enum *conf = (struct config_enum *) record;
3194 
3195  if (!config_enum_lookup_by_name(conf, value, &newval->enumval))
3196  {
3197  char *hintmsg;
3198 
3199  hintmsg = config_enum_get_options(conf,
3200  "Available values: ",
3201  ".", ", ");
3202 
3203  ereport(elevel,
3204  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3205  errmsg("invalid value for parameter \"%s\": \"%s\"",
3206  name, value),
3207  hintmsg ? errhint("%s", _(hintmsg)) : 0));
3208 
3209  if (hintmsg)
3210  pfree(hintmsg);
3211  return false;
3212  }
3213 
3214  if (!call_enum_check_hook(conf, &newval->enumval, newextra,
3215  source, elevel))
3216  return false;
3217  }
3218  break;
3219  }
3220 
3221  return true;
3222 }
3223 
3224 
3225 /*
3226  * set_config_option: sets option `name' to given value.
3227  *
3228  * The value should be a string, which will be parsed and converted to
3229  * the appropriate data type. The context and source parameters indicate
3230  * in which context this function is being called, so that it can apply the
3231  * access restrictions properly.
3232  *
3233  * If value is NULL, set the option to its default value (normally the
3234  * reset_val, but if source == PGC_S_DEFAULT we instead use the boot_val).
3235  *
3236  * action indicates whether to set the value globally in the session, locally
3237  * to the current top transaction, or just for the duration of a function call.
3238  *
3239  * If changeVal is false then don't really set the option but do all
3240  * the checks to see if it would work.
3241  *
3242  * elevel should normally be passed as zero, allowing this function to make
3243  * its standard choice of ereport level. However some callers need to be
3244  * able to override that choice; they should pass the ereport level to use.
3245  *
3246  * is_reload should be true only when called from read_nondefault_variables()
3247  * or RestoreGUCState(), where we are trying to load some other process's
3248  * GUC settings into a new process.
3249  *
3250  * Return value:
3251  * +1: the value is valid and was successfully applied.
3252  * 0: the name or value is invalid (but see below).
3253  * -1: the value was not applied because of context, priority, or changeVal.
3254  *
3255  * If there is an error (non-existing option, invalid value) then an
3256  * ereport(ERROR) is thrown *unless* this is called for a source for which
3257  * we don't want an ERROR (currently, those are defaults, the config file,
3258  * and per-database or per-user settings, as well as callers who specify
3259  * a less-than-ERROR elevel). In those cases we write a suitable error
3260  * message via ereport() and return 0.
3261  *
3262  * See also SetConfigOption for an external interface.
3263  */
3264 int
3265 set_config_option(const char *name, const char *value,
3266  GucContext context, GucSource source,
3267  GucAction action, bool changeVal, int elevel,
3268  bool is_reload)
3269 {
3270  Oid srole;
3271 
3272  /*
3273  * Non-interactive sources should be treated as having all privileges,
3274  * except for PGC_S_CLIENT. Note in particular that this is true for
3275  * pg_db_role_setting sources (PGC_S_GLOBAL etc): we assume a suitable
3276  * privilege check was done when the pg_db_role_setting entry was made.
3277  */
3279  srole = GetUserId();
3280  else
3281  srole = BOOTSTRAP_SUPERUSERID;
3282 
3284  context, source, srole,
3285  action, changeVal, elevel,
3286  is_reload);
3287 }
3288 
3289 /*
3290  * set_config_option_ext: sets option `name' to given value.
3291  *
3292  * This API adds the ability to explicitly specify which role OID
3293  * is considered to be setting the value. Most external callers can use
3294  * set_config_option() and let it determine that based on the GucSource,
3295  * but there are a few that are supplying a value that was determined
3296  * in some special way and need to override the decision. Also, when
3297  * restoring a previously-assigned value, it's important to supply the
3298  * same role OID that set the value originally; so all guc.c callers
3299  * that are doing that type of thing need to call this directly.
3300  *
3301  * Generally, srole should be GetUserId() when the source is a SQL operation,
3302  * or BOOTSTRAP_SUPERUSERID if the source is a config file or similar.
3303  */
3304 int
3305 set_config_option_ext(const char *name, const char *value,
3306  GucContext context, GucSource source, Oid srole,
3307  GucAction action, bool changeVal, int elevel,
3308  bool is_reload)
3309 {
3310  struct config_generic *record;
3311  union config_var_val newval_union;
3312  void *newextra = NULL;
3313  bool prohibitValueChange = false;
3314  bool makeDefault;
3315 
3316  if (elevel == 0)
3317  {
3318  if (source == PGC_S_DEFAULT || source == PGC_S_FILE)
3319  {
3320  /*
3321  * To avoid cluttering the log, only the postmaster bleats loudly
3322  * about problems with the config file.
3323  */
3324  elevel = IsUnderPostmaster ? DEBUG3 : LOG;
3325  }
3326  else if (source == PGC_S_GLOBAL ||
3327  source == PGC_S_DATABASE ||
3328  source == PGC_S_USER ||
3330  elevel = WARNING;
3331  else
3332  elevel = ERROR;
3333  }
3334 
3335  /*
3336  * GUC_ACTION_SAVE changes are acceptable during a parallel operation,
3337  * because the current worker will also pop the change. We're probably
3338  * dealing with a function having a proconfig entry. Only the function's
3339  * body should observe the change, and peer workers do not share in the
3340  * execution of a function call started by this worker.
3341  *
3342  * Other changes might need to affect other workers, so forbid them.
3343  */
3344  if (IsInParallelMode() && changeVal && action != GUC_ACTION_SAVE)
3345  ereport(elevel,
3346  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
3347  errmsg("cannot set parameters during a parallel operation")));
3348 
3349  record = find_option(name, true, false, elevel);
3350  if (record == NULL)
3351  return 0;
3352 
3353  /*
3354  * Check if the option can be set at this time. See guc.h for the precise
3355  * rules.
3356  */
3357  switch (record->context)
3358  {
3359  case PGC_INTERNAL:
3360  if (context != PGC_INTERNAL)
3361  {
3362  ereport(elevel,
3363  (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
3364  errmsg("parameter \"%s\" cannot be changed",
3365  name)));
3366  return 0;
3367  }
3368  break;
3369  case PGC_POSTMASTER:
3370  if (context == PGC_SIGHUP)
3371  {
3372  /*
3373  * We are re-reading a PGC_POSTMASTER variable from
3374  * postgresql.conf. We can't change the setting, so we should
3375  * give a warning if the DBA tries to change it. However,
3376  * because of variant formats, canonicalization by check
3377  * hooks, etc, we can't just compare the given string directly
3378  * to what's stored. Set a flag to check below after we have
3379  * the final storable value.
3380  */
3381  prohibitValueChange = true;
3382  }
3383  else if (context != PGC_POSTMASTER)
3384  {
3385  ereport(elevel,
3386  (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
3387  errmsg("parameter \"%s\" cannot be changed without restarting the server",
3388  name)));
3389  return 0;
3390  }
3391  break;
3392  case PGC_SIGHUP:
3393  if (context != PGC_SIGHUP && context != PGC_POSTMASTER)
3394  {
3395  ereport(elevel,
3396  (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
3397  errmsg("parameter \"%s\" cannot be changed now",
3398  name)));
3399  return 0;
3400  }
3401 
3402  /*
3403  * Hmm, the idea of the SIGHUP context is "ought to be global, but
3404  * can be changed after postmaster start". But there's nothing
3405  * that prevents a crafty administrator from sending SIGHUP
3406  * signals to individual backends only.
3407  */
3408  break;
3409  case PGC_SU_BACKEND:
3410  if (context == PGC_BACKEND)
3411  {
3412  /*
3413  * Check whether the requesting user has been granted
3414  * privilege to set this GUC.
3415  */
3416  AclResult aclresult;
3417 
3418  aclresult = pg_parameter_aclcheck(name, srole, ACL_SET);
3419  if (aclresult != ACLCHECK_OK)
3420  {
3421  /* No granted privilege */
3422  ereport(elevel,
3423  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3424  errmsg("permission denied to set parameter \"%s\"",
3425  name)));
3426  return 0;
3427  }
3428  }
3429  /* fall through to process the same as PGC_BACKEND */
3430  /* FALLTHROUGH */
3431  case PGC_BACKEND:
3432  if (context == PGC_SIGHUP)
3433  {
3434  /*
3435  * If a PGC_BACKEND or PGC_SU_BACKEND parameter is changed in
3436  * the config file, we want to accept the new value in the
3437  * postmaster (whence it will propagate to
3438  * subsequently-started backends), but ignore it in existing
3439  * backends. This is a tad klugy, but necessary because we
3440  * don't re-read the config file during backend start.
3441  *
3442  * In EXEC_BACKEND builds, this works differently: we load all
3443  * non-default settings from the CONFIG_EXEC_PARAMS file
3444  * during backend start. In that case we must accept
3445  * PGC_SIGHUP settings, so as to have the same value as if
3446  * we'd forked from the postmaster. This can also happen when
3447  * using RestoreGUCState() within a background worker that
3448  * needs to have the same settings as the user backend that
3449  * started it. is_reload will be true when either situation
3450  * applies.
3451  */
3452  if (IsUnderPostmaster && !is_reload)
3453  return -1;
3454  }
3455  else if (context != PGC_POSTMASTER &&
3456  context != PGC_BACKEND &&
3457  context != PGC_SU_BACKEND &&
3458  source != PGC_S_CLIENT)
3459  {
3460  ereport(elevel,
3461  (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
3462  errmsg("parameter \"%s\" cannot be set after connection start",
3463  name)));
3464  return 0;
3465  }
3466  break;
3467  case PGC_SUSET:
3468  if (context == PGC_USERSET || context == PGC_BACKEND)
3469  {
3470  /*
3471  * Check whether the requesting user has been granted
3472  * privilege to set this GUC.
3473  */
3474  AclResult aclresult;
3475 
3476  aclresult = pg_parameter_aclcheck(name, srole, ACL_SET);
3477  if (aclresult != ACLCHECK_OK)
3478  {
3479  /* No granted privilege */
3480  ereport(elevel,
3481  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3482  errmsg("permission denied to set parameter \"%s\"",
3483  name)));
3484  return 0;
3485  }
3486  }
3487  break;
3488  case PGC_USERSET:
3489  /* always okay */
3490  break;
3491  }
3492 
3493  /*
3494  * Disallow changing GUC_NOT_WHILE_SEC_REST values if we are inside a
3495  * security restriction context. We can reject this regardless of the GUC
3496  * context or source, mainly because sources that it might be reasonable
3497  * to override for won't be seen while inside a function.
3498  *
3499  * Note: variables marked GUC_NOT_WHILE_SEC_REST should usually be marked
3500  * GUC_NO_RESET_ALL as well, because ResetAllOptions() doesn't check this.
3501  * An exception might be made if the reset value is assumed to be "safe".
3502  *
3503  * Note: this flag is currently used for "session_authorization" and
3504  * "role". We need to prohibit changing these inside a local userid
3505  * context because when we exit it, GUC won't be notified, leaving things
3506  * out of sync. (This could be fixed by forcing a new GUC nesting level,
3507  * but that would change behavior in possibly-undesirable ways.) Also, we
3508  * prohibit changing these in a security-restricted operation because
3509  * otherwise RESET could be used to regain the session user's privileges.
3510  */
3511  if (record->flags & GUC_NOT_WHILE_SEC_REST)
3512  {
3513  if (InLocalUserIdChange())
3514  {
3515  /*
3516  * Phrasing of this error message is historical, but it's the most
3517  * common case.
3518  */
3519  ereport(elevel,
3520  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3521  errmsg("cannot set parameter \"%s\" within security-definer function",
3522  name)));
3523  return 0;
3524  }
3526  {
3527  ereport(elevel,
3528  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3529  errmsg("cannot set parameter \"%s\" within security-restricted operation",
3530  name)));
3531  return 0;
3532  }
3533  }
3534 
3535  /* Disallow resetting and saving GUC_NO_RESET values */
3536  if (record->flags & GUC_NO_RESET)
3537  {
3538  if (value == NULL)
3539  {
3540  ereport(elevel,
3541  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3542  errmsg("parameter \"%s\" cannot be reset", name)));
3543  return 0;
3544  }
3545  if (action == GUC_ACTION_SAVE)
3546  {
3547  ereport(elevel,
3548  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3549  errmsg("parameter \"%s\" cannot be set locally in functions",
3550  name)));
3551  return 0;
3552  }
3553  }
3554 
3555  /*
3556  * Should we set reset/stacked values? (If so, the behavior is not
3557  * transactional.) This is done either when we get a default value from
3558  * the database's/user's/client's default settings or when we reset a
3559  * value to its default.
3560  */
3561  makeDefault = changeVal && (source <= PGC_S_OVERRIDE) &&
3562  ((value != NULL) || source == PGC_S_DEFAULT);
3563 
3564  /*
3565  * Ignore attempted set if overridden by previously processed setting.
3566  * However, if changeVal is false then plow ahead anyway since we are
3567  * trying to find out if the value is potentially good, not actually use
3568  * it. Also keep going if makeDefault is true, since we may want to set
3569  * the reset/stacked values even if we can't set the variable itself.
3570  */
3571  if (record->source > source)
3572  {
3573  if (changeVal && !makeDefault)
3574  {
3575  elog(DEBUG3, "\"%s\": setting ignored because previous source is higher priority",
3576  name);
3577  return -1;
3578  }
3579  changeVal = false;
3580  }
3581 
3582  /*
3583  * Evaluate value and set variable.
3584  */
3585  switch (record->vartype)
3586  {
3587  case PGC_BOOL:
3588  {
3589  struct config_bool *conf = (struct config_bool *) record;
3590 
3591 #define newval (newval_union.boolval)
3592 
3593  if (value)
3594  {
3595  if (!parse_and_validate_value(record, name, value,
3596  source, elevel,
3597  &newval_union, &newextra))
3598  return 0;
3599  }
3600  else if (source == PGC_S_DEFAULT)
3601  {
3602  newval = conf->boot_val;
3603  if (!call_bool_check_hook(conf, &newval, &newextra,
3604  source, elevel))
3605  return 0;
3606  }
3607  else
3608  {
3609  newval = conf->reset_val;
3610  newextra = conf->reset_extra;
3611  source = conf->gen.reset_source;
3612  context = conf->gen.reset_scontext;
3613  srole = conf->gen.reset_srole;
3614  }
3615 
3616  if (prohibitValueChange)
3617  {
3618  /* Release newextra, unless it's reset_extra */
3619  if (newextra && !extra_field_used(&conf->gen, newextra))
3620  guc_free(newextra);
3621 
3622  if (*conf->variable != newval)
3623  {
3624  record->status |= GUC_PENDING_RESTART;
3625  ereport(elevel,
3626  (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
3627  errmsg("parameter \"%s\" cannot be changed without restarting the server",
3628  name)));
3629  return 0;
3630  }
3631  record->status &= ~GUC_PENDING_RESTART;
3632  return -1;
3633  }
3634 
3635  if (changeVal)
3636  {
3637  /* Save old value to support transaction abort */
3638  if (!makeDefault)
3639  push_old_value(&conf->gen, action);
3640 
3641  if (conf->assign_hook)
3642  conf->assign_hook(newval, newextra);
3643  *conf->variable = newval;
3644  set_extra_field(&conf->gen, &conf->gen.extra,
3645  newextra);
3646  set_guc_source(&conf->gen, source);
3647  conf->gen.scontext = context;
3648  conf->gen.srole = srole;
3649  }
3650  if (makeDefault)
3651  {
3652  GucStack *stack;
3653 
3654  if (conf->gen.reset_source <= source)
3655  {
3656  conf->reset_val = newval;
3657  set_extra_field(&conf->gen, &conf->reset_extra,
3658  newextra);
3659  conf->gen.reset_source = source;
3660  conf->gen.reset_scontext = context;
3661  conf->gen.reset_srole = srole;
3662  }
3663  for (stack = conf->gen.stack; stack; stack = stack->prev)
3664  {
3665  if (stack->source <= source)
3666  {
3667  stack->prior.val.boolval = newval;
3668  set_extra_field(&conf->gen, &stack->prior.extra,
3669  newextra);
3670  stack->source = source;
3671  stack->scontext = context;
3672  stack->srole = srole;
3673  }
3674  }
3675  }
3676 
3677  /* Perhaps we didn't install newextra anywhere */
3678  if (newextra && !extra_field_used(&conf->gen, newextra))
3679  guc_free(newextra);
3680  break;
3681 
3682 #undef newval
3683  }
3684 
3685  case PGC_INT:
3686  {
3687  struct config_int *conf = (struct config_int *) record;
3688 
3689 #define newval (newval_union.intval)
3690 
3691  if (value)
3692  {
3693  if (!parse_and_validate_value(record, name, value,
3694  source, elevel,
3695  &newval_union, &newextra))
3696  return 0;
3697  }
3698  else if (source == PGC_S_DEFAULT)
3699  {
3700  newval = conf->boot_val;
3701  if (!call_int_check_hook(conf, &newval, &newextra,
3702  source, elevel))
3703  return 0;
3704  }
3705  else
3706  {
3707  newval = conf->reset_val;
3708  newextra = conf->reset_extra;
3709  source = conf->gen.reset_source;
3710  context = conf->gen.reset_scontext;
3711  srole = conf->gen.reset_srole;
3712  }
3713 
3714  if (prohibitValueChange)
3715  {
3716  /* Release newextra, unless it's reset_extra */
3717  if (newextra && !extra_field_used(&conf->gen, newextra))
3718  guc_free(newextra);
3719 
3720  if (*conf->variable != newval)
3721  {
3722  record->status |= GUC_PENDING_RESTART;
3723  ereport(elevel,
3724  (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
3725  errmsg("parameter \"%s\" cannot be changed without restarting the server",
3726  name)));
3727  return 0;
3728  }
3729  record->status &= ~GUC_PENDING_RESTART;
3730  return -1;
3731  }
3732 
3733  if (changeVal)
3734  {
3735  /* Save old value to support transaction abort */
3736  if (!makeDefault)
3737  push_old_value(&conf->gen, action);
3738 
3739  if (conf->assign_hook)
3740  conf->assign_hook(newval, newextra);
3741  *conf->variable = newval;
3742  set_extra_field(&conf->gen, &conf->gen.extra,
3743  newextra);
3744  set_guc_source(&conf->gen, source);
3745  conf->gen.scontext = context;
3746  conf->gen.srole = srole;
3747  }
3748  if (makeDefault)
3749  {
3750  GucStack *stack;
3751 
3752  if (conf->gen.reset_source <= source)
3753  {
3754  conf->reset_val = newval;
3755  set_extra_field(&conf->gen, &conf->reset_extra,
3756  newextra);
3757  conf->gen.reset_source = source;
3758  conf->gen.reset_scontext = context;
3759  conf->gen.reset_srole = srole;
3760  }
3761  for (stack = conf->gen.stack; stack; stack = stack->prev)
3762  {
3763  if (stack->source <= source)
3764  {
3765  stack->prior.val.intval = newval;
3766  set_extra_field(&conf->gen, &stack->prior.extra,
3767  newextra);
3768  stack->source = source;
3769  stack->scontext = context;
3770  stack->srole = srole;
3771  }
3772  }
3773  }
3774 
3775  /* Perhaps we didn't install newextra anywhere */
3776  if (newextra && !extra_field_used(&conf->gen, newextra))
3777  guc_free(newextra);
3778  break;
3779 
3780 #undef newval
3781  }
3782 
3783  case PGC_REAL:
3784  {
3785  struct config_real *conf = (struct config_real *) record;
3786 
3787 #define newval (newval_union.realval)
3788 
3789  if (value)
3790  {
3791  if (!parse_and_validate_value(record, name, value,
3792  source, elevel,
3793  &newval_union, &newextra))
3794  return 0;
3795  }
3796  else if (source == PGC_S_DEFAULT)
3797  {
3798  newval = conf->boot_val;
3799  if (!call_real_check_hook(conf, &newval, &newextra,
3800  source, elevel))
3801  return 0;
3802  }
3803  else
3804  {
3805  newval = conf->reset_val;
3806  newextra = conf->reset_extra;
3807  source = conf->gen.reset_source;
3808  context = conf->gen.reset_scontext;
3809  srole = conf->gen.reset_srole;
3810  }
3811 
3812  if (prohibitValueChange)
3813  {
3814  /* Release newextra, unless it's reset_extra */
3815  if (newextra && !extra_field_used(&conf->gen, newextra))
3816  guc_free(newextra);
3817 
3818  if (*conf->variable != newval)
3819  {
3820  record->status |= GUC_PENDING_RESTART;
3821  ereport(elevel,
3822  (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
3823  errmsg("parameter \"%s\" cannot be changed without restarting the server",
3824  name)));
3825  return 0;
3826  }
3827  record->status &= ~GUC_PENDING_RESTART;
3828  return -1;
3829  }
3830 
3831  if (changeVal)
3832  {
3833  /* Save old value to support transaction abort */
3834  if (!makeDefault)
3835  push_old_value(&conf->gen, action);
3836 
3837  if (conf->assign_hook)
3838  conf->assign_hook(newval, newextra);
3839  *conf->variable = newval;
3840  set_extra_field(&conf->gen, &conf->gen.extra,
3841  newextra);
3842  set_guc_source(&conf->gen, source);
3843  conf->gen.scontext = context;
3844  conf->gen.srole = srole;
3845  }
3846  if (makeDefault)
3847  {
3848  GucStack *stack;
3849 
3850  if (conf->gen.reset_source <= source)
3851  {
3852  conf->reset_val = newval;
3853  set_extra_field(&conf->gen, &conf->reset_extra,
3854  newextra);
3855  conf->gen.reset_source = source;
3856  conf->gen.reset_scontext = context;
3857  conf->gen.reset_srole = srole;
3858  }
3859  for (stack = conf->gen.stack; stack; stack = stack->prev)
3860  {
3861  if (stack->source <= source)
3862  {
3863  stack->prior.val.realval = newval;
3864  set_extra_field(&conf->gen, &stack->prior.extra,
3865  newextra);
3866  stack->source = source;
3867  stack->scontext = context;
3868  stack->srole = srole;
3869  }
3870  }
3871  }
3872 
3873  /* Perhaps we didn't install newextra anywhere */
3874  if (newextra && !extra_field_used(&conf->gen, newextra))
3875  guc_free(newextra);
3876  break;
3877 
3878 #undef newval
3879  }
3880 
3881  case PGC_STRING:
3882  {
3883  struct config_string *conf = (struct config_string *) record;
3884 
3885 #define newval (newval_union.stringval)
3886 
3887  if (value)
3888  {
3889  if (!parse_and_validate_value(record, name, value,
3890  source, elevel,
3891  &newval_union, &newextra))
3892  return 0;
3893  }
3894  else if (source == PGC_S_DEFAULT)
3895  {
3896  /* non-NULL boot_val must always get strdup'd */
3897  if (conf->boot_val != NULL)
3898  {
3899  newval = guc_strdup(elevel, conf->boot_val);
3900  if (newval == NULL)
3901  return 0;
3902  }
3903  else
3904  newval = NULL;
3905 
3906  if (!call_string_check_hook(conf, &newval, &newextra,
3907  source, elevel))
3908  {
3909  guc_free(newval);
3910  return 0;
3911  }
3912  }
3913  else
3914  {
3915  /*
3916  * strdup not needed, since reset_val is already under
3917  * guc.c's control
3918  */
3919  newval = conf->reset_val;
3920  newextra = conf->reset_extra;
3921  source = conf->gen.reset_source;
3922  context = conf->gen.reset_scontext;
3923  srole = conf->gen.reset_srole;
3924  }
3925 
3926  if (prohibitValueChange)
3927  {
3928  bool newval_different;
3929 
3930  /* newval shouldn't be NULL, so we're a bit sloppy here */
3931  newval_different = (*conf->variable == NULL ||
3932  newval == NULL ||
3933  strcmp(*conf->variable, newval) != 0);
3934 
3935  /* Release newval, unless it's reset_val */
3936  if (newval && !string_field_used(conf, newval))
3937  guc_free(newval);
3938  /* Release newextra, unless it's reset_extra */
3939  if (newextra && !extra_field_used(&conf->gen, newextra))
3940  guc_free(newextra);
3941 
3942  if (newval_different)
3943  {
3944  record->status |= GUC_PENDING_RESTART;
3945  ereport(elevel,
3946  (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
3947  errmsg("parameter \"%s\" cannot be changed without restarting the server",
3948  name)));
3949  return 0;
3950  }
3951  record->status &= ~GUC_PENDING_RESTART;
3952  return -1;
3953  }
3954 
3955  if (changeVal)
3956  {
3957  /* Save old value to support transaction abort */
3958  if (!makeDefault)
3959  push_old_value(&conf->gen, action);
3960 
3961  if (conf->assign_hook)
3962  conf->assign_hook(newval, newextra);
3963  set_string_field(conf, conf->variable, newval);
3964  set_extra_field(&conf->gen, &conf->gen.extra,
3965  newextra);
3966  set_guc_source(&conf->gen, source);
3967  conf->gen.scontext = context;
3968  conf->gen.srole = srole;
3969  }
3970 
3971  if (makeDefault)
3972  {
3973  GucStack *stack;
3974 
3975  if (conf->gen.reset_source <= source)
3976  {
3977  set_string_field(conf, &conf->reset_val, newval);
3978  set_extra_field(&conf->gen, &conf->reset_extra,
3979  newextra);
3980  conf->gen.reset_source = source;
3981  conf->gen.reset_scontext = context;
3982  conf->gen.reset_srole = srole;
3983  }
3984  for (stack = conf->gen.stack; stack; stack = stack->prev)
3985  {
3986  if (stack->source <= source)
3987  {
3988  set_string_field(conf, &stack->prior.val.stringval,
3989  newval);
3990  set_extra_field(&conf->gen, &stack->prior.extra,
3991  newextra);
3992  stack->source = source;
3993  stack->scontext = context;
3994  stack->srole = srole;
3995  }
3996  }
3997  }
3998 
3999  /* Perhaps we didn't install newval anywhere */
4000  if (newval && !string_field_used(conf, newval))
4001  guc_free(newval);
4002  /* Perhaps we didn't install newextra anywhere */
4003  if (newextra && !extra_field_used(&conf->gen, newextra))
4004  guc_free(newextra);
4005  break;
4006 
4007 #undef newval
4008  }
4009 
4010  case PGC_ENUM:
4011  {
4012  struct config_enum *conf = (struct config_enum *) record;
4013 
4014 #define newval (newval_union.enumval)
4015 
4016  if (value)
4017  {
4018  if (!parse_and_validate_value(record, name, value,
4019  source, elevel,
4020  &newval_union, &newextra))
4021  return 0;
4022  }
4023  else if (source == PGC_S_DEFAULT)
4024  {
4025  newval = conf->boot_val;
4026  if (!call_enum_check_hook(conf, &newval, &newextra,
4027  source, elevel))
4028  return 0;
4029  }
4030  else
4031  {
4032  newval = conf->reset_val;
4033  newextra = conf->reset_extra;
4034  source = conf->gen.reset_source;
4035  context = conf->gen.reset_scontext;
4036  srole = conf->gen.reset_srole;
4037  }
4038 
4039  if (prohibitValueChange)
4040  {
4041  /* Release newextra, unless it's reset_extra */
4042  if (newextra && !extra_field_used(&conf->gen, newextra))
4043  guc_free(newextra);
4044 
4045  if (*conf->variable != newval)
4046  {
4047  record->status |= GUC_PENDING_RESTART;
4048  ereport(elevel,
4049  (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
4050  errmsg("parameter \"%s\" cannot be changed without restarting the server",
4051  name)));
4052  return 0;
4053  }
4054  record->status &= ~GUC_PENDING_RESTART;
4055  return -1;
4056  }
4057 
4058  if (changeVal)
4059  {
4060  /* Save old value to support transaction abort */
4061  if (!makeDefault)
4062  push_old_value(&conf->gen, action);
4063 
4064  if (conf->assign_hook)
4065  conf->assign_hook(newval, newextra);
4066  *conf->variable = newval;
4067  set_extra_field(&conf->gen, &conf->gen.extra,
4068  newextra);
4069  set_guc_source(&conf->gen, source);
4070  conf->gen.scontext = context;
4071  conf->gen.srole = srole;
4072  }
4073  if (makeDefault)
4074  {
4075  GucStack *stack;
4076 
4077  if (conf->gen.reset_source <= source)
4078  {
4079  conf->reset_val = newval;
4080  set_extra_field(&conf->gen, &conf->reset_extra,
4081  newextra);
4082  conf->gen.reset_source = source;
4083  conf->gen.reset_scontext = context;
4084  conf->gen.reset_srole = srole;
4085  }
4086  for (stack = conf->gen.stack; stack; stack = stack->prev)
4087  {
4088  if (stack->source <= source)
4089  {
4090  stack->prior.val.enumval = newval;
4091  set_extra_field(&conf->gen, &stack->prior.extra,
4092  newextra);
4093  stack->source = source;
4094  stack->scontext = context;
4095  stack->srole = srole;
4096  }
4097  }
4098  }
4099 
4100  /* Perhaps we didn't install newextra anywhere */
4101  if (newextra && !extra_field_used(&conf->gen, newextra))
4102  guc_free(newextra);
4103  break;
4104 
4105 #undef newval
4106  }
4107  }
4108 
4109  if (changeVal && (record->flags & GUC_REPORT) &&
4110  !(record->status & GUC_NEEDS_REPORT))
4111  {
4112  record->status |= GUC_NEEDS_REPORT;
4114  }
4115 
4116  return changeVal ? 1 : -1;
4117 }
4118 
4119 
4120 /*
4121  * Set the fields for source file and line number the setting came from.
4122  */
4123 static void
4124 set_config_sourcefile(const char *name, char *sourcefile, int sourceline)
4125 {
4126  struct config_generic *record;
4127  int elevel;
4128 
4129  /*
4130  * To avoid cluttering the log, only the postmaster bleats loudly about
4131  * problems with the config file.
4132  */
4133  elevel = IsUnderPostmaster ? DEBUG3 : LOG;
4134 
4135  record = find_option(name, true, false, elevel);
4136  /* should not happen */
4137  if (record == NULL)
4138  return;
4139 
4140  sourcefile = guc_strdup(elevel, sourcefile);
4141  guc_free(record->sourcefile);
4142  record->sourcefile = sourcefile;
4143  record->sourceline = sourceline;
4144 }
4145 
4146 /*
4147  * Set a config option to the given value.
4148  *
4149  * See also set_config_option; this is just the wrapper to be called from
4150  * outside GUC. (This function should be used when possible, because its API
4151  * is more stable than set_config_option's.)
4152  *
4153  * Note: there is no support here for setting source file/line, as it
4154  * is currently not needed.
4155  */
4156 void
4157 SetConfigOption(const char *name, const char *value,
4159 {
4161  GUC_ACTION_SET, true, 0, false);
4162 }
4163 
4164 
4165 
4166 /*
4167  * Fetch the current value of the option `name', as a string.
4168  *
4169  * If the option doesn't exist, return NULL if missing_ok is true (NOTE that
4170  * this cannot be distinguished from a string variable with a NULL value!),
4171  * otherwise throw an ereport and don't return.
4172  *
4173  * If restrict_privileged is true, we also enforce that only superusers and
4174  * members of the pg_read_all_settings role can see GUC_SUPERUSER_ONLY
4175  * variables. This should only be passed as true in user-driven calls.
4176  *
4177  * The string is *not* allocated for modification and is really only
4178  * valid until the next call to configuration related functions.
4179  */
4180 const char *
4181 GetConfigOption(const char *name, bool missing_ok, bool restrict_privileged)
4182 {
4183  struct config_generic *record;
4184  static char buffer[256];
4185 
4186  record = find_option(name, false, missing_ok, ERROR);
4187  if (record == NULL)
4188  return NULL;
4189  if (restrict_privileged &&
4190  !ConfigOptionIsVisible(record))
4191  ereport(ERROR,
4192  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
4193  errmsg("must be superuser or have privileges of pg_read_all_settings to examine \"%s\"",
4194  name)));
4195 
4196  switch (record->vartype)
4197  {
4198  case PGC_BOOL:
4199  return *((struct config_bool *) record)->variable ? "on" : "off";
4200 
4201  case PGC_INT:
4202  snprintf(buffer, sizeof(buffer), "%d",
4203  *((struct config_int *) record)->variable);
4204  return buffer;
4205 
4206  case PGC_REAL:
4207  snprintf(buffer, sizeof(buffer), "%g",
4208  *((struct config_real *) record)->variable);
4209  return buffer;
4210 
4211  case PGC_STRING:
4212  return *((struct config_string *) record)->variable;
4213 
4214  case PGC_ENUM:
4215  return config_enum_lookup_by_value((struct config_enum *) record,
4216  *((struct config_enum *) record)->variable);
4217  }
4218  return NULL;
4219 }
4220 
4221 /*
4222  * Get the RESET value associated with the given option.
4223  *
4224  * Note: this is not re-entrant, due to use of static result buffer;
4225  * not to mention that a string variable could have its reset_val changed.
4226  * Beware of assuming the result value is good for very long.
4227  */
4228 const char *
4230 {
4231  struct config_generic *record;
4232  static char buffer[256];
4233 
4234  record = find_option(name, false, false, ERROR);
4235  Assert(record != NULL);
4236  if (!ConfigOptionIsVisible(record))
4237  ereport(ERROR,
4238  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
4239  errmsg("must be superuser or have privileges of pg_read_all_settings to examine \"%s\"",
4240  name)));
4241 
4242  switch (record->vartype)
4243  {
4244  case PGC_BOOL:
4245  return ((struct config_bool *) record)->reset_val ? "on" : "off";
4246 
4247  case PGC_INT:
4248  snprintf(buffer, sizeof(buffer), "%d",
4249  ((struct config_int *) record)->reset_val);
4250  return buffer;
4251 
4252  case PGC_REAL:
4253  snprintf(buffer, sizeof(buffer), "%g",
4254  ((struct config_real *) record)->reset_val);
4255  return buffer;
4256 
4257  case PGC_STRING:
4258  return ((struct config_string *) record)->reset_val;
4259 
4260  case PGC_ENUM:
4261  return config_enum_lookup_by_value((struct config_enum *) record,
4262  ((struct config_enum *) record)->reset_val);
4263  }
4264  return NULL;
4265 }
4266 
4267 /*
4268  * Get the GUC flags associated with the given option.
4269  *
4270  * If the option doesn't exist, return 0 if missing_ok is true,
4271  * otherwise throw an ereport and don't return.
4272  */
4273 int
4274 GetConfigOptionFlags(const char *name, bool missing_ok)
4275 {
4276  struct config_generic *record;
4277 
4278  record = find_option(name, false, missing_ok, ERROR);
4279  if (record == NULL)
4280  return 0;
4281  return record->flags;
4282 }
4283 
4284 
4285 /*
4286  * Write updated configuration parameter values into a temporary file.
4287  * This function traverses the list of parameters and quotes the string
4288  * values before writing them.
4289  */
4290 static void
4292 {
4294  ConfigVariable *item;
4295 
4296  initStringInfo(&buf);
4297 
4298  /* Emit file header containing warning comment */
4299  appendStringInfoString(&buf, "# Do not edit this file manually!\n");
4300  appendStringInfoString(&buf, "# It will be overwritten by the ALTER SYSTEM command.\n");
4301 
4302  errno = 0;
4303  if (write(fd, buf.data, buf.len) != buf.len)
4304  {
4305  /* if write didn't set errno, assume problem is no disk space */
4306  if (errno == 0)
4307  errno = ENOSPC;
4308  ereport(ERROR,
4310  errmsg("could not write to file \"%s\": %m", filename)));
4311  }
4312 
4313  /* Emit each parameter, properly quoting the value */
4314  for (item = head; item != NULL; item = item->next)
4315  {
4316  char *escaped;
4317 
4318  resetStringInfo(&buf);
4319 
4320  appendStringInfoString(&buf, item->name);
4321  appendStringInfoString(&buf, " = '");
4322 
4323  escaped = escape_single_quotes_ascii(item->value);
4324  if (!escaped)
4325  ereport(ERROR,
4326  (errcode(ERRCODE_OUT_OF_MEMORY),
4327  errmsg("out of memory")));
4328  appendStringInfoString(&buf, escaped);
4329  free(escaped);
4330 
4331  appendStringInfoString(&buf, "'\n");
4332 
4333  errno = 0;
4334  if (write(fd, buf.data, buf.len) != buf.len)
4335  {
4336  /* if write didn't set errno, assume problem is no disk space */
4337  if (errno == 0)
4338  errno = ENOSPC;
4339  ereport(ERROR,
4341  errmsg("could not write to file \"%s\": %m", filename)));
4342  }
4343  }
4344 
4345  /* fsync before considering the write to be successful */
4346  if (pg_fsync(fd) != 0)
4347  ereport(ERROR,
4349  errmsg("could not fsync file \"%s\": %m", filename)));
4350 
4351  pfree(buf.data);
4352 }
4353 
4354 /*
4355  * Update the given list of configuration parameters, adding, replacing
4356  * or deleting the entry for item "name" (delete if "value" == NULL).
4357  */
4358 static void
4360  const char *name, const char *value)
4361 {
4362  ConfigVariable *item,
4363  *next,
4364  *prev = NULL;
4365 
4366  /*
4367  * Remove any existing match(es) for "name". Normally there'd be at most
4368  * one, but if external tools have modified the config file, there could
4369  * be more.
4370  */
4371  for (item = *head_p; item != NULL; item = next)
4372  {
4373  next = item->next;
4374  if (guc_name_compare(item->name, name) == 0)
4375  {
4376  /* found a match, delete it */
4377  if (prev)
4378  prev->next = next;
4379  else
4380  *head_p = next;
4381  if (next == NULL)
4382  *tail_p = prev;
4383 
4384  pfree(item->name);
4385  pfree(item->value);
4386  pfree(item->filename);
4387  pfree(item);
4388  }
4389  else
4390  prev = item;
4391  }
4392 
4393  /* Done if we're trying to delete it */
4394  if (value == NULL)
4395  return;
4396 
4397  /* OK, append a new entry */
4398  item = palloc(sizeof *item);
4399  item->name = pstrdup(name);
4400  item->value = pstrdup(value);
4401  item->errmsg = NULL;
4402  item->filename = pstrdup(""); /* new item has no location */
4403  item->sourceline = 0;
4404  item->ignore = false;
4405  item->applied = false;
4406  item->next = NULL;
4407 
4408  if (*head_p == NULL)
4409  *head_p = item;
4410  else
4411  (*tail_p)->next = item;
4412  *tail_p = item;
4413 }
4414 
4415 
4416 /*
4417  * Execute ALTER SYSTEM statement.
4418  *
4419  * Read the old PG_AUTOCONF_FILENAME file, merge in the new variable value,
4420  * and write out an updated file. If the command is ALTER SYSTEM RESET ALL,
4421  * we can skip reading the old file and just write an empty file.
4422  *
4423  * An LWLock is used to serialize updates of the configuration file.
4424  *
4425  * In case of an error, we leave the original automatic
4426  * configuration file (PG_AUTOCONF_FILENAME) intact.
4427  */
4428 void
4430 {
4431  char *name;
4432  char *value;
4433  bool resetall = false;
4434  ConfigVariable *head = NULL;
4435  ConfigVariable *tail = NULL;
4436  volatile int Tmpfd;
4437  char AutoConfFileName[MAXPGPATH];
4438  char AutoConfTmpFileName[MAXPGPATH];
4439 
4440  /*
4441  * Extract statement arguments
4442  */
4443  name = altersysstmt->setstmt->name;
4444 
4445  switch (altersysstmt->setstmt->kind)
4446  {
4447  case VAR_SET_VALUE:
4448  value = ExtractSetVariableArgs(altersysstmt->setstmt);
4449  break;
4450 
4451  case VAR_SET_DEFAULT:
4452  case VAR_RESET:
4453  value = NULL;
4454  break;
4455 
4456  case VAR_RESET_ALL:
4457  value = NULL;
4458  resetall = true;
4459  break;
4460 
4461  default:
4462  elog(ERROR, "unrecognized alter system stmt type: %d",
4463  altersysstmt->setstmt->kind);
4464  break;
4465  }
4466 
4467  /*
4468  * Check permission to run ALTER SYSTEM on the target variable
4469  */
4470  if (!superuser())
4471  {
4472  if (resetall)
4473  ereport(ERROR,
4474  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
4475  errmsg("permission denied to perform ALTER SYSTEM RESET ALL")));
4476  else
4477  {
4478  AclResult aclresult;
4479 
4480  aclresult = pg_parameter_aclcheck(name, GetUserId(),
4482  if (aclresult != ACLCHECK_OK)
4483  ereport(ERROR,
4484  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
4485  errmsg("permission denied to set parameter \"%s\"",
4486  name)));
4487  }
4488  }
4489 
4490  /*
4491  * Unless it's RESET_ALL, validate the target variable and value
4492  */
4493  if (!resetall)
4494  {
4495  struct config_generic *record;
4496 
4497  record = find_option(name, false, false, ERROR);
4498  Assert(record != NULL);
4499 
4500  /*
4501  * Don't allow parameters that can't be set in configuration files to
4502  * be set in PG_AUTOCONF_FILENAME file.
4503  */
4504  if ((record->context == PGC_INTERNAL) ||
4505  (record->flags & GUC_DISALLOW_IN_FILE) ||
4506  (record->flags & GUC_DISALLOW_IN_AUTO_FILE))
4507  ereport(ERROR,
4508  (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
4509  errmsg("parameter \"%s\" cannot be changed",
4510  name)));
4511 
4512  /*
4513  * If a value is specified, verify that it's sane.
4514  */
4515  if (value)
4516  {
4517  union config_var_val newval;
4518  void *newextra = NULL;
4519 
4520  /* Check that it's acceptable for the indicated parameter */
4521  if (!parse_and_validate_value(record, name, value,
4522  PGC_S_FILE, ERROR,
4523  &newval, &newextra))
4524  ereport(ERROR,
4525  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4526  errmsg("invalid value for parameter \"%s\": \"%s\"",
4527  name, value)));
4528 
4529  if (record->vartype == PGC_STRING && newval.stringval != NULL)
4530  guc_free(newval.stringval);
4531  guc_free(newextra);
4532 
4533  /*
4534  * We must also reject values containing newlines, because the
4535  * grammar for config files doesn't support embedded newlines in
4536  * string literals.
4537  */
4538  if (strchr(value, '\n'))
4539  ereport(ERROR,
4540  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4541  errmsg("parameter value for ALTER SYSTEM must not contain a newline")));
4542  }
4543  }
4544 
4545  /*
4546  * PG_AUTOCONF_FILENAME and its corresponding temporary file are always in
4547  * the data directory, so we can reference them by simple relative paths.
4548  */
4549  snprintf(AutoConfFileName, sizeof(AutoConfFileName), "%s",
4551  snprintf(AutoConfTmpFileName, sizeof(AutoConfTmpFileName), "%s.%s",
4552  AutoConfFileName,
4553  "tmp");
4554 
4555  /*
4556  * Only one backend is allowed to operate on PG_AUTOCONF_FILENAME at a
4557  * time. Use AutoFileLock to ensure that. We must hold the lock while
4558  * reading the old file contents.
4559  */
4560  LWLockAcquire(AutoFileLock, LW_EXCLUSIVE);
4561 
4562  /*
4563  * If we're going to reset everything, then no need to open or parse the
4564  * old file. We'll just write out an empty list.
4565  */
4566  if (!resetall)
4567  {
4568  struct stat st;
4569 
4570  if (stat(AutoConfFileName, &st) == 0)
4571  {
4572  /* open old file PG_AUTOCONF_FILENAME */
4573  FILE *infile;
4574 
4575  infile = AllocateFile(AutoConfFileName, "r");
4576  if (infile == NULL)
4577  ereport(ERROR,
4579  errmsg("could not open file \"%s\": %m",
4580  AutoConfFileName)));
4581 
4582  /* parse it */
4583  if (!ParseConfigFp(infile, AutoConfFileName, CONF_FILE_START_DEPTH,
4584  LOG, &head, &tail))
4585  ereport(ERROR,
4586  (errcode(ERRCODE_CONFIG_FILE_ERROR),
4587  errmsg("could not parse contents of file \"%s\"",
4588  AutoConfFileName)));
4589 
4590  FreeFile(infile);
4591  }
4592 
4593  /*
4594  * Now, replace any existing entry with the new value, or add it if
4595  * not present.
4596  */
4597  replace_auto_config_value(&head, &tail, name, value);
4598  }
4599 
4600  /*
4601  * Invoke the post-alter hook for setting this GUC variable. GUCs
4602  * typically do not have corresponding entries in pg_parameter_acl, so we
4603  * call the hook using the name rather than a potentially-non-existent
4604  * OID. Nonetheless, we pass ParameterAclRelationId so that this call
4605  * context can be distinguished from others. (Note that "name" will be
4606  * NULL in the RESET ALL case.)
4607  *
4608  * We do this here rather than at the end, because ALTER SYSTEM is not
4609  * transactional. If the hook aborts our transaction, it will be cleaner
4610  * to do so before we touch any files.
4611  */
4612  InvokeObjectPostAlterHookArgStr(ParameterAclRelationId, name,
4614  altersysstmt->setstmt->kind,
4615  false);
4616 
4617  /*
4618  * To ensure crash safety, first write the new file data to a temp file,
4619  * then atomically rename it into place.
4620  *
4621  * If there is a temp file left over due to a previous crash, it's okay to
4622  * truncate and reuse it.
4623  */
4624  Tmpfd = BasicOpenFile(AutoConfTmpFileName,
4625  O_CREAT | O_RDWR | O_TRUNC);
4626  if (Tmpfd < 0)
4627  ereport(ERROR,
4629  errmsg("could not open file \"%s\": %m",
4630  AutoConfTmpFileName)));
4631 
4632  /*
4633  * Use a TRY block to clean up the file if we fail. Since we need a TRY
4634  * block anyway, OK to use BasicOpenFile rather than OpenTransientFile.
4635  */
4636  PG_TRY();
4637  {
4638  /* Write and sync the new contents to the temporary file */
4639  write_auto_conf_file(Tmpfd, AutoConfTmpFileName, head);
4640 
4641  /* Close before renaming; may be required on some platforms */
4642  close(Tmpfd);
4643  Tmpfd = -1;
4644 
4645  /*
4646  * As the rename is atomic operation, if any problem occurs after this
4647  * at worst it can lose the parameters set by last ALTER SYSTEM
4648  * command.
4649  */
4650  durable_rename(AutoConfTmpFileName, AutoConfFileName, ERROR);
4651  }
4652  PG_CATCH();
4653  {
4654  /* Close file first, else unlink might fail on some platforms */
4655  if (Tmpfd >= 0)
4656  close(Tmpfd);
4657 
4658  /* Unlink, but ignore any error */
4659  (void) unlink(AutoConfTmpFileName);
4660 
4661  PG_RE_THROW();
4662  }
4663  PG_END_TRY();
4664 
4665  FreeConfigVariables(head);
4666 
4667  LWLockRelease(AutoFileLock);
4668 }
4669 
4670 
4671 /*
4672  * Common code for DefineCustomXXXVariable subroutines: allocate the
4673  * new variable's config struct and fill in generic fields.
4674  */
4675 static struct config_generic *
4677  const char *short_desc,
4678  const char *long_desc,
4680  int flags,
4681  enum config_type type,
4682  size_t sz)
4683 {
4684  struct config_generic *gen;
4685 
4686  /*
4687  * Only allow custom PGC_POSTMASTER variables to be created during shared
4688  * library preload; any later than that, we can't ensure that the value
4689  * doesn't change after startup. This is a fatal elog if it happens; just
4690  * erroring out isn't safe because we don't know what the calling loadable
4691  * module might already have hooked into.
4692  */
4693  if (context == PGC_POSTMASTER &&
4695  elog(FATAL, "cannot create PGC_POSTMASTER variables after startup");
4696 
4697  /*
4698  * We can't support custom GUC_LIST_QUOTE variables, because the wrong
4699  * things would happen if such a variable were set or pg_dump'd when the
4700  * defining extension isn't loaded. Again, treat this as fatal because
4701  * the loadable module may be partly initialized already.
4702  */
4703  if (flags & GUC_LIST_QUOTE)
4704  elog(FATAL, "extensions cannot define GUC_LIST_QUOTE variables");
4705 
4706  /*
4707  * Before pljava commit 398f3b876ed402bdaec8bc804f29e2be95c75139
4708  * (2015-12-15), two of that module's PGC_USERSET variables facilitated
4709  * trivial escalation to superuser privileges. Restrict the variables to
4710  * protect sites that have yet to upgrade pljava.
4711  */
4712  if (context == PGC_USERSET &&
4713  (strcmp(name, "pljava.classpath") == 0 ||
4714  strcmp(name, "pljava.vmoptions") == 0))
4715  context = PGC_SUSET;
4716 
4717  gen = (struct config_generic *) guc_malloc(ERROR, sz);
4718  memset(gen, 0, sz);
4719 
4720  gen->name = guc_strdup(ERROR, name);
4721  gen->context = context;
4722  gen->group = CUSTOM_OPTIONS;
4723  gen->short_desc = short_desc;
4724  gen->long_desc = long_desc;
4725  gen->flags = flags;
4726  gen->vartype = type;
4727 
4728  return gen;
4729 }
4730 
4731 /*
4732  * Common code for DefineCustomXXXVariable subroutines: insert the new
4733  * variable into the GUC variable hash, replacing any placeholder.
4734  */
4735 static void
4737 {
4738  const char *name = variable->name;
4739  GUCHashEntry *hentry;
4740  struct config_string *pHolder;
4741 
4742  /* Check mapping between initial and default value */
4743  Assert(check_GUC_init(variable));
4744 
4745  /*
4746  * See if there's a placeholder by the same name.
4747  */
4748  hentry = (GUCHashEntry *) hash_search(guc_hashtab,
4749  &name,
4750  HASH_FIND,
4751  NULL);
4752  if (hentry == NULL)
4753  {
4754  /*
4755  * No placeholder to replace, so we can just add it ... but first,
4756  * make sure it's initialized to its default value.
4757  */
4760  return;
4761  }
4762 
4763  /*
4764  * This better be a placeholder
4765  */
4766  if ((hentry->gucvar->flags & GUC_CUSTOM_PLACEHOLDER) == 0)
4767  ereport(ERROR,
4768  (errcode(ERRCODE_INTERNAL_ERROR),
4769  errmsg("attempt to redefine parameter \"%s\"", name)));
4770 
4771  Assert(hentry->gucvar->vartype == PGC_STRING);
4772  pHolder = (struct config_string *) hentry->gucvar;
4773 
4774  /*
4775  * First, set the variable to its default value. We must do this even
4776  * though we intend to immediately apply a new value, since it's possible
4777  * that the new value is invalid.
4778  */
4780 
4781  /*
4782  * Replace the placeholder in the hash table. We aren't changing the name
4783  * (at least up to case-folding), so the hash value is unchanged.
4784  */
4785  hentry->gucname = name;
4786  hentry->gucvar = variable;
4787 
4788  /*
4789  * Remove the placeholder from any lists it's in, too.
4790  */
4791  RemoveGUCFromLists(&pHolder->gen);
4792 
4793  /*
4794  * Assign the string value(s) stored in the placeholder to the real
4795  * variable. Essentially, we need to duplicate all the active and stacked
4796  * values, but with appropriate validation and datatype adjustment.
4797  *
4798  * If an assignment fails, we report a WARNING and keep going. We don't
4799  * want to throw ERROR for bad values, because it'd bollix the add-on
4800  * module that's presumably halfway through getting loaded. In such cases
4801  * the default or previous state will become active instead.
4802  */
4803 
4804  /* First, apply the reset value if any */
4805  if (pHolder->reset_val)
4806  (void) set_config_option_ext(name, pHolder->reset_val,
4807  pHolder->gen.reset_scontext,
4808  pHolder->gen.reset_source,
4809  pHolder->gen.reset_srole,
4810  GUC_ACTION_SET, true, WARNING, false);
4811  /* That should not have resulted in stacking anything */
4812  Assert(variable->stack == NULL);
4813 
4814  /* Now, apply current and stacked values, in the order they were stacked */
4815  reapply_stacked_values(variable, pHolder, pHolder->gen.stack,
4816  *(pHolder->variable),
4817  pHolder->gen.scontext, pHolder->gen.source,
4818  pHolder->gen.srole);
4819 
4820  /* Also copy over any saved source-location information */
4821  if (pHolder->gen.sourcefile)
4823  pHolder->gen.sourceline);
4824 
4825  /*
4826  * Free up as much as we conveniently can of the placeholder structure.
4827  * (This neglects any stack items, so it's possible for some memory to be
4828  * leaked. Since this can only happen once per session per variable, it
4829  * doesn't seem worth spending much code on.)
4830  */
4831  set_string_field(pHolder, pHolder->variable, NULL);
4832  set_string_field(pHolder, &pHolder->reset_val, NULL);
4833 
4834  guc_free(pHolder);
4835 }
4836 
4837 /*
4838  * Recursive subroutine for define_custom_variable: reapply non-reset values
4839  *
4840  * We recurse so that the values are applied in the same order as originally.
4841  * At each recursion level, apply the upper-level value (passed in) in the
4842  * fashion implied by the stack entry.
4843  */
4844 static void
4846  struct config_string *pHolder,
4847  GucStack *stack,
4848  const char *curvalue,
4849  GucContext curscontext, GucSource cursource,
4850  Oid cursrole)
4851 {
4852  const char *name = variable->name;
4853  GucStack *oldvarstack = variable->stack;
4854 
4855  if (stack != NULL)
4856  {
4857  /* First, recurse, so that stack items are processed bottom to top */
4858  reapply_stacked_values(variable, pHolder, stack->prev,
4859  stack->prior.val.stringval,
4860  stack->scontext, stack->source, stack->srole);
4861 
4862  /* See how to apply the passed-in value */
4863  switch (stack->state)
4864  {
4865  case GUC_SAVE:
4866  (void) set_config_option_ext(name, curvalue,
4867  curscontext, cursource, cursrole,
4868  GUC_ACTION_SAVE, true,
4869  WARNING, false);
4870  break;
4871 
4872  case GUC_SET:
4873  (void) set_config_option_ext(name, curvalue,
4874  curscontext, cursource, cursrole,
4875  GUC_ACTION_SET, true,
4876  WARNING, false);
4877  break;
4878 
4879  case GUC_LOCAL:
4880  (void) set_config_option_ext(name, curvalue,
4881  curscontext, cursource, cursrole,
4882  GUC_ACTION_LOCAL, true,
4883  WARNING, false);
4884  break;
4885 
4886  case GUC_SET_LOCAL:
4887  /* first, apply the masked value as SET */
4889  stack->masked_scontext,
4890  PGC_S_SESSION,
4891  stack->masked_srole,
4892  GUC_ACTION_SET, true,
4893  WARNING, false);
4894  /* then apply the current value as LOCAL */
4895  (void) set_config_option_ext(name, curvalue,
4896  curscontext, cursource, cursrole,
4897  GUC_ACTION_LOCAL, true,
4898  WARNING, false);
4899  break;
4900  }
4901 
4902  /* If we successfully made a stack entry, adjust its nest level */
4903  if (variable->stack != oldvarstack)
4904  variable->stack->nest_level = stack->nest_level;
4905  }
4906  else
4907  {
4908  /*
4909  * We are at the end of the stack. If the active/previous value is
4910  * different from the reset value, it must represent a previously
4911  * committed session value. Apply it, and then drop the stack entry
4912  * that set_config_option will have created under the impression that
4913  * this is to be just a transactional assignment. (We leak the stack
4914  * entry.)
4915  */
4916  if (curvalue != pHolder->reset_val ||
4917  curscontext != pHolder->gen.reset_scontext ||
4918  cursource != pHolder->gen.reset_source ||
4919  cursrole != pHolder->gen.reset_srole)
4920  {
4921  (void) set_config_option_ext(name, curvalue,
4922  curscontext, cursource, cursrole,
4923  GUC_ACTION_SET, true, WARNING, false);
4924  if (variable->stack != NULL)
4925  {
4926  slist_delete(&guc_stack_list, &variable->stack_link);
4927  variable->stack = NULL;
4928  }
4929  }
4930  }
4931 }
4932 
4933 /*
4934  * Functions for extensions to call to define their custom GUC variables.
4935  */
4936 void
4938  const char *short_desc,
4939  const char *long_desc,
4940  bool *valueAddr,
4941  bool bootValue,
4942  GucContext context,
4943  int flags,
4947 {
4948  struct config_bool *var;
4949 
4950  var = (struct config_bool *)
4951  init_custom_variable(name, short_desc, long_desc, context, flags,
4952  PGC_BOOL, sizeof(struct config_bool));
4953  var->variable = valueAddr;
4954  var->boot_val = bootValue;
4955  var->reset_val = bootValue;
4956  var->check_hook = check_hook;
4957  var->assign_hook = assign_hook;
4958  var->show_hook = show_hook;
4959  define_custom_variable(&var->gen);
4960 }
4961 
4962 void
4964  const char *short_desc,
4965  const char *long_desc,
4966  int *valueAddr,
4967  int bootValue,
4968  int minValue,
4969  int maxValue,
4970  GucContext context,
4971  int flags,
4975 {
4976  struct config_int *var;
4977 
4978  var = (struct config_int *)
4979  init_custom_variable(name, short_desc, long_desc, context, flags,
4980  PGC_INT, sizeof(struct config_int));
4981  var->variable = valueAddr;
4982  var->boot_val = bootValue;
4983  var->reset_val = bootValue;
4984  var->min = minValue;
4985  var->max = maxValue;
4986  var->check_hook = check_hook;
4987  var->assign_hook = assign_hook;
4988  var->show_hook = show_hook;
4989  define_custom_variable(&var->gen);
4990 }
4991 
4992 void
4994  const char *short_desc,
4995  const char *long_desc,
4996  double *valueAddr,
4997  double bootValue,
4998  double minValue,
4999  double maxValue,
5000  GucContext context,
5001  int flags,
5005 {
5006  struct config_real *var;
5007 
5008  var = (struct config_real *)
5009  init_custom_variable(name, short_desc, long_desc, context, flags,
5010  PGC_REAL, sizeof(struct config_real));
5011  var->variable = valueAddr;
5012  var->boot_val = bootValue;
5013  var->reset_val = bootValue;
5014  var->min = minValue;
5015  var->max = maxValue;
5016  var->check_hook = check_hook;
5017  var->assign_hook = assign_hook;
5018  var->show_hook = show_hook;
5019  define_custom_variable(&var->gen);
5020 }
5021 
5022 void
5024  const char *short_desc,
5025  const char *long_desc,
5026  char **valueAddr,
5027  const char *bootValue,
5028  GucContext context,
5029  int flags,
5033 {
5034  struct config_string *var;
5035 
5036  var = (struct config_string *)
5037  init_custom_variable(name, short_desc, long_desc, context, flags,
5038  PGC_STRING, sizeof(struct config_string));
5039  var->variable = valueAddr;
5040  var->boot_val = bootValue;
5041  var->check_hook = check_hook;
5042  var->assign_hook = assign_hook;
5043  var->show_hook = show_hook;
5044  define_custom_variable(&var->gen);
5045 }
5046 
5047 void
5049  const char *short_desc,
5050  const char *long_desc,
5051  int *valueAddr,
5052  int bootValue,
5053  const struct config_enum_entry *options,
5054  GucContext context,
5055  int flags,
5059 {
5060  struct config_enum *var;
5061 
5062  var = (struct config_enum *)
5063  init_custom_variable(name, short_desc, long_desc, context, flags,
5064  PGC_ENUM, sizeof(struct config_enum));
5065  var->variable = valueAddr;
5066  var->boot_val = bootValue;
5067  var->reset_val = bootValue;
5068  var->options = options;
5069  var->check_hook = check_hook;
5070  var->assign_hook = assign_hook;
5071  var->show_hook = show_hook;
5072  define_custom_variable(&var->gen);
5073 }
5074 
5075 /*
5076  * Mark the given GUC prefix as "reserved".
5077  *
5078  * This deletes any existing placeholders matching the prefix,
5079  * and then prevents new ones from being created.
5080  * Extensions should call this after they've defined all of their custom
5081  * GUCs, to help catch misspelled config-file entries.
5082  */
5083 void
5084 MarkGUCPrefixReserved(const char *className)
5085 {
5086  int classLen = strlen(className);
5088  GUCHashEntry *hentry;
5089  MemoryContext oldcontext;
5090 
5091  /*
5092  * Check for existing placeholders. We must actually remove invalid
5093  * placeholders, else future parallel worker startups will fail. (We
5094  * don't bother trying to free associated memory, since this shouldn't
5095  * happen often.)
5096  */
5098  while ((hentry = (GUCHashEntry *) hash_seq_search(&status)) != NULL)
5099  {
5100  struct config_generic *var = hentry->gucvar;
5101 
5102  if ((var->flags & GUC_CUSTOM_PLACEHOLDER) != 0 &&
5103  strncmp(className, var->name, classLen) == 0 &&
5104  var->name[classLen] == GUC_QUALIFIER_SEPARATOR)
5105  {
5106  ereport(WARNING,
5107  (errcode(ERRCODE_INVALID_NAME),
5108  errmsg("invalid configuration parameter name \"%s\", removing it",
5109  var->name),
5110  errdetail("\"%s\" is now a reserved prefix.",
5111  className)));
5112  /* Remove it from the hash table */
5114  &var->name,
5115  HASH_REMOVE,
5116  NULL);
5117  /* Remove it from any lists it's in, too */
5118  RemoveGUCFromLists(var);
5119  }
5120  }
5121 
5122  /* And remember the name so we can prevent future mistakes. */
5125  MemoryContextSwitchTo(oldcontext);
5126 }
5127 
5128 
5129 /*
5130  * Return an array of modified GUC options to show in EXPLAIN.
5131  *
5132  * We only report options related to query planning (marked with GUC_EXPLAIN),
5133  * with values different from their built-in defaults.
5134  */
5135 struct config_generic **
5137 {
5138  struct config_generic **result;
5139  dlist_iter iter;
5140 
5141  *num = 0;
5142 
5143  /*
5144  * While only a fraction of all the GUC variables are marked GUC_EXPLAIN,
5145  * it doesn't seem worth dynamically resizing this array.
5146  */
5147  result = palloc(sizeof(struct config_generic *) * hash_get_num_entries(guc_hashtab));
5148 
5149  /* We need only consider GUCs with source not PGC_S_DEFAULT */
5151  {
5152  struct config_generic *conf = dlist_container(struct config_generic,
5153  nondef_link, iter.cur);
5154  bool modified;
5155 
5156  /* return only parameters marked for inclusion in explain */
5157  if (!(conf->flags & GUC_EXPLAIN))
5158  continue;
5159 
5160  /* return only options visible to the current user */
5161  if (!ConfigOptionIsVisible(conf))
5162  continue;
5163 
5164  /* return only options that are different from their boot values */
5165  modified = false;
5166 
5167  switch (conf->vartype)
5168  {
5169  case PGC_BOOL:
5170  {
5171  struct config_bool *lconf = (struct config_bool *) conf;
5172 
5173  modified = (lconf->boot_val != *(lconf->variable));
5174  }
5175  break;
5176 
5177  case PGC_INT:
5178  {
5179  struct config_int *lconf = (struct config_int *) conf;
5180 
5181  modified = (lconf->boot_val != *(lconf->variable));
5182  }
5183  break;
5184 
5185  case PGC_REAL:
5186  {
5187  struct config_real *lconf = (struct config_real *) conf;
5188 
5189  modified = (lconf->boot_val != *(lconf->variable));
5190  }
5191  break;
5192 
5193  case PGC_STRING:
5194  {
5195  struct config_string *lconf = (struct config_string *) conf;
5196 
5197  modified = (strcmp(lconf->boot_val, *(lconf->variable)) != 0);
5198  }
5199  break;
5200 
5201  case PGC_ENUM:
5202  {
5203  struct config_enum *lconf = (struct config_enum *) conf;
5204 
5205  modified = (lconf->boot_val != *(lconf->variable));
5206  }
5207  break;
5208 
5209  default:
5210  elog(ERROR, "unexpected GUC type: %d", conf->vartype);
5211  }
5212 
5213  if (!modified)
5214  continue;
5215 
5216  /* OK, report it */
5217  result[*num] = conf;
5218  *num = *num + 1;
5219  }
5220 
5221  return result;
5222 }
5223 
5224 /*
5225  * Return GUC variable value by name; optionally return canonical form of
5226  * name. If the GUC is unset, then throw an error unless missing_ok is true,
5227  * in which case return NULL. Return value is palloc'd (but *varname isn't).
5228  */
5229 char *
5230 GetConfigOptionByName(const char *name, const char **varname, bool missing_ok)
5231 {
5232  struct config_generic *record;
5233 
5234  record = find_option(name, false, missing_ok, ERROR);
5235  if (record == NULL)
5236  {
5237  if (varname)
5238  *varname = NULL;
5239  return NULL;
5240  }
5241 
5242  if (!ConfigOptionIsVisible(record))
5243  ereport(ERROR,
5244  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
5245  errmsg("must be superuser or have privileges of pg_read_all_settings to examine \"%s\"",
5246  name)));
5247 
5248  if (varname)
5249  *varname = record->name;
5250 
5251  return ShowGUCOption(record, true);
5252 }
5253 
5254 /*
5255  * ShowGUCOption: get string value of variable
5256  *
5257  * We express a numeric value in appropriate units if it has units and
5258  * use_units is true; else you just get the raw number.
5259  * The result string is palloc'd.
5260  */
5261 char *
5262 ShowGUCOption(struct config_generic *record, bool use_units)
5263 {
5264  char buffer[256];
5265  const char *val;
5266 
5267  switch (record->vartype)
5268  {
5269  case PGC_BOOL:
5270  {
5271  struct config_bool *conf = (struct config_bool *) record;
5272 
5273  if (conf->show_hook)
5274  val = conf->show_hook();
5275  else
5276  val = *conf->variable ? "on" : "off";
5277  }
5278  break;
5279 
5280  case PGC_INT:
5281  {
5282  struct config_int *conf = (struct config_int *) record;
5283 
5284  if (conf->show_hook)
5285  val = conf->show_hook();
5286  else
5287  {
5288  /*
5289  * Use int64 arithmetic to avoid overflows in units
5290  * conversion.
5291  */
5292  int64 result = *conf->variable;
5293  const char *unit;
5294 
5295  if (use_units && result > 0 && (record->flags & GUC_UNIT))
5297  record->flags & GUC_UNIT,
5298  &result, &unit);
5299  else
5300  unit = "";
5301 
5302  snprintf(buffer, sizeof(buffer), INT64_FORMAT "%s",
5303  result, unit);
5304  val = buffer;
5305  }
5306  }
5307  break;
5308 
5309  case PGC_REAL:
5310  {
5311  struct config_real *conf = (struct config_real *) record;
5312 
5313  if (conf->show_hook)
5314  val = conf->show_hook();
5315  else
5316  {
5317  double result = *conf->variable;
5318  const char *unit;
5319 
5320  if (use_units && result > 0 && (record->flags & GUC_UNIT))
5322  record->flags & GUC_UNIT,
5323  &result, &unit);
5324  else
5325  unit = "";
5326 
5327  snprintf(buffer, sizeof(buffer), "%g%s",
5328  result, unit);
5329  val = buffer;
5330  }
5331  }
5332  break;
5333 
5334  case PGC_STRING:
5335  {
5336  struct config_string *conf = (struct config_string *) record;
5337 
5338  if (conf->show_hook)
5339  val = conf->show_hook();
5340  else if (*conf->variable && **conf->variable)
5341  val = *conf->variable;
5342  else
5343  val = "";
5344  }
5345  break;
5346 
5347  case PGC_ENUM:
5348  {
5349  struct config_enum *conf = (struct config_enum *) record;
5350 
5351  if (conf->show_hook)
5352  val = conf->show_hook();
5353  else
5354  val = config_enum_lookup_by_value(conf, *conf->variable);
5355  }
5356  break;
5357 
5358  default:
5359  /* just to keep compiler quiet */
5360  val = "???";
5361  break;
5362  }
5363 
5364  return pstrdup(val);
5365 }
5366 
5367 
5368 #ifdef EXEC_BACKEND
5369 
5370 /*
5371  * These routines dump out all non-default GUC options into a binary
5372  * file that is read by all exec'ed backends. The format is:
5373  *
5374  * variable name, string, null terminated
5375  * variable value, string, null terminated
5376  * variable sourcefile, string, null terminated (empty if none)
5377  * variable sourceline, integer
5378  * variable source, integer
5379  * variable scontext, integer
5380 * variable srole, OID
5381  */
5382 static void
5383 write_one_nondefault_variable(FILE *fp, struct config_generic *gconf)
5384 {
5385  Assert(gconf->source != PGC_S_DEFAULT);
5386 
5387  fprintf(fp, "%s", gconf->name);
5388  fputc(0, fp);