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