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