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