1 /*--------------------------------------------------------------------
2  * guc.c
3  *
4  * Support for grand unified configuration scheme, including SET
5  * command, configuration file, and command line options.
6  * See src/backend/utils/misc/README for more information.
7  *
8  *
9  * Copyright (c) 2000-2016, PostgreSQL Global Development Group
10  * Written by Peter Eisentraut <peter_e@gmx.net>.
11  *
12  * IDENTIFICATION
13  *	  src/backend/utils/misc/guc.c
14  *
15  *--------------------------------------------------------------------
16  */
17 #include "postgres.h"
18 
19 #include <stdbool.h>
20 #include <ctype.h>
21 #include <float.h>
22 #include <math.h>
23 #include <limits.h>
24 #include <unistd.h>
25 #include <sys/stat.h>
26 #ifdef HAVE_SYSLOG
27 #include <syslog.h>
28 #endif
29 
30 #include "access/commit_ts.h"
31 #include "access/gin.h"
32 #include "access/transam.h"
33 #include "access/twophase.h"
34 #include "access/xact.h"
35 #include "catalog/namespace.h"
36 #include "commands/async.h"
37 #include "commands/prepare.h"
38 #include "commands/vacuum.h"
39 #include "commands/variable.h"
40 #include "commands/trigger.h"
41 #include "funcapi.h"
42 #include "libpq/auth.h"
43 #include "libpq/be-fsstubs.h"
44 #include "libpq/libpq.h"
45 #include "libpq/pqformat.h"
46 #include "miscadmin.h"
47 #include "optimizer/cost.h"
48 #include "optimizer/geqo.h"
49 #include "optimizer/paths.h"
50 #include "optimizer/planmain.h"
51 #include "parser/parse_expr.h"
52 #include "parser/parse_type.h"
53 #include "parser/parser.h"
54 #include "parser/scansup.h"
55 #include "pgstat.h"
56 #include "postmaster/autovacuum.h"
57 #include "postmaster/bgworker.h"
58 #include "postmaster/bgwriter.h"
59 #include "postmaster/postmaster.h"
60 #include "postmaster/syslogger.h"
61 #include "postmaster/walwriter.h"
62 #include "replication/slot.h"
63 #include "replication/syncrep.h"
64 #include "replication/walreceiver.h"
65 #include "replication/walsender.h"
66 #include "storage/bufmgr.h"
67 #include "storage/dsm_impl.h"
68 #include "storage/standby.h"
69 #include "storage/fd.h"
70 #include "storage/pg_shmem.h"
71 #include "storage/proc.h"
72 #include "storage/predicate.h"
73 #include "tcop/tcopprot.h"
74 #include "tsearch/ts_cache.h"
75 #include "utils/builtins.h"
76 #include "utils/bytea.h"
77 #include "utils/guc_tables.h"
78 #include "utils/memutils.h"
79 #include "utils/pg_locale.h"
80 #include "utils/plancache.h"
81 #include "utils/portal.h"
82 #include "utils/ps_status.h"
83 #include "utils/rls.h"
84 #include "utils/snapmgr.h"
85 #include "utils/tzparser.h"
86 #include "utils/xml.h"
87 
88 #ifndef PG_KRB_SRVTAB
89 #define PG_KRB_SRVTAB ""
90 #endif
91 
92 #define CONFIG_FILENAME "postgresql.conf"
93 #define HBA_FILENAME	"pg_hba.conf"
94 #define IDENT_FILENAME	"pg_ident.conf"
95 
96 #ifdef EXEC_BACKEND
97 #define CONFIG_EXEC_PARAMS "global/config_exec_params"
98 #define CONFIG_EXEC_PARAMS_NEW "global/config_exec_params.new"
99 #endif
100 
101 /*
102  * Precision with which REAL type guc values are to be printed for GUC
103  * serialization.
104  */
105 #define REALTYPE_PRECISION 17
106 
107 /* XXX these should appear in other modules' header files */
108 extern bool Log_disconnections;
109 extern int	CommitDelay;
110 extern int	CommitSiblings;
111 extern char *default_tablespace;
112 extern char *temp_tablespaces;
113 extern bool ignore_checksum_failure;
114 extern bool synchronize_seqscans;
115 
116 #ifdef TRACE_SYNCSCAN
117 extern bool trace_syncscan;
118 #endif
119 #ifdef DEBUG_BOUNDED_SORT
120 extern bool optimize_bounded_sort;
121 #endif
122 
123 static int	GUC_check_errcode_value;
124 
125 /* global variables for check hook support */
126 char	   *GUC_check_errmsg_string;
127 char	   *GUC_check_errdetail_string;
128 char	   *GUC_check_errhint_string;
129 
130 static void do_serialize(char **destptr, Size *maxbytes, const char *fmt,...) pg_attribute_printf(3, 4);
131 
132 static void set_config_sourcefile(const char *name, char *sourcefile,
133 					  int sourceline);
134 static bool call_bool_check_hook(struct config_bool * conf, bool *newval,
135 					 void **extra, GucSource source, int elevel);
136 static bool call_int_check_hook(struct config_int * conf, int *newval,
137 					void **extra, GucSource source, int elevel);
138 static bool call_real_check_hook(struct config_real * conf, double *newval,
139 					 void **extra, GucSource source, int elevel);
140 static bool call_string_check_hook(struct config_string * conf, char **newval,
141 					   void **extra, GucSource source, int elevel);
142 static bool call_enum_check_hook(struct config_enum * conf, int *newval,
143 					 void **extra, GucSource source, int elevel);
144 
145 static bool check_log_destination(char **newval, void **extra, GucSource source);
146 static void assign_log_destination(const char *newval, void *extra);
147 
148 #ifdef HAVE_SYSLOG
149 static int	syslog_facility = LOG_LOCAL0;
150 #else
151 static int	syslog_facility = 0;
152 #endif
153 
154 static void assign_syslog_facility(int newval, void *extra);
155 static void assign_syslog_ident(const char *newval, void *extra);
156 static void assign_session_replication_role(int newval, void *extra);
157 static bool check_client_min_messages(int *newval, void **extra, GucSource source);
158 static bool check_temp_buffers(int *newval, void **extra, GucSource source);
159 static bool check_bonjour(bool *newval, void **extra, GucSource source);
160 static bool check_ssl(bool *newval, void **extra, GucSource source);
161 static bool check_stage_log_stats(bool *newval, void **extra, GucSource source);
162 static bool check_log_stats(bool *newval, void **extra, GucSource source);
163 static bool check_canonical_path(char **newval, void **extra, GucSource source);
164 static bool check_timezone_abbreviations(char **newval, void **extra, GucSource source);
165 static void assign_timezone_abbreviations(const char *newval, void *extra);
166 static void pg_timezone_abbrev_initialize(void);
167 static const char *show_archive_command(void);
168 static void assign_tcp_keepalives_idle(int newval, void *extra);
169 static void assign_tcp_keepalives_interval(int newval, void *extra);
170 static void assign_tcp_keepalives_count(int newval, void *extra);
171 static const char *show_tcp_keepalives_idle(void);
172 static const char *show_tcp_keepalives_interval(void);
173 static const char *show_tcp_keepalives_count(void);
174 static bool check_maxconnections(int *newval, void **extra, GucSource source);
175 static bool check_max_worker_processes(int *newval, void **extra, GucSource source);
176 static bool check_autovacuum_max_workers(int *newval, void **extra, GucSource source);
177 static bool check_autovacuum_work_mem(int *newval, void **extra, GucSource source);
178 static bool check_effective_io_concurrency(int *newval, void **extra, GucSource source);
179 static void assign_effective_io_concurrency(int newval, void *extra);
180 static void assign_pgstat_temp_directory(const char *newval, void *extra);
181 static bool check_application_name(char **newval, void **extra, GucSource source);
182 static void assign_application_name(const char *newval, void *extra);
183 static bool check_cluster_name(char **newval, void **extra, GucSource source);
184 static const char *show_unix_socket_permissions(void);
185 static const char *show_log_file_mode(void);
186 
187 /* Private functions in guc-file.l that need to be called from guc.c */
188 static ConfigVariable *ProcessConfigFileInternal(GucContext context,
189 						  bool applySettings, int elevel);
190 
191 
192 /*
193  * Options for enum values defined in this module.
194  *
195  * NOTE! Option values may not contain double quotes!
196  */
197 
198 static const struct config_enum_entry bytea_output_options[] = {
199 	{"escape", BYTEA_OUTPUT_ESCAPE, false},
200 	{"hex", BYTEA_OUTPUT_HEX, false},
201 	{NULL, 0, false}
202 };
203 
204 /*
205  * We have different sets for client and server message level options because
206  * they sort slightly different (see "log" level)
207  */
208 static const struct config_enum_entry client_message_level_options[] = {
209 	{"debug", DEBUG2, true},
210 	{"debug5", DEBUG5, false},
211 	{"debug4", DEBUG4, false},
212 	{"debug3", DEBUG3, false},
213 	{"debug2", DEBUG2, false},
214 	{"debug1", DEBUG1, false},
215 	{"log", LOG, false},
216 	{"info", INFO, true},
217 	{"notice", NOTICE, false},
218 	{"warning", WARNING, false},
219 	{"error", ERROR, false},
220 	{"fatal", FATAL, true},
221 	{"panic", PANIC, true},
222 	{NULL, 0, false}
223 };
224 
225 static const struct config_enum_entry server_message_level_options[] = {
226 	{"debug", DEBUG2, true},
227 	{"debug5", DEBUG5, false},
228 	{"debug4", DEBUG4, false},
229 	{"debug3", DEBUG3, false},
230 	{"debug2", DEBUG2, false},
231 	{"debug1", DEBUG1, false},
232 	{"info", INFO, false},
233 	{"notice", NOTICE, false},
234 	{"warning", WARNING, false},
235 	{"error", ERROR, false},
236 	{"log", LOG, false},
237 	{"fatal", FATAL, false},
238 	{"panic", PANIC, false},
239 	{NULL, 0, false}
240 };
241 
242 static const struct config_enum_entry intervalstyle_options[] = {
243 	{"postgres", INTSTYLE_POSTGRES, false},
244 	{"postgres_verbose", INTSTYLE_POSTGRES_VERBOSE, false},
245 	{"sql_standard", INTSTYLE_SQL_STANDARD, false},
246 	{"iso_8601", INTSTYLE_ISO_8601, false},
247 	{NULL, 0, false}
248 };
249 
250 static const struct config_enum_entry log_error_verbosity_options[] = {
251 	{"terse", PGERROR_TERSE, false},
252 	{"default", PGERROR_DEFAULT, false},
253 	{"verbose", PGERROR_VERBOSE, false},
254 	{NULL, 0, false}
255 };
256 
257 static const struct config_enum_entry log_statement_options[] = {
258 	{"none", LOGSTMT_NONE, false},
259 	{"ddl", LOGSTMT_DDL, false},
260 	{"mod", LOGSTMT_MOD, false},
261 	{"all", LOGSTMT_ALL, false},
262 	{NULL, 0, false}
263 };
264 
265 static const struct config_enum_entry isolation_level_options[] = {
266 	{"serializable", XACT_SERIALIZABLE, false},
267 	{"repeatable read", XACT_REPEATABLE_READ, false},
268 	{"read committed", XACT_READ_COMMITTED, false},
269 	{"read uncommitted", XACT_READ_UNCOMMITTED, false},
270 	{NULL, 0}
271 };
272 
273 static const struct config_enum_entry session_replication_role_options[] = {
274 	{"origin", SESSION_REPLICATION_ROLE_ORIGIN, false},
275 	{"replica", SESSION_REPLICATION_ROLE_REPLICA, false},
276 	{"local", SESSION_REPLICATION_ROLE_LOCAL, false},
277 	{NULL, 0, false}
278 };
279 
280 static const struct config_enum_entry syslog_facility_options[] = {
281 #ifdef HAVE_SYSLOG
282 	{"local0", LOG_LOCAL0, false},
283 	{"local1", LOG_LOCAL1, false},
284 	{"local2", LOG_LOCAL2, false},
285 	{"local3", LOG_LOCAL3, false},
286 	{"local4", LOG_LOCAL4, false},
287 	{"local5", LOG_LOCAL5, false},
288 	{"local6", LOG_LOCAL6, false},
289 	{"local7", LOG_LOCAL7, false},
290 #else
291 	{"none", 0, false},
292 #endif
293 	{NULL, 0}
294 };
295 
296 static const struct config_enum_entry track_function_options[] = {
297 	{"none", TRACK_FUNC_OFF, false},
298 	{"pl", TRACK_FUNC_PL, false},
299 	{"all", TRACK_FUNC_ALL, false},
300 	{NULL, 0, false}
301 };
302 
303 static const struct config_enum_entry xmlbinary_options[] = {
304 	{"base64", XMLBINARY_BASE64, false},
305 	{"hex", XMLBINARY_HEX, false},
306 	{NULL, 0, false}
307 };
308 
309 static const struct config_enum_entry xmloption_options[] = {
310 	{"content", XMLOPTION_CONTENT, false},
311 	{"document", XMLOPTION_DOCUMENT, false},
312 	{NULL, 0, false}
313 };
314 
315 /*
316  * Although only "on", "off", and "safe_encoding" are documented, we
317  * accept all the likely variants of "on" and "off".
318  */
319 static const struct config_enum_entry backslash_quote_options[] = {
320 	{"safe_encoding", BACKSLASH_QUOTE_SAFE_ENCODING, false},
321 	{"on", BACKSLASH_QUOTE_ON, false},
322 	{"off", BACKSLASH_QUOTE_OFF, false},
323 	{"true", BACKSLASH_QUOTE_ON, true},
324 	{"false", BACKSLASH_QUOTE_OFF, true},
325 	{"yes", BACKSLASH_QUOTE_ON, true},
326 	{"no", BACKSLASH_QUOTE_OFF, true},
327 	{"1", BACKSLASH_QUOTE_ON, true},
328 	{"0", BACKSLASH_QUOTE_OFF, true},
329 	{NULL, 0, false}
330 };
331 
332 /*
333  * Although only "on", "off", and "partition" are documented, we
334  * accept all the likely variants of "on" and "off".
335  */
336 static const struct config_enum_entry constraint_exclusion_options[] = {
337 	{"partition", CONSTRAINT_EXCLUSION_PARTITION, false},
338 	{"on", CONSTRAINT_EXCLUSION_ON, false},
339 	{"off", CONSTRAINT_EXCLUSION_OFF, false},
340 	{"true", CONSTRAINT_EXCLUSION_ON, true},
341 	{"false", CONSTRAINT_EXCLUSION_OFF, true},
342 	{"yes", CONSTRAINT_EXCLUSION_ON, true},
343 	{"no", CONSTRAINT_EXCLUSION_OFF, true},
344 	{"1", CONSTRAINT_EXCLUSION_ON, true},
345 	{"0", CONSTRAINT_EXCLUSION_OFF, true},
346 	{NULL, 0, false}
347 };
348 
349 /*
350  * Although only "on", "off", "remote_apply", "remote_write", and "local" are
351  * documented, we accept all the likely variants of "on" and "off".
352  */
353 static const struct config_enum_entry synchronous_commit_options[] = {
354 	{"local", SYNCHRONOUS_COMMIT_LOCAL_FLUSH, false},
355 	{"remote_write", SYNCHRONOUS_COMMIT_REMOTE_WRITE, false},
356 	{"remote_apply", SYNCHRONOUS_COMMIT_REMOTE_APPLY, false},
357 	{"on", SYNCHRONOUS_COMMIT_ON, false},
358 	{"off", SYNCHRONOUS_COMMIT_OFF, false},
359 	{"true", SYNCHRONOUS_COMMIT_ON, true},
360 	{"false", SYNCHRONOUS_COMMIT_OFF, true},
361 	{"yes", SYNCHRONOUS_COMMIT_ON, true},
362 	{"no", SYNCHRONOUS_COMMIT_OFF, true},
363 	{"1", SYNCHRONOUS_COMMIT_ON, true},
364 	{"0", SYNCHRONOUS_COMMIT_OFF, true},
365 	{NULL, 0, false}
366 };
367 
368 /*
369  * Although only "on", "off", "try" are documented, we accept all the likely
370  * variants of "on" and "off".
371  */
372 static const struct config_enum_entry huge_pages_options[] = {
373 	{"off", HUGE_PAGES_OFF, false},
374 	{"on", HUGE_PAGES_ON, false},
375 	{"try", HUGE_PAGES_TRY, false},
376 	{"true", HUGE_PAGES_ON, true},
377 	{"false", HUGE_PAGES_OFF, true},
378 	{"yes", HUGE_PAGES_ON, true},
379 	{"no", HUGE_PAGES_OFF, true},
380 	{"1", HUGE_PAGES_ON, true},
381 	{"0", HUGE_PAGES_OFF, true},
382 	{NULL, 0, false}
383 };
384 
385 static const struct config_enum_entry force_parallel_mode_options[] = {
386 	{"off", FORCE_PARALLEL_OFF, false},
387 	{"on", FORCE_PARALLEL_ON, false},
388 	{"regress", FORCE_PARALLEL_REGRESS, false},
389 	{"true", FORCE_PARALLEL_ON, true},
390 	{"false", FORCE_PARALLEL_OFF, true},
391 	{"yes", FORCE_PARALLEL_ON, true},
392 	{"no", FORCE_PARALLEL_OFF, true},
393 	{"1", FORCE_PARALLEL_ON, true},
394 	{"0", FORCE_PARALLEL_OFF, true},
395 	{NULL, 0, false}
396 };
397 
398 /*
399  * Options for enum values stored in other modules
400  */
401 extern const struct config_enum_entry wal_level_options[];
402 extern const struct config_enum_entry archive_mode_options[];
403 extern const struct config_enum_entry sync_method_options[];
404 extern const struct config_enum_entry dynamic_shared_memory_options[];
405 
406 /*
407  * GUC option variables that are exported from this module
408  */
409 bool		log_duration = false;
410 bool		Debug_print_plan = false;
411 bool		Debug_print_parse = false;
412 bool		Debug_print_rewritten = false;
413 bool		Debug_pretty_print = true;
414 
415 bool		log_parser_stats = false;
416 bool		log_planner_stats = false;
417 bool		log_executor_stats = false;
418 bool		log_statement_stats = false;		/* this is sort of all three
419 												 * above together */
420 bool		log_btree_build_stats = false;
421 char	   *event_source;
422 
423 bool		row_security;
424 bool		check_function_bodies = true;
425 bool		default_with_oids = false;
426 bool		SQL_inheritance = true;
427 
428 bool		Password_encryption = true;
429 bool		session_auth_is_superuser;
430 
431 int			log_min_error_statement = ERROR;
432 int			log_min_messages = WARNING;
433 int			client_min_messages = NOTICE;
434 int			log_min_duration_statement = -1;
435 int			log_temp_files = -1;
436 int			trace_recovery_messages = LOG;
437 
438 int			temp_file_limit = -1;
439 
440 int			num_temp_buffers = 1024;
441 
442 char	   *cluster_name = "";
443 char	   *ConfigFileName;
444 char	   *HbaFileName;
445 char	   *IdentFileName;
446 char	   *external_pid_file;
447 
448 char	   *pgstat_temp_directory;
449 
450 char	   *application_name;
451 
452 int			tcp_keepalives_idle;
453 int			tcp_keepalives_interval;
454 int			tcp_keepalives_count;
455 
456 /*
457  * SSL renegotiation was been removed in PostgreSQL 9.5, but we tolerate it
458  * being set to zero (meaning never renegotiate) for backward compatibility.
459  * This avoids breaking compatibility with clients that have never supported
460  * renegotiation and therefore always try to zero it.
461  */
462 int			ssl_renegotiation_limit;
463 
464 /*
465  * This really belongs in pg_shmem.c, but is defined here so that it doesn't
466  * need to be duplicated in all the different implementations of pg_shmem.c.
467  */
468 int			huge_pages;
469 
470 /*
471  * These variables are all dummies that don't do anything, except in some
472  * cases provide the value for SHOW to display.  The real state is elsewhere
473  * and is kept in sync by assign_hooks.
474  */
475 static char *syslog_ident_str;
476 static double phony_random_seed;
477 static char *client_encoding_string;
478 static char *datestyle_string;
479 static char *locale_collate;
480 static char *locale_ctype;
481 static char *server_encoding_string;
482 static char *server_version_string;
483 static int	server_version_num;
484 static char *timezone_string;
485 static char *log_timezone_string;
486 static char *timezone_abbreviations_string;
487 static char *XactIsoLevel_string;
488 static char *data_directory;
489 static char *session_authorization_string;
490 static int	max_function_args;
491 static int	max_index_keys;
492 static int	max_identifier_length;
493 static int	block_size;
494 static int	segment_size;
495 static int	wal_block_size;
496 static bool data_checksums;
497 static int	wal_segment_size;
498 static bool integer_datetimes;
499 static bool assert_enabled;
500 
501 /* should be static, but commands/variable.c needs to get at this */
502 char	   *role_string;
503 
504 
505 /*
506  * Displayable names for context types (enum GucContext)
507  *
508  * Note: these strings are deliberately not localized.
509  */
510 const char *const GucContext_Names[] =
511 {
512 	 /* PGC_INTERNAL */ "internal",
513 	 /* PGC_POSTMASTER */ "postmaster",
514 	 /* PGC_SIGHUP */ "sighup",
515 	 /* PGC_SU_BACKEND */ "superuser-backend",
516 	 /* PGC_BACKEND */ "backend",
517 	 /* PGC_SUSET */ "superuser",
518 	 /* PGC_USERSET */ "user"
519 };
520 
521 /*
522  * Displayable names for source types (enum GucSource)
523  *
524  * Note: these strings are deliberately not localized.
525  */
526 const char *const GucSource_Names[] =
527 {
528 	 /* PGC_S_DEFAULT */ "default",
529 	 /* PGC_S_DYNAMIC_DEFAULT */ "default",
530 	 /* PGC_S_ENV_VAR */ "environment variable",
531 	 /* PGC_S_FILE */ "configuration file",
532 	 /* PGC_S_ARGV */ "command line",
533 	 /* PGC_S_GLOBAL */ "global",
534 	 /* PGC_S_DATABASE */ "database",
535 	 /* PGC_S_USER */ "user",
536 	 /* PGC_S_DATABASE_USER */ "database user",
537 	 /* PGC_S_CLIENT */ "client",
538 	 /* PGC_S_OVERRIDE */ "override",
539 	 /* PGC_S_INTERACTIVE */ "interactive",
540 	 /* PGC_S_TEST */ "test",
541 	 /* PGC_S_SESSION */ "session"
542 };
543 
544 /*
545  * Displayable names for the groupings defined in enum config_group
546  */
547 const char *const config_group_names[] =
548 {
549 	/* UNGROUPED */
550 	gettext_noop("Ungrouped"),
551 	/* FILE_LOCATIONS */
552 	gettext_noop("File Locations"),
553 	/* CONN_AUTH */
554 	gettext_noop("Connections and Authentication"),
555 	/* CONN_AUTH_SETTINGS */
556 	gettext_noop("Connections and Authentication / Connection Settings"),
557 	/* CONN_AUTH_SECURITY */
558 	gettext_noop("Connections and Authentication / Security and Authentication"),
559 	/* RESOURCES */
560 	gettext_noop("Resource Usage"),
561 	/* RESOURCES_MEM */
562 	gettext_noop("Resource Usage / Memory"),
563 	/* RESOURCES_DISK */
564 	gettext_noop("Resource Usage / Disk"),
565 	/* RESOURCES_KERNEL */
566 	gettext_noop("Resource Usage / Kernel Resources"),
567 	/* RESOURCES_VACUUM_DELAY */
568 	gettext_noop("Resource Usage / Cost-Based Vacuum Delay"),
569 	/* RESOURCES_BGWRITER */
570 	gettext_noop("Resource Usage / Background Writer"),
571 	/* RESOURCES_ASYNCHRONOUS */
572 	gettext_noop("Resource Usage / Asynchronous Behavior"),
573 	/* WAL */
574 	gettext_noop("Write-Ahead Log"),
575 	/* WAL_SETTINGS */
576 	gettext_noop("Write-Ahead Log / Settings"),
577 	/* WAL_CHECKPOINTS */
578 	gettext_noop("Write-Ahead Log / Checkpoints"),
579 	/* WAL_ARCHIVING */
580 	gettext_noop("Write-Ahead Log / Archiving"),
581 	/* REPLICATION */
582 	gettext_noop("Replication"),
583 	/* REPLICATION_SENDING */
584 	gettext_noop("Replication / Sending Servers"),
585 	/* REPLICATION_MASTER */
586 	gettext_noop("Replication / Master Server"),
587 	/* REPLICATION_STANDBY */
588 	gettext_noop("Replication / Standby Servers"),
589 	/* QUERY_TUNING */
590 	gettext_noop("Query Tuning"),
591 	/* QUERY_TUNING_METHOD */
592 	gettext_noop("Query Tuning / Planner Method Configuration"),
593 	/* QUERY_TUNING_COST */
594 	gettext_noop("Query Tuning / Planner Cost Constants"),
595 	/* QUERY_TUNING_GEQO */
596 	gettext_noop("Query Tuning / Genetic Query Optimizer"),
597 	/* QUERY_TUNING_OTHER */
598 	gettext_noop("Query Tuning / Other Planner Options"),
599 	/* LOGGING */
600 	gettext_noop("Reporting and Logging"),
601 	/* LOGGING_WHERE */
602 	gettext_noop("Reporting and Logging / Where to Log"),
603 	/* LOGGING_WHEN */
604 	gettext_noop("Reporting and Logging / When to Log"),
605 	/* LOGGING_WHAT */
606 	gettext_noop("Reporting and Logging / What to Log"),
607 	/* PROCESS_TITLE */
608 	gettext_noop("Process Title"),
609 	/* STATS */
610 	gettext_noop("Statistics"),
611 	/* STATS_MONITORING */
612 	gettext_noop("Statistics / Monitoring"),
613 	/* STATS_COLLECTOR */
614 	gettext_noop("Statistics / Query and Index Statistics Collector"),
615 	/* AUTOVACUUM */
616 	gettext_noop("Autovacuum"),
617 	/* CLIENT_CONN */
618 	gettext_noop("Client Connection Defaults"),
619 	/* CLIENT_CONN_STATEMENT */
620 	gettext_noop("Client Connection Defaults / Statement Behavior"),
621 	/* CLIENT_CONN_LOCALE */
622 	gettext_noop("Client Connection Defaults / Locale and Formatting"),
623 	/* CLIENT_CONN_PRELOAD */
624 	gettext_noop("Client Connection Defaults / Shared Library Preloading"),
625 	/* CLIENT_CONN_OTHER */
626 	gettext_noop("Client Connection Defaults / Other Defaults"),
627 	/* LOCK_MANAGEMENT */
628 	gettext_noop("Lock Management"),
629 	/* COMPAT_OPTIONS */
630 	gettext_noop("Version and Platform Compatibility"),
631 	/* COMPAT_OPTIONS_PREVIOUS */
632 	gettext_noop("Version and Platform Compatibility / Previous PostgreSQL Versions"),
633 	/* COMPAT_OPTIONS_CLIENT */
634 	gettext_noop("Version and Platform Compatibility / Other Platforms and Clients"),
635 	/* ERROR_HANDLING */
636 	gettext_noop("Error Handling"),
637 	/* PRESET_OPTIONS */
638 	gettext_noop("Preset Options"),
639 	/* CUSTOM_OPTIONS */
640 	gettext_noop("Customized Options"),
641 	/* DEVELOPER_OPTIONS */
642 	gettext_noop("Developer Options"),
643 	/* help_config wants this array to be null-terminated */
644 	NULL
645 };
646 
647 /*
648  * Displayable names for GUC variable types (enum config_type)
649  *
650  * Note: these strings are deliberately not localized.
651  */
652 const char *const config_type_names[] =
653 {
654 	 /* PGC_BOOL */ "bool",
655 	 /* PGC_INT */ "integer",
656 	 /* PGC_REAL */ "real",
657 	 /* PGC_STRING */ "string",
658 	 /* PGC_ENUM */ "enum"
659 };
660 
661 /*
662  * Unit conversion tables.
663  *
664  * There are two tables, one for memory units, and another for time units.
665  * For each supported conversion from one unit to another, we have an entry
666  * in the table.
667  *
668  * To keep things simple, and to avoid intermediate-value overflows,
669  * conversions are never chained.  There needs to be a direct conversion
670  * between all units (of the same type).
671  *
672  * The conversions from each base unit must be kept in order from greatest
673  * to smallest unit; convert_from_base_unit() relies on that.  (The order of
674  * the base units does not matter.)
675  */
676 #define MAX_UNIT_LEN		3	/* length of longest recognized unit string */
677 
678 typedef struct
679 {
680 	char		unit[MAX_UNIT_LEN + 1]; /* unit, as a string, like "kB" or
681 										 * "min" */
682 	int			base_unit;		/* GUC_UNIT_XXX */
683 	int			multiplier;		/* If positive, multiply the value with this
684 								 * for unit -> base_unit conversion.  If
685 								 * negative, divide (with the absolute value) */
686 } unit_conversion;
687 
688 /* Ensure that the constants in the tables don't overflow or underflow */
689 #if BLCKSZ < 1024 || BLCKSZ > (1024*1024)
690 #error BLCKSZ must be between 1KB and 1MB
691 #endif
692 #if XLOG_BLCKSZ < 1024 || XLOG_BLCKSZ > (1024*1024)
693 #error XLOG_BLCKSZ must be between 1KB and 1MB
694 #endif
695 #if XLOG_SEG_SIZE < (1024*1024) || XLOG_BLCKSZ > (1024*1024*1024)
696 #error XLOG_SEG_SIZE must be between 1MB and 1GB
697 #endif
698 
699 static const char *memory_units_hint = gettext_noop("Valid units for this parameter are \"kB\", \"MB\", \"GB\", and \"TB\".");
700 
701 static const unit_conversion memory_unit_conversion_table[] =
702 {
703 	{"TB", GUC_UNIT_KB, 1024 * 1024 * 1024},
704 	{"GB", GUC_UNIT_KB, 1024 * 1024},
705 	{"MB", GUC_UNIT_KB, 1024},
706 	{"kB", GUC_UNIT_KB, 1},
707 
708 	{"TB", GUC_UNIT_BLOCKS, (1024 * 1024 * 1024) / (BLCKSZ / 1024)},
709 	{"GB", GUC_UNIT_BLOCKS, (1024 * 1024) / (BLCKSZ / 1024)},
710 	{"MB", GUC_UNIT_BLOCKS, 1024 / (BLCKSZ / 1024)},
711 	{"kB", GUC_UNIT_BLOCKS, -(BLCKSZ / 1024)},
712 
713 	{"TB", GUC_UNIT_XBLOCKS, (1024 * 1024 * 1024) / (XLOG_BLCKSZ / 1024)},
714 	{"GB", GUC_UNIT_XBLOCKS, (1024 * 1024) / (XLOG_BLCKSZ / 1024)},
715 	{"MB", GUC_UNIT_XBLOCKS, 1024 / (XLOG_BLCKSZ / 1024)},
716 	{"kB", GUC_UNIT_XBLOCKS, -(XLOG_BLCKSZ / 1024)},
717 
718 	{"TB", GUC_UNIT_XSEGS, (1024 * 1024 * 1024) / (XLOG_SEG_SIZE / 1024)},
719 	{"GB", GUC_UNIT_XSEGS, (1024 * 1024) / (XLOG_SEG_SIZE / 1024)},
720 	{"MB", GUC_UNIT_XSEGS, -(XLOG_SEG_SIZE / (1024 * 1024))},
721 	{"kB", GUC_UNIT_XSEGS, -(XLOG_SEG_SIZE / 1024)},
722 
723 	{""}						/* end of table marker */
724 };
725 
726 static const char *time_units_hint = gettext_noop("Valid units for this parameter are \"ms\", \"s\", \"min\", \"h\", and \"d\".");
727 
728 static const unit_conversion time_unit_conversion_table[] =
729 {
730 	{"d", GUC_UNIT_MS, 1000 * 60 * 60 * 24},
731 	{"h", GUC_UNIT_MS, 1000 * 60 * 60},
732 	{"min", GUC_UNIT_MS, 1000 * 60},
733 	{"s", GUC_UNIT_MS, 1000},
734 	{"ms", GUC_UNIT_MS, 1},
735 
736 	{"d", GUC_UNIT_S, 60 * 60 * 24},
737 	{"h", GUC_UNIT_S, 60 * 60},
738 	{"min", GUC_UNIT_S, 60},
739 	{"s", GUC_UNIT_S, 1},
740 	{"ms", GUC_UNIT_S, -1000},
741 
742 	{"d", GUC_UNIT_MIN, 60 * 24},
743 	{"h", GUC_UNIT_MIN, 60},
744 	{"min", GUC_UNIT_MIN, 1},
745 	{"s", GUC_UNIT_MIN, -60},
746 	{"ms", GUC_UNIT_MIN, -1000 * 60},
747 
748 	{""}						/* end of table marker */
749 };
750 
751 /*
752  * Contents of GUC tables
753  *
754  * See src/backend/utils/misc/README for design notes.
755  *
756  * TO ADD AN OPTION:
757  *
758  * 1. Declare a global variable of type bool, int, double, or char*
759  *	  and make use of it.
760  *
761  * 2. Decide at what times it's safe to set the option. See guc.h for
762  *	  details.
763  *
764  * 3. Decide on a name, a default value, upper and lower bounds (if
765  *	  applicable), etc.
766  *
767  * 4. Add a record below.
768  *
769  * 5. Add it to src/backend/utils/misc/postgresql.conf.sample, if
770  *	  appropriate.
771  *
772  * 6. Don't forget to document the option (at least in config.sgml).
773  *
774  * 7. If it's a new GUC_LIST_QUOTE option, you must add it to
775  *	  variable_is_guc_list_quote() in src/bin/pg_dump/dumputils.c.
776  */
777 
778 
779 /******** option records follow ********/
780 
781 static struct config_bool ConfigureNamesBool[] =
782 {
783 	{
784 		{"enable_seqscan", PGC_USERSET, QUERY_TUNING_METHOD,
785 			gettext_noop("Enables the planner's use of sequential-scan plans."),
786 			NULL
787 		},
788 		&enable_seqscan,
789 		true,
790 		NULL, NULL, NULL
791 	},
792 	{
793 		{"enable_indexscan", PGC_USERSET, QUERY_TUNING_METHOD,
794 			gettext_noop("Enables the planner's use of index-scan plans."),
795 			NULL
796 		},
797 		&enable_indexscan,
798 		true,
799 		NULL, NULL, NULL
800 	},
801 	{
802 		{"enable_indexonlyscan", PGC_USERSET, QUERY_TUNING_METHOD,
803 			gettext_noop("Enables the planner's use of index-only-scan plans."),
804 			NULL
805 		},
806 		&enable_indexonlyscan,
807 		true,
808 		NULL, NULL, NULL
809 	},
810 	{
811 		{"enable_bitmapscan", PGC_USERSET, QUERY_TUNING_METHOD,
812 			gettext_noop("Enables the planner's use of bitmap-scan plans."),
813 			NULL
814 		},
815 		&enable_bitmapscan,
816 		true,
817 		NULL, NULL, NULL
818 	},
819 	{
820 		{"enable_tidscan", PGC_USERSET, QUERY_TUNING_METHOD,
821 			gettext_noop("Enables the planner's use of TID scan plans."),
822 			NULL
823 		},
824 		&enable_tidscan,
825 		true,
826 		NULL, NULL, NULL
827 	},
828 	{
829 		{"enable_sort", PGC_USERSET, QUERY_TUNING_METHOD,
830 			gettext_noop("Enables the planner's use of explicit sort steps."),
831 			NULL
832 		},
833 		&enable_sort,
834 		true,
835 		NULL, NULL, NULL
836 	},
837 	{
838 		{"enable_hashagg", PGC_USERSET, QUERY_TUNING_METHOD,
839 			gettext_noop("Enables the planner's use of hashed aggregation plans."),
840 			NULL
841 		},
842 		&enable_hashagg,
843 		true,
844 		NULL, NULL, NULL
845 	},
846 	{
847 		{"enable_material", PGC_USERSET, QUERY_TUNING_METHOD,
848 			gettext_noop("Enables the planner's use of materialization."),
849 			NULL
850 		},
851 		&enable_material,
852 		true,
853 		NULL, NULL, NULL
854 	},
855 	{
856 		{"enable_nestloop", PGC_USERSET, QUERY_TUNING_METHOD,
857 			gettext_noop("Enables the planner's use of nested-loop join plans."),
858 			NULL
859 		},
860 		&enable_nestloop,
861 		true,
862 		NULL, NULL, NULL
863 	},
864 	{
865 		{"enable_mergejoin", PGC_USERSET, QUERY_TUNING_METHOD,
866 			gettext_noop("Enables the planner's use of merge join plans."),
867 			NULL
868 		},
869 		&enable_mergejoin,
870 		true,
871 		NULL, NULL, NULL
872 	},
873 	{
874 		{"enable_hashjoin", PGC_USERSET, QUERY_TUNING_METHOD,
875 			gettext_noop("Enables the planner's use of hash join plans."),
876 			NULL
877 		},
878 		&enable_hashjoin,
879 		true,
880 		NULL, NULL, NULL
881 	},
882 
883 	{
884 		{"geqo", PGC_USERSET, QUERY_TUNING_GEQO,
885 			gettext_noop("Enables genetic query optimization."),
886 			gettext_noop("This algorithm attempts to do planning without "
887 						 "exhaustive searching.")
888 		},
889 		&enable_geqo,
890 		true,
891 		NULL, NULL, NULL
892 	},
893 	{
894 		/* Not for general use --- used by SET SESSION AUTHORIZATION */
895 		{"is_superuser", PGC_INTERNAL, UNGROUPED,
896 			gettext_noop("Shows whether the current user is a superuser."),
897 			NULL,
898 			GUC_REPORT | GUC_NO_SHOW_ALL | GUC_NO_RESET_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
899 		},
900 		&session_auth_is_superuser,
901 		false,
902 		NULL, NULL, NULL
903 	},
904 	{
905 		{"bonjour", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
906 			gettext_noop("Enables advertising the server via Bonjour."),
907 			NULL
908 		},
909 		&enable_bonjour,
910 		false,
911 		check_bonjour, NULL, NULL
912 	},
913 	{
914 		{"track_commit_timestamp", PGC_POSTMASTER, REPLICATION,
915 			gettext_noop("Collects transaction commit time."),
916 			NULL
917 		},
918 		&track_commit_timestamp,
919 		false,
920 		NULL, NULL, NULL
921 	},
922 	{
923 		{"ssl", PGC_POSTMASTER, CONN_AUTH_SECURITY,
924 			gettext_noop("Enables SSL connections."),
925 			NULL
926 		},
927 		&EnableSSL,
928 		false,
929 		check_ssl, NULL, NULL
930 	},
931 	{
932 		{"ssl_prefer_server_ciphers", PGC_POSTMASTER, CONN_AUTH_SECURITY,
933 			gettext_noop("Give priority to server ciphersuite order."),
934 			NULL
935 		},
936 		&SSLPreferServerCiphers,
937 		true,
938 		NULL, NULL, NULL
939 	},
940 	{
941 		{"fsync", PGC_SIGHUP, WAL_SETTINGS,
942 			gettext_noop("Forces synchronization of updates to disk."),
943 			gettext_noop("The server will use the fsync() system call in several places to make "
944 			"sure that updates are physically written to disk. This insures "
945 						 "that a database cluster will recover to a consistent state after "
946 						 "an operating system or hardware crash.")
947 		},
948 		&enableFsync,
949 		true,
950 		NULL, NULL, NULL
951 	},
952 	{
953 		{"ignore_checksum_failure", PGC_SUSET, DEVELOPER_OPTIONS,
954 			gettext_noop("Continues processing after a checksum failure."),
955 			gettext_noop("Detection of a checksum failure normally causes PostgreSQL to "
956 				"report an error, aborting the current transaction. Setting "
957 						 "ignore_checksum_failure to true causes the system to ignore the failure "
958 			   "(but still report a warning), and continue processing. This "
959 			  "behavior could cause crashes or other serious problems. Only "
960 						 "has an effect if checksums are enabled."),
961 			GUC_NOT_IN_SAMPLE
962 		},
963 		&ignore_checksum_failure,
964 		false,
965 		NULL, NULL, NULL
966 	},
967 	{
968 		{"zero_damaged_pages", PGC_SUSET, DEVELOPER_OPTIONS,
969 			gettext_noop("Continues processing past damaged page headers."),
970 			gettext_noop("Detection of a damaged page header normally causes PostgreSQL to "
971 				"report an error, aborting the current transaction. Setting "
972 						 "zero_damaged_pages to true causes the system to instead report a "
973 						 "warning, zero out the damaged page, and continue processing. This "
974 						 "behavior will destroy data, namely all the rows on the damaged page."),
975 			GUC_NOT_IN_SAMPLE
976 		},
977 		&zero_damaged_pages,
978 		false,
979 		NULL, NULL, NULL
980 	},
981 	{
982 		{"full_page_writes", PGC_SIGHUP, WAL_SETTINGS,
983 			gettext_noop("Writes full pages to WAL when first modified after a checkpoint."),
984 			gettext_noop("A page write in process during an operating system crash might be "
985 						 "only partially written to disk.  During recovery, the row changes "
986 			  "stored in WAL are not enough to recover.  This option writes "
987 						 "pages when first modified after a checkpoint to WAL so full recovery "
988 						 "is possible.")
989 		},
990 		&fullPageWrites,
991 		true,
992 		NULL, NULL, NULL
993 	},
994 
995 	{
996 		{"wal_log_hints", PGC_POSTMASTER, WAL_SETTINGS,
997 			gettext_noop("Writes full pages to WAL when first modified after a checkpoint, even for a non-critical modification."),
998 			NULL
999 		},
1000 		&wal_log_hints,
1001 		false,
1002 		NULL, NULL, NULL
1003 	},
1004 
1005 	{
1006 		{"wal_compression", PGC_SUSET, WAL_SETTINGS,
1007 			gettext_noop("Compresses full-page writes written in WAL file."),
1008 			NULL
1009 		},
1010 		&wal_compression,
1011 		false,
1012 		NULL, NULL, NULL
1013 	},
1014 
1015 	{
1016 		{"log_checkpoints", PGC_SIGHUP, LOGGING_WHAT,
1017 			gettext_noop("Logs each checkpoint."),
1018 			NULL
1019 		},
1020 		&log_checkpoints,
1021 		false,
1022 		NULL, NULL, NULL
1023 	},
1024 	{
1025 		{"log_connections", PGC_SU_BACKEND, LOGGING_WHAT,
1026 			gettext_noop("Logs each successful connection."),
1027 			NULL
1028 		},
1029 		&Log_connections,
1030 		false,
1031 		NULL, NULL, NULL
1032 	},
1033 	{
1034 		{"log_disconnections", PGC_SU_BACKEND, LOGGING_WHAT,
1035 			gettext_noop("Logs end of a session, including duration."),
1036 			NULL
1037 		},
1038 		&Log_disconnections,
1039 		false,
1040 		NULL, NULL, NULL
1041 	},
1042 	{
1043 		{"log_replication_commands", PGC_SUSET, LOGGING_WHAT,
1044 			gettext_noop("Logs each replication command."),
1045 			NULL
1046 		},
1047 		&log_replication_commands,
1048 		false,
1049 		NULL, NULL, NULL
1050 	},
1051 	{
1052 		{"debug_assertions", PGC_INTERNAL, PRESET_OPTIONS,
1053 			gettext_noop("Shows whether the running server has assertion checks enabled."),
1054 			NULL,
1055 			GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
1056 		},
1057 		&assert_enabled,
1058 #ifdef USE_ASSERT_CHECKING
1059 		true,
1060 #else
1061 		false,
1062 #endif
1063 		NULL, NULL, NULL
1064 	},
1065 
1066 	{
1067 		{"exit_on_error", PGC_USERSET, ERROR_HANDLING_OPTIONS,
1068 			gettext_noop("Terminate session on any error."),
1069 			NULL
1070 		},
1071 		&ExitOnAnyError,
1072 		false,
1073 		NULL, NULL, NULL
1074 	},
1075 	{
1076 		{"restart_after_crash", PGC_SIGHUP, ERROR_HANDLING_OPTIONS,
1077 			gettext_noop("Reinitialize server after backend crash."),
1078 			NULL
1079 		},
1080 		&restart_after_crash,
1081 		true,
1082 		NULL, NULL, NULL
1083 	},
1084 
1085 	{
1086 		{"log_duration", PGC_SUSET, LOGGING_WHAT,
1087 			gettext_noop("Logs the duration of each completed SQL statement."),
1088 			NULL
1089 		},
1090 		&log_duration,
1091 		false,
1092 		NULL, NULL, NULL
1093 	},
1094 	{
1095 		{"debug_print_parse", PGC_USERSET, LOGGING_WHAT,
1096 			gettext_noop("Logs each query's parse tree."),
1097 			NULL
1098 		},
1099 		&Debug_print_parse,
1100 		false,
1101 		NULL, NULL, NULL
1102 	},
1103 	{
1104 		{"debug_print_rewritten", PGC_USERSET, LOGGING_WHAT,
1105 			gettext_noop("Logs each query's rewritten parse tree."),
1106 			NULL
1107 		},
1108 		&Debug_print_rewritten,
1109 		false,
1110 		NULL, NULL, NULL
1111 	},
1112 	{
1113 		{"debug_print_plan", PGC_USERSET, LOGGING_WHAT,
1114 			gettext_noop("Logs each query's execution plan."),
1115 			NULL
1116 		},
1117 		&Debug_print_plan,
1118 		false,
1119 		NULL, NULL, NULL
1120 	},
1121 	{
1122 		{"debug_pretty_print", PGC_USERSET, LOGGING_WHAT,
1123 			gettext_noop("Indents parse and plan tree displays."),
1124 			NULL
1125 		},
1126 		&Debug_pretty_print,
1127 		true,
1128 		NULL, NULL, NULL
1129 	},
1130 	{
1131 		{"log_parser_stats", PGC_SUSET, STATS_MONITORING,
1132 			gettext_noop("Writes parser performance statistics to the server log."),
1133 			NULL
1134 		},
1135 		&log_parser_stats,
1136 		false,
1137 		check_stage_log_stats, NULL, NULL
1138 	},
1139 	{
1140 		{"log_planner_stats", PGC_SUSET, STATS_MONITORING,
1141 			gettext_noop("Writes planner performance statistics to the server log."),
1142 			NULL
1143 		},
1144 		&log_planner_stats,
1145 		false,
1146 		check_stage_log_stats, NULL, NULL
1147 	},
1148 	{
1149 		{"log_executor_stats", PGC_SUSET, STATS_MONITORING,
1150 			gettext_noop("Writes executor performance statistics to the server log."),
1151 			NULL
1152 		},
1153 		&log_executor_stats,
1154 		false,
1155 		check_stage_log_stats, NULL, NULL
1156 	},
1157 	{
1158 		{"log_statement_stats", PGC_SUSET, STATS_MONITORING,
1159 			gettext_noop("Writes cumulative performance statistics to the server log."),
1160 			NULL
1161 		},
1162 		&log_statement_stats,
1163 		false,
1164 		check_log_stats, NULL, NULL
1165 	},
1166 #ifdef BTREE_BUILD_STATS
1167 	{
1168 		{"log_btree_build_stats", PGC_SUSET, DEVELOPER_OPTIONS,
1169 			gettext_noop("Logs system resource usage statistics (memory and CPU) on various B-tree operations."),
1170 			NULL,
1171 			GUC_NOT_IN_SAMPLE
1172 		},
1173 		&log_btree_build_stats,
1174 		false,
1175 		NULL, NULL, NULL
1176 	},
1177 #endif
1178 
1179 	{
1180 		{"track_activities", PGC_SUSET, STATS_COLLECTOR,
1181 			gettext_noop("Collects information about executing commands."),
1182 			gettext_noop("Enables the collection of information on the currently "
1183 						 "executing command of each session, along with "
1184 						 "the time at which that command began execution.")
1185 		},
1186 		&pgstat_track_activities,
1187 		true,
1188 		NULL, NULL, NULL
1189 	},
1190 	{
1191 		{"track_counts", PGC_SUSET, STATS_COLLECTOR,
1192 			gettext_noop("Collects statistics on database activity."),
1193 			NULL
1194 		},
1195 		&pgstat_track_counts,
1196 		true,
1197 		NULL, NULL, NULL
1198 	},
1199 	{
1200 		{"track_io_timing", PGC_SUSET, STATS_COLLECTOR,
1201 			gettext_noop("Collects timing statistics for database I/O activity."),
1202 			NULL
1203 		},
1204 		&track_io_timing,
1205 		false,
1206 		NULL, NULL, NULL
1207 	},
1208 
1209 	{
1210 		{"update_process_title", PGC_SUSET, PROCESS_TITLE,
1211 			gettext_noop("Updates the process title to show the active SQL command."),
1212 			gettext_noop("Enables updating of the process title every time a new SQL command is received by the server.")
1213 		},
1214 		&update_process_title,
1215 #ifdef WIN32
1216 		false,
1217 #else
1218 		true,
1219 #endif
1220 		NULL, NULL, NULL
1221 	},
1222 
1223 	{
1224 		{"autovacuum", PGC_SIGHUP, AUTOVACUUM,
1225 			gettext_noop("Starts the autovacuum subprocess."),
1226 			NULL
1227 		},
1228 		&autovacuum_start_daemon,
1229 		true,
1230 		NULL, NULL, NULL
1231 	},
1232 
1233 	{
1234 		{"trace_notify", PGC_USERSET, DEVELOPER_OPTIONS,
1235 			gettext_noop("Generates debugging output for LISTEN and NOTIFY."),
1236 			NULL,
1237 			GUC_NOT_IN_SAMPLE
1238 		},
1239 		&Trace_notify,
1240 		false,
1241 		NULL, NULL, NULL
1242 	},
1243 
1244 #ifdef LOCK_DEBUG
1245 	{
1246 		{"trace_locks", PGC_SUSET, DEVELOPER_OPTIONS,
1247 			gettext_noop("Emits information about lock usage."),
1248 			NULL,
1249 			GUC_NOT_IN_SAMPLE
1250 		},
1251 		&Trace_locks,
1252 		false,
1253 		NULL, NULL, NULL
1254 	},
1255 	{
1256 		{"trace_userlocks", PGC_SUSET, DEVELOPER_OPTIONS,
1257 			gettext_noop("Emits information about user lock usage."),
1258 			NULL,
1259 			GUC_NOT_IN_SAMPLE
1260 		},
1261 		&Trace_userlocks,
1262 		false,
1263 		NULL, NULL, NULL
1264 	},
1265 	{
1266 		{"trace_lwlocks", PGC_SUSET, DEVELOPER_OPTIONS,
1267 			gettext_noop("Emits information about lightweight lock usage."),
1268 			NULL,
1269 			GUC_NOT_IN_SAMPLE
1270 		},
1271 		&Trace_lwlocks,
1272 		false,
1273 		NULL, NULL, NULL
1274 	},
1275 	{
1276 		{"debug_deadlocks", PGC_SUSET, DEVELOPER_OPTIONS,
1277 			gettext_noop("Dumps information about all current locks when a deadlock timeout occurs."),
1278 			NULL,
1279 			GUC_NOT_IN_SAMPLE
1280 		},
1281 		&Debug_deadlocks,
1282 		false,
1283 		NULL, NULL, NULL
1284 	},
1285 #endif
1286 
1287 	{
1288 		{"log_lock_waits", PGC_SUSET, LOGGING_WHAT,
1289 			gettext_noop("Logs long lock waits."),
1290 			NULL
1291 		},
1292 		&log_lock_waits,
1293 		false,
1294 		NULL, NULL, NULL
1295 	},
1296 
1297 	{
1298 		{"log_hostname", PGC_SIGHUP, LOGGING_WHAT,
1299 			gettext_noop("Logs the host name in the connection logs."),
1300 			gettext_noop("By default, connection logs only show the IP address "
1301 						 "of the connecting host. If you want them to show the host name you "
1302 			  "can turn this on, but depending on your host name resolution "
1303 			   "setup it might impose a non-negligible performance penalty.")
1304 		},
1305 		&log_hostname,
1306 		false,
1307 		NULL, NULL, NULL
1308 	},
1309 	{
1310 		{"sql_inheritance", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
1311 			gettext_noop("Causes subtables to be included by default in various commands."),
1312 			NULL
1313 		},
1314 		&SQL_inheritance,
1315 		true,
1316 		NULL, NULL, NULL
1317 	},
1318 	{
1319 		{"password_encryption", PGC_USERSET, CONN_AUTH_SECURITY,
1320 			gettext_noop("Encrypt passwords."),
1321 			gettext_noop("When a password is specified in CREATE USER or "
1322 			   "ALTER USER without writing either ENCRYPTED or UNENCRYPTED, "
1323 						 "this parameter determines whether the password is to be encrypted.")
1324 		},
1325 		&Password_encryption,
1326 		true,
1327 		NULL, NULL, NULL
1328 	},
1329 	{
1330 		{"transform_null_equals", PGC_USERSET, COMPAT_OPTIONS_CLIENT,
1331 			gettext_noop("Treats \"expr=NULL\" as \"expr IS NULL\"."),
1332 			gettext_noop("When turned on, expressions of the form expr = NULL "
1333 			   "(or NULL = expr) are treated as expr IS NULL, that is, they "
1334 				"return true if expr evaluates to the null value, and false "
1335 			   "otherwise. The correct behavior of expr = NULL is to always "
1336 						 "return null (unknown).")
1337 		},
1338 		&Transform_null_equals,
1339 		false,
1340 		NULL, NULL, NULL
1341 	},
1342 	{
1343 		{"db_user_namespace", PGC_SIGHUP, CONN_AUTH_SECURITY,
1344 			gettext_noop("Enables per-database user names."),
1345 			NULL
1346 		},
1347 		&Db_user_namespace,
1348 		false,
1349 		NULL, NULL, NULL
1350 	},
1351 	{
1352 		{"default_transaction_read_only", PGC_USERSET, CLIENT_CONN_STATEMENT,
1353 			gettext_noop("Sets the default read-only status of new transactions."),
1354 			NULL
1355 		},
1356 		&DefaultXactReadOnly,
1357 		false,
1358 		NULL, NULL, NULL
1359 	},
1360 	{
1361 		{"transaction_read_only", PGC_USERSET, CLIENT_CONN_STATEMENT,
1362 			gettext_noop("Sets the current transaction's read-only status."),
1363 			NULL,
1364 			GUC_NO_RESET_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
1365 		},
1366 		&XactReadOnly,
1367 		false,
1368 		check_transaction_read_only, NULL, NULL
1369 	},
1370 	{
1371 		{"default_transaction_deferrable", PGC_USERSET, CLIENT_CONN_STATEMENT,
1372 			gettext_noop("Sets the default deferrable status of new transactions."),
1373 			NULL
1374 		},
1375 		&DefaultXactDeferrable,
1376 		false,
1377 		NULL, NULL, NULL
1378 	},
1379 	{
1380 		{"transaction_deferrable", PGC_USERSET, CLIENT_CONN_STATEMENT,
1381 			gettext_noop("Whether to defer a read-only serializable transaction until it can be executed with no possible serialization failures."),
1382 			NULL,
1383 			GUC_NO_RESET_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
1384 		},
1385 		&XactDeferrable,
1386 		false,
1387 		check_transaction_deferrable, NULL, NULL
1388 	},
1389 	{
1390 		{"row_security", PGC_USERSET, CONN_AUTH_SECURITY,
1391 			gettext_noop("Enable row security."),
1392 			gettext_noop("When enabled, row security will be applied to all users.")
1393 		},
1394 		&row_security,
1395 		true,
1396 		NULL, NULL, NULL
1397 	},
1398 	{
1399 		{"check_function_bodies", PGC_USERSET, CLIENT_CONN_STATEMENT,
1400 			gettext_noop("Check function bodies during CREATE FUNCTION."),
1401 			NULL
1402 		},
1403 		&check_function_bodies,
1404 		true,
1405 		NULL, NULL, NULL
1406 	},
1407 	{
1408 		{"array_nulls", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
1409 			gettext_noop("Enable input of NULL elements in arrays."),
1410 			gettext_noop("When turned on, unquoted NULL in an array input "
1411 						 "value means a null value; "
1412 						 "otherwise it is taken literally.")
1413 		},
1414 		&Array_nulls,
1415 		true,
1416 		NULL, NULL, NULL
1417 	},
1418 	{
1419 		{"default_with_oids", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
1420 			gettext_noop("Create new tables with OIDs by default."),
1421 			NULL
1422 		},
1423 		&default_with_oids,
1424 		false,
1425 		NULL, NULL, NULL
1426 	},
1427 	{
1428 		{"logging_collector", PGC_POSTMASTER, LOGGING_WHERE,
1429 			gettext_noop("Start a subprocess to capture stderr output and/or csvlogs into log files."),
1430 			NULL
1431 		},
1432 		&Logging_collector,
1433 		false,
1434 		NULL, NULL, NULL
1435 	},
1436 	{
1437 		{"log_truncate_on_rotation", PGC_SIGHUP, LOGGING_WHERE,
1438 			gettext_noop("Truncate existing log files of same name during log rotation."),
1439 			NULL
1440 		},
1441 		&Log_truncate_on_rotation,
1442 		false,
1443 		NULL, NULL, NULL
1444 	},
1445 
1446 #ifdef TRACE_SORT
1447 	{
1448 		{"trace_sort", PGC_USERSET, DEVELOPER_OPTIONS,
1449 			gettext_noop("Emit information about resource usage in sorting."),
1450 			NULL,
1451 			GUC_NOT_IN_SAMPLE
1452 		},
1453 		&trace_sort,
1454 		false,
1455 		NULL, NULL, NULL
1456 	},
1457 #endif
1458 
1459 #ifdef TRACE_SYNCSCAN
1460 	/* this is undocumented because not exposed in a standard build */
1461 	{
1462 		{"trace_syncscan", PGC_USERSET, DEVELOPER_OPTIONS,
1463 			gettext_noop("Generate debugging output for synchronized scanning."),
1464 			NULL,
1465 			GUC_NOT_IN_SAMPLE
1466 		},
1467 		&trace_syncscan,
1468 		false,
1469 		NULL, NULL, NULL
1470 	},
1471 #endif
1472 
1473 #ifdef DEBUG_BOUNDED_SORT
1474 	/* this is undocumented because not exposed in a standard build */
1475 	{
1476 		{
1477 			"optimize_bounded_sort", PGC_USERSET, QUERY_TUNING_METHOD,
1478 			gettext_noop("Enable bounded sorting using heap sort."),
1479 			NULL,
1480 			GUC_NOT_IN_SAMPLE
1481 		},
1482 		&optimize_bounded_sort,
1483 		true,
1484 		NULL, NULL, NULL
1485 	},
1486 #endif
1487 
1488 #ifdef WAL_DEBUG
1489 	{
1490 		{"wal_debug", PGC_SUSET, DEVELOPER_OPTIONS,
1491 			gettext_noop("Emit WAL-related debugging output."),
1492 			NULL,
1493 			GUC_NOT_IN_SAMPLE
1494 		},
1495 		&XLOG_DEBUG,
1496 		false,
1497 		NULL, NULL, NULL
1498 	},
1499 #endif
1500 
1501 	{
1502 		{"integer_datetimes", PGC_INTERNAL, PRESET_OPTIONS,
1503 			gettext_noop("Datetimes are integer based."),
1504 			NULL,
1505 			GUC_REPORT | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
1506 		},
1507 		&integer_datetimes,
1508 #ifdef HAVE_INT64_TIMESTAMP
1509 		true,
1510 #else
1511 		false,
1512 #endif
1513 		NULL, NULL, NULL
1514 	},
1515 
1516 	{
1517 		{"krb_caseins_users", PGC_SIGHUP, CONN_AUTH_SECURITY,
1518 			gettext_noop("Sets whether Kerberos and GSSAPI user names should be treated as case-insensitive."),
1519 			NULL
1520 		},
1521 		&pg_krb_caseins_users,
1522 		false,
1523 		NULL, NULL, NULL
1524 	},
1525 
1526 	{
1527 		{"escape_string_warning", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
1528 			gettext_noop("Warn about backslash escapes in ordinary string literals."),
1529 			NULL
1530 		},
1531 		&escape_string_warning,
1532 		true,
1533 		NULL, NULL, NULL
1534 	},
1535 
1536 	{
1537 		{"standard_conforming_strings", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
1538 			gettext_noop("Causes '...' strings to treat backslashes literally."),
1539 			NULL,
1540 			GUC_REPORT
1541 		},
1542 		&standard_conforming_strings,
1543 		true,
1544 		NULL, NULL, NULL
1545 	},
1546 
1547 	{
1548 		{"synchronize_seqscans", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
1549 			gettext_noop("Enable synchronized sequential scans."),
1550 			NULL
1551 		},
1552 		&synchronize_seqscans,
1553 		true,
1554 		NULL, NULL, NULL
1555 	},
1556 
1557 	{
1558 		{"hot_standby", PGC_POSTMASTER, REPLICATION_STANDBY,
1559 			gettext_noop("Allows connections and queries during recovery."),
1560 			NULL
1561 		},
1562 		&EnableHotStandby,
1563 		false,
1564 		NULL, NULL, NULL
1565 	},
1566 
1567 	{
1568 		{"hot_standby_feedback", PGC_SIGHUP, REPLICATION_STANDBY,
1569 			gettext_noop("Allows feedback from a hot standby to the primary that will avoid query conflicts."),
1570 			NULL
1571 		},
1572 		&hot_standby_feedback,
1573 		false,
1574 		NULL, NULL, NULL
1575 	},
1576 
1577 	{
1578 		{"allow_system_table_mods", PGC_POSTMASTER, DEVELOPER_OPTIONS,
1579 			gettext_noop("Allows modifications of the structure of system tables."),
1580 			NULL,
1581 			GUC_NOT_IN_SAMPLE
1582 		},
1583 		&allowSystemTableMods,
1584 		false,
1585 		NULL, NULL, NULL
1586 	},
1587 
1588 	{
1589 		{"ignore_system_indexes", PGC_BACKEND, DEVELOPER_OPTIONS,
1590 			gettext_noop("Disables reading from system indexes."),
1591 			gettext_noop("It does not prevent updating the indexes, so it is safe "
1592 						 "to use.  The worst consequence is slowness."),
1593 			GUC_NOT_IN_SAMPLE
1594 		},
1595 		&IgnoreSystemIndexes,
1596 		false,
1597 		NULL, NULL, NULL
1598 	},
1599 
1600 	{
1601 		{"lo_compat_privileges", PGC_SUSET, COMPAT_OPTIONS_PREVIOUS,
1602 			gettext_noop("Enables backward compatibility mode for privilege checks on large objects."),
1603 			gettext_noop("Skips privilege checks when reading or modifying large objects, "
1604 				  "for compatibility with PostgreSQL releases prior to 9.0.")
1605 		},
1606 		&lo_compat_privileges,
1607 		false,
1608 		NULL, NULL, NULL
1609 	},
1610 
1611 	{
1612 		{"operator_precedence_warning", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
1613 			gettext_noop("Emit a warning for constructs that changed meaning since PostgreSQL 9.4."),
1614 			NULL,
1615 		},
1616 		&operator_precedence_warning,
1617 		false,
1618 		NULL, NULL, NULL
1619 	},
1620 
1621 	{
1622 		{"quote_all_identifiers", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
1623 			gettext_noop("When generating SQL fragments, quote all identifiers."),
1624 			NULL,
1625 		},
1626 		&quote_all_identifiers,
1627 		false,
1628 		NULL, NULL, NULL
1629 	},
1630 
1631 	{
1632 		{"data_checksums", PGC_INTERNAL, PRESET_OPTIONS,
1633 			gettext_noop("Shows whether data checksums are turned on for this cluster."),
1634 			NULL,
1635 			GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
1636 		},
1637 		&data_checksums,
1638 		false,
1639 		NULL, NULL, NULL
1640 	},
1641 
1642 	{
1643 		{"syslog_sequence_numbers", PGC_SIGHUP, LOGGING_WHERE,
1644 			gettext_noop("Add sequence number to syslog messages to avoid duplicate suppression."),
1645 			NULL
1646 		},
1647 		&syslog_sequence_numbers,
1648 		true,
1649 		NULL, NULL, NULL
1650 	},
1651 
1652 	{
1653 		{"syslog_split_messages", PGC_SIGHUP, LOGGING_WHERE,
1654 			gettext_noop("Split messages sent to syslog by lines and to fit into 1024 bytes."),
1655 			NULL
1656 		},
1657 		&syslog_split_messages,
1658 		true,
1659 		NULL, NULL, NULL
1660 	},
1661 
1662 	{
1663 		{"data_sync_retry", PGC_POSTMASTER, ERROR_HANDLING_OPTIONS,
1664 			gettext_noop("Whether to continue running after a failure to sync data files."),
1665 		},
1666 		&data_sync_retry,
1667 		false,
1668 		NULL, NULL, NULL
1669 	},
1670 
1671 	/* End-of-list marker */
1672 	{
1673 		{NULL, 0, 0, NULL, NULL}, NULL, false, NULL, NULL, NULL
1674 	}
1675 };
1676 
1677 
1678 static struct config_int ConfigureNamesInt[] =
1679 {
1680 	{
1681 		{"archive_timeout", PGC_SIGHUP, WAL_ARCHIVING,
1682 			gettext_noop("Forces a switch to the next xlog file if a "
1683 						 "new file has not been started within N seconds."),
1684 			NULL,
1685 			GUC_UNIT_S
1686 		},
1687 		&XLogArchiveTimeout,
1688 		0, 0, INT_MAX / 2,
1689 		NULL, NULL, NULL
1690 	},
1691 	{
1692 		{"post_auth_delay", PGC_BACKEND, DEVELOPER_OPTIONS,
1693 			gettext_noop("Waits N seconds on connection startup after authentication."),
1694 			gettext_noop("This allows attaching a debugger to the process."),
1695 			GUC_NOT_IN_SAMPLE | GUC_UNIT_S
1696 		},
1697 		&PostAuthDelay,
1698 		0, 0, INT_MAX / 1000000,
1699 		NULL, NULL, NULL
1700 	},
1701 	{
1702 		{"default_statistics_target", PGC_USERSET, QUERY_TUNING_OTHER,
1703 			gettext_noop("Sets the default statistics target."),
1704 			gettext_noop("This applies to table columns that have not had a "
1705 				"column-specific target set via ALTER TABLE SET STATISTICS.")
1706 		},
1707 		&default_statistics_target,
1708 		100, 1, 10000,
1709 		NULL, NULL, NULL
1710 	},
1711 	{
1712 		{"from_collapse_limit", PGC_USERSET, QUERY_TUNING_OTHER,
1713 			gettext_noop("Sets the FROM-list size beyond which subqueries "
1714 						 "are not collapsed."),
1715 			gettext_noop("The planner will merge subqueries into upper "
1716 				"queries if the resulting FROM list would have no more than "
1717 						 "this many items.")
1718 		},
1719 		&from_collapse_limit,
1720 		8, 1, INT_MAX,
1721 		NULL, NULL, NULL
1722 	},
1723 	{
1724 		{"join_collapse_limit", PGC_USERSET, QUERY_TUNING_OTHER,
1725 			gettext_noop("Sets the FROM-list size beyond which JOIN "
1726 						 "constructs are not flattened."),
1727 			gettext_noop("The planner will flatten explicit JOIN "
1728 						 "constructs into lists of FROM items whenever a "
1729 						 "list of no more than this many items would result.")
1730 		},
1731 		&join_collapse_limit,
1732 		8, 1, INT_MAX,
1733 		NULL, NULL, NULL
1734 	},
1735 	{
1736 		{"geqo_threshold", PGC_USERSET, QUERY_TUNING_GEQO,
1737 			gettext_noop("Sets the threshold of FROM items beyond which GEQO is used."),
1738 			NULL
1739 		},
1740 		&geqo_threshold,
1741 		12, 2, INT_MAX,
1742 		NULL, NULL, NULL
1743 	},
1744 	{
1745 		{"geqo_effort", PGC_USERSET, QUERY_TUNING_GEQO,
1746 			gettext_noop("GEQO: effort is used to set the default for other GEQO parameters."),
1747 			NULL
1748 		},
1749 		&Geqo_effort,
1750 		DEFAULT_GEQO_EFFORT, MIN_GEQO_EFFORT, MAX_GEQO_EFFORT,
1751 		NULL, NULL, NULL
1752 	},
1753 	{
1754 		{"geqo_pool_size", PGC_USERSET, QUERY_TUNING_GEQO,
1755 			gettext_noop("GEQO: number of individuals in the population."),
1756 			gettext_noop("Zero selects a suitable default value.")
1757 		},
1758 		&Geqo_pool_size,
1759 		0, 0, INT_MAX,
1760 		NULL, NULL, NULL
1761 	},
1762 	{
1763 		{"geqo_generations", PGC_USERSET, QUERY_TUNING_GEQO,
1764 			gettext_noop("GEQO: number of iterations of the algorithm."),
1765 			gettext_noop("Zero selects a suitable default value.")
1766 		},
1767 		&Geqo_generations,
1768 		0, 0, INT_MAX,
1769 		NULL, NULL, NULL
1770 	},
1771 
1772 	{
1773 		/* This is PGC_SUSET to prevent hiding from log_lock_waits. */
1774 		{"deadlock_timeout", PGC_SUSET, LOCK_MANAGEMENT,
1775 			gettext_noop("Sets the time to wait on a lock before checking for deadlock."),
1776 			NULL,
1777 			GUC_UNIT_MS
1778 		},
1779 		&DeadlockTimeout,
1780 		1000, 1, INT_MAX,
1781 		NULL, NULL, NULL
1782 	},
1783 
1784 	{
1785 		{"max_standby_archive_delay", PGC_SIGHUP, REPLICATION_STANDBY,
1786 			gettext_noop("Sets the maximum delay before canceling queries when a hot standby server is processing archived WAL data."),
1787 			NULL,
1788 			GUC_UNIT_MS
1789 		},
1790 		&max_standby_archive_delay,
1791 		30 * 1000, -1, INT_MAX,
1792 		NULL, NULL, NULL
1793 	},
1794 
1795 	{
1796 		{"max_standby_streaming_delay", PGC_SIGHUP, REPLICATION_STANDBY,
1797 			gettext_noop("Sets the maximum delay before canceling queries when a hot standby server is processing streamed WAL data."),
1798 			NULL,
1799 			GUC_UNIT_MS
1800 		},
1801 		&max_standby_streaming_delay,
1802 		30 * 1000, -1, INT_MAX,
1803 		NULL, NULL, NULL
1804 	},
1805 
1806 	{
1807 		{"wal_receiver_status_interval", PGC_SIGHUP, REPLICATION_STANDBY,
1808 			gettext_noop("Sets the maximum interval between WAL receiver status reports to the primary."),
1809 			NULL,
1810 			GUC_UNIT_S
1811 		},
1812 		&wal_receiver_status_interval,
1813 		10, 0, INT_MAX / 1000,
1814 		NULL, NULL, NULL
1815 	},
1816 
1817 	{
1818 		{"wal_receiver_timeout", PGC_SIGHUP, REPLICATION_STANDBY,
1819 			gettext_noop("Sets the maximum wait time to receive data from the primary."),
1820 			NULL,
1821 			GUC_UNIT_MS
1822 		},
1823 		&wal_receiver_timeout,
1824 		60 * 1000, 0, INT_MAX,
1825 		NULL, NULL, NULL
1826 	},
1827 
1828 	{
1829 		{"max_connections", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
1830 			gettext_noop("Sets the maximum number of concurrent connections."),
1831 			NULL
1832 		},
1833 		&MaxConnections,
1834 		100, 1, MAX_BACKENDS,
1835 		check_maxconnections, NULL, NULL
1836 	},
1837 
1838 	{
1839 		{"superuser_reserved_connections", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
1840 			gettext_noop("Sets the number of connection slots reserved for superusers."),
1841 			NULL
1842 		},
1843 		&ReservedBackends,
1844 		3, 0, MAX_BACKENDS,
1845 		NULL, NULL, NULL
1846 	},
1847 
1848 	/*
1849 	 * We sometimes multiply the number of shared buffers by two without
1850 	 * checking for overflow, so we mustn't allow more than INT_MAX / 2.
1851 	 */
1852 	{
1853 		{"shared_buffers", PGC_POSTMASTER, RESOURCES_MEM,
1854 			gettext_noop("Sets the number of shared memory buffers used by the server."),
1855 			NULL,
1856 			GUC_UNIT_BLOCKS
1857 		},
1858 		&NBuffers,
1859 		1024, 16, INT_MAX / 2,
1860 		NULL, NULL, NULL
1861 	},
1862 
1863 	{
1864 		{"temp_buffers", PGC_USERSET, RESOURCES_MEM,
1865 			gettext_noop("Sets the maximum number of temporary buffers used by each session."),
1866 			NULL,
1867 			GUC_UNIT_BLOCKS
1868 		},
1869 		&num_temp_buffers,
1870 		1024, 100, INT_MAX / 2,
1871 		check_temp_buffers, NULL, NULL
1872 	},
1873 
1874 	{
1875 		{"port", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
1876 			gettext_noop("Sets the TCP port the server listens on."),
1877 			NULL
1878 		},
1879 		&PostPortNumber,
1880 		DEF_PGPORT, 1, 65535,
1881 		NULL, NULL, NULL
1882 	},
1883 
1884 	{
1885 		{"unix_socket_permissions", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
1886 			gettext_noop("Sets the access permissions of the Unix-domain socket."),
1887 			gettext_noop("Unix-domain sockets use the usual Unix file system "
1888 						 "permission set. The parameter value is expected "
1889 						 "to be a numeric mode specification in the form "
1890 						 "accepted by the chmod and umask system calls. "
1891 						 "(To use the customary octal format the number must "
1892 						 "start with a 0 (zero).)")
1893 		},
1894 		&Unix_socket_permissions,
1895 		0777, 0000, 0777,
1896 		NULL, NULL, show_unix_socket_permissions
1897 	},
1898 
1899 	{
1900 		{"log_file_mode", PGC_SIGHUP, LOGGING_WHERE,
1901 			gettext_noop("Sets the file permissions for log files."),
1902 			gettext_noop("The parameter value is expected "
1903 						 "to be a numeric mode specification in the form "
1904 						 "accepted by the chmod and umask system calls. "
1905 						 "(To use the customary octal format the number must "
1906 						 "start with a 0 (zero).)")
1907 		},
1908 		&Log_file_mode,
1909 		0600, 0000, 0777,
1910 		NULL, NULL, show_log_file_mode
1911 	},
1912 
1913 	{
1914 		{"work_mem", PGC_USERSET, RESOURCES_MEM,
1915 			gettext_noop("Sets the maximum memory to be used for query workspaces."),
1916 			gettext_noop("This much memory can be used by each internal "
1917 						 "sort operation and hash table before switching to "
1918 						 "temporary disk files."),
1919 			GUC_UNIT_KB
1920 		},
1921 		&work_mem,
1922 		4096, 64, MAX_KILOBYTES,
1923 		NULL, NULL, NULL
1924 	},
1925 
1926 	{
1927 		{"maintenance_work_mem", PGC_USERSET, RESOURCES_MEM,
1928 			gettext_noop("Sets the maximum memory to be used for maintenance operations."),
1929 			gettext_noop("This includes operations such as VACUUM and CREATE INDEX."),
1930 			GUC_UNIT_KB
1931 		},
1932 		&maintenance_work_mem,
1933 		65536, 1024, MAX_KILOBYTES,
1934 		NULL, NULL, NULL
1935 	},
1936 
1937 	{
1938 		{"replacement_sort_tuples", PGC_USERSET, RESOURCES_MEM,
1939 			gettext_noop("Sets the maximum number of tuples to be sorted using replacement selection."),
1940 			gettext_noop("When more tuples than this are present, quicksort will be used.")
1941 		},
1942 		&replacement_sort_tuples,
1943 		150000, 0, INT_MAX,
1944 		NULL, NULL, NULL
1945 	},
1946 
1947 	/*
1948 	 * We use the hopefully-safely-small value of 100kB as the compiled-in
1949 	 * default for max_stack_depth.  InitializeGUCOptions will increase it if
1950 	 * possible, depending on the actual platform-specific stack limit.
1951 	 */
1952 	{
1953 		{"max_stack_depth", PGC_SUSET, RESOURCES_MEM,
1954 			gettext_noop("Sets the maximum stack depth, in kilobytes."),
1955 			NULL,
1956 			GUC_UNIT_KB
1957 		},
1958 		&max_stack_depth,
1959 		100, 100, MAX_KILOBYTES,
1960 		check_max_stack_depth, assign_max_stack_depth, NULL
1961 	},
1962 
1963 	{
1964 		{"temp_file_limit", PGC_SUSET, RESOURCES_DISK,
1965 			gettext_noop("Limits the total size of all temporary files used by each process."),
1966 			gettext_noop("-1 means no limit."),
1967 			GUC_UNIT_KB
1968 		},
1969 		&temp_file_limit,
1970 		-1, -1, INT_MAX,
1971 		NULL, NULL, NULL
1972 	},
1973 
1974 	{
1975 		{"vacuum_cost_page_hit", PGC_USERSET, RESOURCES_VACUUM_DELAY,
1976 			gettext_noop("Vacuum cost for a page found in the buffer cache."),
1977 			NULL
1978 		},
1979 		&VacuumCostPageHit,
1980 		1, 0, 10000,
1981 		NULL, NULL, NULL
1982 	},
1983 
1984 	{
1985 		{"vacuum_cost_page_miss", PGC_USERSET, RESOURCES_VACUUM_DELAY,
1986 			gettext_noop("Vacuum cost for a page not found in the buffer cache."),
1987 			NULL
1988 		},
1989 		&VacuumCostPageMiss,
1990 		10, 0, 10000,
1991 		NULL, NULL, NULL
1992 	},
1993 
1994 	{
1995 		{"vacuum_cost_page_dirty", PGC_USERSET, RESOURCES_VACUUM_DELAY,
1996 			gettext_noop("Vacuum cost for a page dirtied by vacuum."),
1997 			NULL
1998 		},
1999 		&VacuumCostPageDirty,
2000 		20, 0, 10000,
2001 		NULL, NULL, NULL
2002 	},
2003 
2004 	{
2005 		{"vacuum_cost_limit", PGC_USERSET, RESOURCES_VACUUM_DELAY,
2006 			gettext_noop("Vacuum cost amount available before napping."),
2007 			NULL
2008 		},
2009 		&VacuumCostLimit,
2010 		200, 1, 10000,
2011 		NULL, NULL, NULL
2012 	},
2013 
2014 	{
2015 		{"vacuum_cost_delay", PGC_USERSET, RESOURCES_VACUUM_DELAY,
2016 			gettext_noop("Vacuum cost delay in milliseconds."),
2017 			NULL,
2018 			GUC_UNIT_MS
2019 		},
2020 		&VacuumCostDelay,
2021 		0, 0, 100,
2022 		NULL, NULL, NULL
2023 	},
2024 
2025 	{
2026 		{"autovacuum_vacuum_cost_delay", PGC_SIGHUP, AUTOVACUUM,
2027 			gettext_noop("Vacuum cost delay in milliseconds, for autovacuum."),
2028 			NULL,
2029 			GUC_UNIT_MS
2030 		},
2031 		&autovacuum_vac_cost_delay,
2032 		20, -1, 100,
2033 		NULL, NULL, NULL
2034 	},
2035 
2036 	{
2037 		{"autovacuum_vacuum_cost_limit", PGC_SIGHUP, AUTOVACUUM,
2038 			gettext_noop("Vacuum cost amount available before napping, for autovacuum."),
2039 			NULL
2040 		},
2041 		&autovacuum_vac_cost_limit,
2042 		-1, -1, 10000,
2043 		NULL, NULL, NULL
2044 	},
2045 
2046 	{
2047 		{"max_files_per_process", PGC_POSTMASTER, RESOURCES_KERNEL,
2048 			gettext_noop("Sets the maximum number of simultaneously open files for each server process."),
2049 			NULL
2050 		},
2051 		&max_files_per_process,
2052 		1000, 25, INT_MAX,
2053 		NULL, NULL, NULL
2054 	},
2055 
2056 	/*
2057 	 * See also CheckRequiredParameterValues() if this parameter changes
2058 	 */
2059 	{
2060 		{"max_prepared_transactions", PGC_POSTMASTER, RESOURCES_MEM,
2061 			gettext_noop("Sets the maximum number of simultaneously prepared transactions."),
2062 			NULL
2063 		},
2064 		&max_prepared_xacts,
2065 		0, 0, MAX_BACKENDS,
2066 		NULL, NULL, NULL
2067 	},
2068 
2069 #ifdef LOCK_DEBUG
2070 	{
2071 		{"trace_lock_oidmin", PGC_SUSET, DEVELOPER_OPTIONS,
2072 			gettext_noop("Sets the minimum OID of tables for tracking locks."),
2073 			gettext_noop("Is used to avoid output on system tables."),
2074 			GUC_NOT_IN_SAMPLE
2075 		},
2076 		&Trace_lock_oidmin,
2077 		FirstNormalObjectId, 0, INT_MAX,
2078 		NULL, NULL, NULL
2079 	},
2080 	{
2081 		{"trace_lock_table", PGC_SUSET, DEVELOPER_OPTIONS,
2082 			gettext_noop("Sets the OID of the table with unconditionally lock tracing."),
2083 			NULL,
2084 			GUC_NOT_IN_SAMPLE
2085 		},
2086 		&Trace_lock_table,
2087 		0, 0, INT_MAX,
2088 		NULL, NULL, NULL
2089 	},
2090 #endif
2091 
2092 	{
2093 		{"statement_timeout", PGC_USERSET, CLIENT_CONN_STATEMENT,
2094 			gettext_noop("Sets the maximum allowed duration of any statement."),
2095 			gettext_noop("A value of 0 turns off the timeout."),
2096 			GUC_UNIT_MS
2097 		},
2098 		&StatementTimeout,
2099 		0, 0, INT_MAX,
2100 		NULL, NULL, NULL
2101 	},
2102 
2103 	{
2104 		{"lock_timeout", PGC_USERSET, CLIENT_CONN_STATEMENT,
2105 			gettext_noop("Sets the maximum allowed duration of any wait for a lock."),
2106 			gettext_noop("A value of 0 turns off the timeout."),
2107 			GUC_UNIT_MS
2108 		},
2109 		&LockTimeout,
2110 		0, 0, INT_MAX,
2111 		NULL, NULL, NULL
2112 	},
2113 
2114 	{
2115 		{"idle_in_transaction_session_timeout", PGC_USERSET, CLIENT_CONN_STATEMENT,
2116 			gettext_noop("Sets the maximum allowed duration of any idling transaction."),
2117 			gettext_noop("A value of 0 turns off the timeout."),
2118 			GUC_UNIT_MS
2119 		},
2120 		&IdleInTransactionSessionTimeout,
2121 		0, 0, INT_MAX,
2122 		NULL, NULL, NULL
2123 	},
2124 
2125 	{
2126 		{"vacuum_freeze_min_age", PGC_USERSET, CLIENT_CONN_STATEMENT,
2127 			gettext_noop("Minimum age at which VACUUM should freeze a table row."),
2128 			NULL
2129 		},
2130 		&vacuum_freeze_min_age,
2131 		50000000, 0, 1000000000,
2132 		NULL, NULL, NULL
2133 	},
2134 
2135 	{
2136 		{"vacuum_freeze_table_age", PGC_USERSET, CLIENT_CONN_STATEMENT,
2137 			gettext_noop("Age at which VACUUM should scan whole table to freeze tuples."),
2138 			NULL
2139 		},
2140 		&vacuum_freeze_table_age,
2141 		150000000, 0, 2000000000,
2142 		NULL, NULL, NULL
2143 	},
2144 
2145 	{
2146 		{"vacuum_multixact_freeze_min_age", PGC_USERSET, CLIENT_CONN_STATEMENT,
2147 			gettext_noop("Minimum age at which VACUUM should freeze a MultiXactId in a table row."),
2148 			NULL
2149 		},
2150 		&vacuum_multixact_freeze_min_age,
2151 		5000000, 0, 1000000000,
2152 		NULL, NULL, NULL
2153 	},
2154 
2155 	{
2156 		{"vacuum_multixact_freeze_table_age", PGC_USERSET, CLIENT_CONN_STATEMENT,
2157 			gettext_noop("Multixact age at which VACUUM should scan whole table to freeze tuples."),
2158 			NULL
2159 		},
2160 		&vacuum_multixact_freeze_table_age,
2161 		150000000, 0, 2000000000,
2162 		NULL, NULL, NULL
2163 	},
2164 
2165 	{
2166 		{"vacuum_defer_cleanup_age", PGC_SIGHUP, REPLICATION_MASTER,
2167 			gettext_noop("Number of transactions by which VACUUM and HOT cleanup should be deferred, if any."),
2168 			NULL
2169 		},
2170 		&vacuum_defer_cleanup_age,
2171 		0, 0, 1000000,
2172 		NULL, NULL, NULL
2173 	},
2174 
2175 	/*
2176 	 * See also CheckRequiredParameterValues() if this parameter changes
2177 	 */
2178 	{
2179 		{"max_locks_per_transaction", PGC_POSTMASTER, LOCK_MANAGEMENT,
2180 			gettext_noop("Sets the maximum number of locks per transaction."),
2181 			gettext_noop("The shared lock table is sized on the assumption that "
2182 			  "at most max_locks_per_transaction * max_connections distinct "
2183 						 "objects will need to be locked at any one time.")
2184 		},
2185 		&max_locks_per_xact,
2186 		64, 10, INT_MAX,
2187 		NULL, NULL, NULL
2188 	},
2189 
2190 	{
2191 		{"max_pred_locks_per_transaction", PGC_POSTMASTER, LOCK_MANAGEMENT,
2192 			gettext_noop("Sets the maximum number of predicate locks per transaction."),
2193 			gettext_noop("The shared predicate lock table is sized on the assumption that "
2194 						 "at most max_pred_locks_per_transaction * max_connections distinct "
2195 						 "objects will need to be locked at any one time.")
2196 		},
2197 		&max_predicate_locks_per_xact,
2198 		64, 10, INT_MAX,
2199 		NULL, NULL, NULL
2200 	},
2201 
2202 	{
2203 		{"authentication_timeout", PGC_SIGHUP, CONN_AUTH_SECURITY,
2204 			gettext_noop("Sets the maximum allowed time to complete client authentication."),
2205 			NULL,
2206 			GUC_UNIT_S
2207 		},
2208 		&AuthenticationTimeout,
2209 		60, 1, 600,
2210 		NULL, NULL, NULL
2211 	},
2212 
2213 	{
2214 		/* Not for general use */
2215 		{"pre_auth_delay", PGC_SIGHUP, DEVELOPER_OPTIONS,
2216 			gettext_noop("Waits N seconds on connection startup before authentication."),
2217 			gettext_noop("This allows attaching a debugger to the process."),
2218 			GUC_NOT_IN_SAMPLE | GUC_UNIT_S
2219 		},
2220 		&PreAuthDelay,
2221 		0, 0, 60,
2222 		NULL, NULL, NULL
2223 	},
2224 
2225 	{
2226 		{"wal_keep_segments", PGC_SIGHUP, REPLICATION_SENDING,
2227 			gettext_noop("Sets the number of WAL files held for standby servers."),
2228 			NULL
2229 		},
2230 		&wal_keep_segments,
2231 		0, 0, INT_MAX,
2232 		NULL, NULL, NULL
2233 	},
2234 
2235 	{
2236 		{"min_wal_size", PGC_SIGHUP, WAL_CHECKPOINTS,
2237 			gettext_noop("Sets the minimum size to shrink the WAL to."),
2238 			NULL,
2239 			GUC_UNIT_XSEGS
2240 		},
2241 		&min_wal_size,
2242 		5, 2, INT_MAX,
2243 		NULL, NULL, NULL
2244 	},
2245 
2246 	{
2247 		{"max_wal_size", PGC_SIGHUP, WAL_CHECKPOINTS,
2248 			gettext_noop("Sets the WAL size that triggers a checkpoint."),
2249 			NULL,
2250 			GUC_UNIT_XSEGS
2251 		},
2252 		&max_wal_size,
2253 		64, 2, INT_MAX,
2254 		NULL, assign_max_wal_size, NULL
2255 	},
2256 
2257 	{
2258 		{"checkpoint_timeout", PGC_SIGHUP, WAL_CHECKPOINTS,
2259 			gettext_noop("Sets the maximum time between automatic WAL checkpoints."),
2260 			NULL,
2261 			GUC_UNIT_S
2262 		},
2263 		&CheckPointTimeout,
2264 		300, 30, 86400,
2265 		NULL, NULL, NULL
2266 	},
2267 
2268 	{
2269 		{"checkpoint_warning", PGC_SIGHUP, WAL_CHECKPOINTS,
2270 			gettext_noop("Enables warnings if checkpoint segments are filled more "
2271 						 "frequently than this."),
2272 			gettext_noop("Write a message to the server log if checkpoints "
2273 			"caused by the filling of checkpoint segment files happens more "
2274 						 "frequently than this number of seconds. Zero turns off the warning."),
2275 			GUC_UNIT_S
2276 		},
2277 		&CheckPointWarning,
2278 		30, 0, INT_MAX,
2279 		NULL, NULL, NULL
2280 	},
2281 
2282 	{
2283 		{"checkpoint_flush_after", PGC_SIGHUP, WAL_CHECKPOINTS,
2284 			gettext_noop("Number of pages after which previously performed writes are flushed to disk."),
2285 			NULL,
2286 			GUC_UNIT_BLOCKS
2287 		},
2288 		&checkpoint_flush_after,
2289 		DEFAULT_CHECKPOINT_FLUSH_AFTER, 0, WRITEBACK_MAX_PENDING_FLUSHES,
2290 		NULL, NULL, NULL
2291 	},
2292 
2293 	{
2294 		{"wal_buffers", PGC_POSTMASTER, WAL_SETTINGS,
2295 			gettext_noop("Sets the number of disk-page buffers in shared memory for WAL."),
2296 			NULL,
2297 			GUC_UNIT_XBLOCKS
2298 		},
2299 		&XLOGbuffers,
2300 		-1, -1, (INT_MAX / XLOG_BLCKSZ),
2301 		check_wal_buffers, NULL, NULL
2302 	},
2303 
2304 	{
2305 		{"wal_writer_delay", PGC_SIGHUP, WAL_SETTINGS,
2306 			gettext_noop("Time between WAL flushes performed in the WAL writer."),
2307 			NULL,
2308 			GUC_UNIT_MS
2309 		},
2310 		&WalWriterDelay,
2311 		200, 1, 10000,
2312 		NULL, NULL, NULL
2313 	},
2314 
2315 	{
2316 		{"wal_writer_flush_after", PGC_SIGHUP, WAL_SETTINGS,
2317 			gettext_noop("Amount of WAL written out by WAL writer that triggers a flush."),
2318 			NULL,
2319 			GUC_UNIT_XBLOCKS
2320 		},
2321 		&WalWriterFlushAfter,
2322 		(1024*1024) / XLOG_BLCKSZ, 0, INT_MAX,
2323 		NULL, NULL, NULL
2324 	},
2325 
2326 	{
2327 		/* see max_connections */
2328 		{"max_wal_senders", PGC_POSTMASTER, REPLICATION_SENDING,
2329 			gettext_noop("Sets the maximum number of simultaneously running WAL sender processes."),
2330 			NULL
2331 		},
2332 		&max_wal_senders,
2333 		0, 0, MAX_BACKENDS,
2334 		NULL, NULL, NULL
2335 	},
2336 
2337 	{
2338 		/* see max_connections */
2339 		{"max_replication_slots", PGC_POSTMASTER, REPLICATION_SENDING,
2340 			gettext_noop("Sets the maximum number of simultaneously defined replication slots."),
2341 			NULL
2342 		},
2343 		&max_replication_slots,
2344 		0, 0, MAX_BACKENDS /* XXX? */ ,
2345 		NULL, NULL, NULL
2346 	},
2347 
2348 	{
2349 		{"wal_sender_timeout", PGC_SIGHUP, REPLICATION_SENDING,
2350 			gettext_noop("Sets the maximum time to wait for WAL replication."),
2351 			NULL,
2352 			GUC_UNIT_MS
2353 		},
2354 		&wal_sender_timeout,
2355 		60 * 1000, 0, INT_MAX,
2356 		NULL, NULL, NULL
2357 	},
2358 
2359 	{
2360 		{"commit_delay", PGC_SUSET, WAL_SETTINGS,
2361 			gettext_noop("Sets the delay in microseconds between transaction commit and "
2362 						 "flushing WAL to disk."),
2363 			NULL
2364 			/* we have no microseconds designation, so can't supply units here */
2365 		},
2366 		&CommitDelay,
2367 		0, 0, 100000,
2368 		NULL, NULL, NULL
2369 	},
2370 
2371 	{
2372 		{"commit_siblings", PGC_USERSET, WAL_SETTINGS,
2373 			gettext_noop("Sets the minimum concurrent open transactions before performing "
2374 						 "commit_delay."),
2375 			NULL
2376 		},
2377 		&CommitSiblings,
2378 		5, 0, 1000,
2379 		NULL, NULL, NULL
2380 	},
2381 
2382 	{
2383 		{"extra_float_digits", PGC_USERSET, CLIENT_CONN_LOCALE,
2384 			gettext_noop("Sets the number of digits displayed for floating-point values."),
2385 			gettext_noop("This affects real, double precision, and geometric data types. "
2386 			 "The parameter value is added to the standard number of digits "
2387 						 "(FLT_DIG or DBL_DIG as appropriate).")
2388 		},
2389 		&extra_float_digits,
2390 		0, -15, 3,
2391 		NULL, NULL, NULL
2392 	},
2393 
2394 	{
2395 		{"log_min_duration_statement", PGC_SUSET, LOGGING_WHEN,
2396 			gettext_noop("Sets the minimum execution time above which "
2397 						 "statements will be logged."),
2398 			gettext_noop("Zero prints all queries. -1 turns this feature off."),
2399 			GUC_UNIT_MS
2400 		},
2401 		&log_min_duration_statement,
2402 		-1, -1, INT_MAX,
2403 		NULL, NULL, NULL
2404 	},
2405 
2406 	{
2407 		{"log_autovacuum_min_duration", PGC_SIGHUP, LOGGING_WHAT,
2408 			gettext_noop("Sets the minimum execution time above which "
2409 						 "autovacuum actions will be logged."),
2410 			gettext_noop("Zero prints all actions. -1 turns autovacuum logging off."),
2411 			GUC_UNIT_MS
2412 		},
2413 		&Log_autovacuum_min_duration,
2414 		-1, -1, INT_MAX,
2415 		NULL, NULL, NULL
2416 	},
2417 
2418 	{
2419 		{"bgwriter_delay", PGC_SIGHUP, RESOURCES_BGWRITER,
2420 			gettext_noop("Background writer sleep time between rounds."),
2421 			NULL,
2422 			GUC_UNIT_MS
2423 		},
2424 		&BgWriterDelay,
2425 		200, 10, 10000,
2426 		NULL, NULL, NULL
2427 	},
2428 
2429 	{
2430 		{"bgwriter_lru_maxpages", PGC_SIGHUP, RESOURCES_BGWRITER,
2431 			gettext_noop("Background writer maximum number of LRU pages to flush per round."),
2432 			NULL
2433 		},
2434 		&bgwriter_lru_maxpages,
2435 		100, 0, 1000,
2436 		NULL, NULL, NULL
2437 	},
2438 
2439 	{
2440 		{"bgwriter_flush_after", PGC_SIGHUP, RESOURCES_BGWRITER,
2441 			gettext_noop("Number of pages after which previously performed writes are flushed to disk."),
2442 			NULL,
2443 			GUC_UNIT_BLOCKS
2444 		},
2445 		&bgwriter_flush_after,
2446 		DEFAULT_BGWRITER_FLUSH_AFTER, 0, WRITEBACK_MAX_PENDING_FLUSHES,
2447 		NULL, NULL, NULL
2448 	},
2449 
2450 	{
2451 		{"effective_io_concurrency",
2452 			PGC_USERSET,
2453 			RESOURCES_ASYNCHRONOUS,
2454 			gettext_noop("Number of simultaneous requests that can be handled efficiently by the disk subsystem."),
2455 			gettext_noop("For RAID arrays, this should be approximately the number of drive spindles in the array.")
2456 		},
2457 		&effective_io_concurrency,
2458 #ifdef USE_PREFETCH
2459 		1, 0, MAX_IO_CONCURRENCY,
2460 #else
2461 		0, 0, 0,
2462 #endif
2463 		check_effective_io_concurrency, assign_effective_io_concurrency, NULL
2464 	},
2465 
2466 	{
2467 		{"backend_flush_after", PGC_USERSET, RESOURCES_ASYNCHRONOUS,
2468 			gettext_noop("Number of pages after which previously performed writes are flushed to disk."),
2469 			NULL,
2470 			GUC_UNIT_BLOCKS
2471 		},
2472 		&backend_flush_after,
2473 		DEFAULT_BACKEND_FLUSH_AFTER, 0, WRITEBACK_MAX_PENDING_FLUSHES,
2474 		NULL, NULL, NULL
2475 	},
2476 
2477 	{
2478 		{"max_worker_processes",
2479 			PGC_POSTMASTER,
2480 			RESOURCES_ASYNCHRONOUS,
2481 			gettext_noop("Maximum number of concurrent worker processes."),
2482 			NULL,
2483 		},
2484 		&max_worker_processes,
2485 		8, 0, MAX_BACKENDS,
2486 		check_max_worker_processes, NULL, NULL
2487 	},
2488 
2489 	{
2490 		{"log_rotation_age", PGC_SIGHUP, LOGGING_WHERE,
2491 			gettext_noop("Automatic log file rotation will occur after N minutes."),
2492 			NULL,
2493 			GUC_UNIT_MIN
2494 		},
2495 		&Log_RotationAge,
2496 		HOURS_PER_DAY * MINS_PER_HOUR, 0, INT_MAX / SECS_PER_MINUTE,
2497 		NULL, NULL, NULL
2498 	},
2499 
2500 	{
2501 		{"log_rotation_size", PGC_SIGHUP, LOGGING_WHERE,
2502 			gettext_noop("Automatic log file rotation will occur after N kilobytes."),
2503 			NULL,
2504 			GUC_UNIT_KB
2505 		},
2506 		&Log_RotationSize,
2507 		10 * 1024, 0, INT_MAX / 1024,
2508 		NULL, NULL, NULL
2509 	},
2510 
2511 	{
2512 		{"max_function_args", PGC_INTERNAL, PRESET_OPTIONS,
2513 			gettext_noop("Shows the maximum number of function arguments."),
2514 			NULL,
2515 			GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2516 		},
2517 		&max_function_args,
2518 		FUNC_MAX_ARGS, FUNC_MAX_ARGS, FUNC_MAX_ARGS,
2519 		NULL, NULL, NULL
2520 	},
2521 
2522 	{
2523 		{"max_index_keys", PGC_INTERNAL, PRESET_OPTIONS,
2524 			gettext_noop("Shows the maximum number of index keys."),
2525 			NULL,
2526 			GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2527 		},
2528 		&max_index_keys,
2529 		INDEX_MAX_KEYS, INDEX_MAX_KEYS, INDEX_MAX_KEYS,
2530 		NULL, NULL, NULL
2531 	},
2532 
2533 	{
2534 		{"max_identifier_length", PGC_INTERNAL, PRESET_OPTIONS,
2535 			gettext_noop("Shows the maximum identifier length."),
2536 			NULL,
2537 			GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2538 		},
2539 		&max_identifier_length,
2540 		NAMEDATALEN - 1, NAMEDATALEN - 1, NAMEDATALEN - 1,
2541 		NULL, NULL, NULL
2542 	},
2543 
2544 	{
2545 		{"block_size", PGC_INTERNAL, PRESET_OPTIONS,
2546 			gettext_noop("Shows the size of a disk block."),
2547 			NULL,
2548 			GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2549 		},
2550 		&block_size,
2551 		BLCKSZ, BLCKSZ, BLCKSZ,
2552 		NULL, NULL, NULL
2553 	},
2554 
2555 	{
2556 		{"segment_size", PGC_INTERNAL, PRESET_OPTIONS,
2557 			gettext_noop("Shows the number of pages per disk file."),
2558 			NULL,
2559 			GUC_UNIT_BLOCKS | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2560 		},
2561 		&segment_size,
2562 		RELSEG_SIZE, RELSEG_SIZE, RELSEG_SIZE,
2563 		NULL, NULL, NULL
2564 	},
2565 
2566 	{
2567 		{"wal_block_size", PGC_INTERNAL, PRESET_OPTIONS,
2568 			gettext_noop("Shows the block size in the write ahead log."),
2569 			NULL,
2570 			GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2571 		},
2572 		&wal_block_size,
2573 		XLOG_BLCKSZ, XLOG_BLCKSZ, XLOG_BLCKSZ,
2574 		NULL, NULL, NULL
2575 	},
2576 
2577 	{
2578 		{"wal_retrieve_retry_interval", PGC_SIGHUP, REPLICATION_STANDBY,
2579 			gettext_noop("Sets the time to wait before retrying to retrieve WAL "
2580 						 "after a failed attempt."),
2581 			NULL,
2582 			GUC_UNIT_MS
2583 		},
2584 		&wal_retrieve_retry_interval,
2585 		5000, 1, INT_MAX,
2586 		NULL, NULL, NULL
2587 	},
2588 
2589 	{
2590 		{"wal_segment_size", PGC_INTERNAL, PRESET_OPTIONS,
2591 			gettext_noop("Shows the number of pages per write ahead log segment."),
2592 			NULL,
2593 			GUC_UNIT_XBLOCKS | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2594 		},
2595 		&wal_segment_size,
2596 		(XLOG_SEG_SIZE / XLOG_BLCKSZ),
2597 		(XLOG_SEG_SIZE / XLOG_BLCKSZ),
2598 		(XLOG_SEG_SIZE / XLOG_BLCKSZ),
2599 		NULL, NULL, NULL
2600 	},
2601 
2602 	{
2603 		{"autovacuum_naptime", PGC_SIGHUP, AUTOVACUUM,
2604 			gettext_noop("Time to sleep between autovacuum runs."),
2605 			NULL,
2606 			GUC_UNIT_S
2607 		},
2608 		&autovacuum_naptime,
2609 		60, 1, INT_MAX / 1000,
2610 		NULL, NULL, NULL
2611 	},
2612 	{
2613 		{"autovacuum_vacuum_threshold", PGC_SIGHUP, AUTOVACUUM,
2614 			gettext_noop("Minimum number of tuple updates or deletes prior to vacuum."),
2615 			NULL
2616 		},
2617 		&autovacuum_vac_thresh,
2618 		50, 0, INT_MAX,
2619 		NULL, NULL, NULL
2620 	},
2621 	{
2622 		{"autovacuum_analyze_threshold", PGC_SIGHUP, AUTOVACUUM,
2623 			gettext_noop("Minimum number of tuple inserts, updates, or deletes prior to analyze."),
2624 			NULL
2625 		},
2626 		&autovacuum_anl_thresh,
2627 		50, 0, INT_MAX,
2628 		NULL, NULL, NULL
2629 	},
2630 	{
2631 		/* see varsup.c for why this is PGC_POSTMASTER not PGC_SIGHUP */
2632 		{"autovacuum_freeze_max_age", PGC_POSTMASTER, AUTOVACUUM,
2633 			gettext_noop("Age at which to autovacuum a table to prevent transaction ID wraparound."),
2634 			NULL
2635 		},
2636 		&autovacuum_freeze_max_age,
2637 		/* see pg_resetxlog if you change the upper-limit value */
2638 		200000000, 100000, 2000000000,
2639 		NULL, NULL, NULL
2640 	},
2641 	{
2642 		/* see multixact.c for why this is PGC_POSTMASTER not PGC_SIGHUP */
2643 		{"autovacuum_multixact_freeze_max_age", PGC_POSTMASTER, AUTOVACUUM,
2644 			gettext_noop("Multixact age at which to autovacuum a table to prevent multixact wraparound."),
2645 			NULL
2646 		},
2647 		&autovacuum_multixact_freeze_max_age,
2648 		400000000, 10000, 2000000000,
2649 		NULL, NULL, NULL
2650 	},
2651 	{
2652 		/* see max_connections */
2653 		{"autovacuum_max_workers", PGC_POSTMASTER, AUTOVACUUM,
2654 			gettext_noop("Sets the maximum number of simultaneously running autovacuum worker processes."),
2655 			NULL
2656 		},
2657 		&autovacuum_max_workers,
2658 		3, 1, MAX_BACKENDS,
2659 		check_autovacuum_max_workers, NULL, NULL
2660 	},
2661 
2662 	{
2663 		{"max_parallel_workers_per_gather", PGC_USERSET, RESOURCES_ASYNCHRONOUS,
2664 			gettext_noop("Sets the maximum number of parallel processes per executor node."),
2665 			NULL
2666 		},
2667 		&max_parallel_workers_per_gather,
2668 		0, 0, 1024,
2669 		NULL, NULL, NULL
2670 	},
2671 
2672 	{
2673 		{"autovacuum_work_mem", PGC_SIGHUP, RESOURCES_MEM,
2674 			gettext_noop("Sets the maximum memory to be used by each autovacuum worker process."),
2675 			NULL,
2676 			GUC_UNIT_KB
2677 		},
2678 		&autovacuum_work_mem,
2679 		-1, -1, MAX_KILOBYTES,
2680 		check_autovacuum_work_mem, NULL, NULL
2681 	},
2682 
2683 	{
2684 		{"old_snapshot_threshold", PGC_POSTMASTER, RESOURCES_ASYNCHRONOUS,
2685 			gettext_noop("Time before a snapshot is too old to read pages changed after the snapshot was taken."),
2686 			gettext_noop("A value of -1 disables this feature."),
2687 			GUC_UNIT_MIN
2688 		},
2689 		&old_snapshot_threshold,
2690 		-1, -1, MINS_PER_HOUR * HOURS_PER_DAY * 60,
2691 		NULL, NULL, NULL
2692 	},
2693 
2694 	{
2695 		{"tcp_keepalives_idle", PGC_USERSET, CLIENT_CONN_OTHER,
2696 			gettext_noop("Time between issuing TCP keepalives."),
2697 			gettext_noop("A value of 0 uses the system default."),
2698 			GUC_UNIT_S
2699 		},
2700 		&tcp_keepalives_idle,
2701 		0, 0, INT_MAX,
2702 		NULL, assign_tcp_keepalives_idle, show_tcp_keepalives_idle
2703 	},
2704 
2705 	{
2706 		{"tcp_keepalives_interval", PGC_USERSET, CLIENT_CONN_OTHER,
2707 			gettext_noop("Time between TCP keepalive retransmits."),
2708 			gettext_noop("A value of 0 uses the system default."),
2709 			GUC_UNIT_S
2710 		},
2711 		&tcp_keepalives_interval,
2712 		0, 0, INT_MAX,
2713 		NULL, assign_tcp_keepalives_interval, show_tcp_keepalives_interval
2714 	},
2715 
2716 	{
2717 		{"ssl_renegotiation_limit", PGC_USERSET, CONN_AUTH_SECURITY,
2718 			gettext_noop("SSL renegotiation is no longer supported; this can only be 0."),
2719 			NULL,
2720 			GUC_NO_SHOW_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE,
2721 		},
2722 		&ssl_renegotiation_limit,
2723 		0, 0, 0,
2724 		NULL, NULL, NULL
2725 	},
2726 
2727 	{
2728 		{"tcp_keepalives_count", PGC_USERSET, CLIENT_CONN_OTHER,
2729 			gettext_noop("Maximum number of TCP keepalive retransmits."),
2730 			gettext_noop("This controls the number of consecutive keepalive retransmits that can be "
2731 						 "lost before a connection is considered dead. A value of 0 uses the "
2732 						 "system default."),
2733 		},
2734 		&tcp_keepalives_count,
2735 		0, 0, INT_MAX,
2736 		NULL, assign_tcp_keepalives_count, show_tcp_keepalives_count
2737 	},
2738 
2739 	{
2740 		{"gin_fuzzy_search_limit", PGC_USERSET, CLIENT_CONN_OTHER,
2741 			gettext_noop("Sets the maximum allowed result for exact search by GIN."),
2742 			NULL,
2743 			0
2744 		},
2745 		&GinFuzzySearchLimit,
2746 		0, 0, INT_MAX,
2747 		NULL, NULL, NULL
2748 	},
2749 
2750 	{
2751 		{"effective_cache_size", PGC_USERSET, QUERY_TUNING_COST,
2752 			gettext_noop("Sets the planner's assumption about the total size of the data caches."),
2753 			gettext_noop("That is, the total size of the caches (kernel cache and shared buffers) used for PostgreSQL data files. "
2754 						 "This is measured in disk pages, which are normally 8 kB each."),
2755 			GUC_UNIT_BLOCKS,
2756 		},
2757 		&effective_cache_size,
2758 		DEFAULT_EFFECTIVE_CACHE_SIZE, 1, INT_MAX,
2759 		NULL, NULL, NULL
2760 	},
2761 
2762 	{
2763 		{"min_parallel_relation_size", PGC_USERSET, QUERY_TUNING_COST,
2764 			gettext_noop("Sets the minimum size of relations to be considered for parallel scan."),
2765 			NULL,
2766 			GUC_UNIT_BLOCKS,
2767 		},
2768 		&min_parallel_relation_size,
2769 		(8 * 1024 * 1024) / BLCKSZ, 0, INT_MAX / 3,
2770 		NULL, NULL, NULL
2771 	},
2772 
2773 	{
2774 		/* Can't be set in postgresql.conf */
2775 		{"server_version_num", PGC_INTERNAL, PRESET_OPTIONS,
2776 			gettext_noop("Shows the server version as an integer."),
2777 			NULL,
2778 			GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2779 		},
2780 		&server_version_num,
2781 		PG_VERSION_NUM, PG_VERSION_NUM, PG_VERSION_NUM,
2782 		NULL, NULL, NULL
2783 	},
2784 
2785 	{
2786 		{"log_temp_files", PGC_SUSET, LOGGING_WHAT,
2787 			gettext_noop("Log the use of temporary files larger than this number of kilobytes."),
2788 			gettext_noop("Zero logs all files. The default is -1 (turning this feature off)."),
2789 			GUC_UNIT_KB
2790 		},
2791 		&log_temp_files,
2792 		-1, -1, INT_MAX,
2793 		NULL, NULL, NULL
2794 	},
2795 
2796 	{
2797 		{"track_activity_query_size", PGC_POSTMASTER, RESOURCES_MEM,
2798 			gettext_noop("Sets the size reserved for pg_stat_activity.query, in bytes."),
2799 			NULL,
2800 
2801 			/*
2802 			 * There is no _bytes_ unit, so the user can't supply units for
2803 			 * this.
2804 			 */
2805 		},
2806 		&pgstat_track_activity_query_size,
2807 		1024, 100, 102400,
2808 		NULL, NULL, NULL
2809 	},
2810 
2811 	{
2812 		{"gin_pending_list_limit", PGC_USERSET, CLIENT_CONN_STATEMENT,
2813 			gettext_noop("Sets the maximum size of the pending list for GIN index."),
2814 			NULL,
2815 			GUC_UNIT_KB
2816 		},
2817 		&gin_pending_list_limit,
2818 		4096, 64, MAX_KILOBYTES,
2819 		NULL, NULL, NULL
2820 	},
2821 
2822 	/* End-of-list marker */
2823 	{
2824 		{NULL, 0, 0, NULL, NULL}, NULL, 0, 0, 0, NULL, NULL, NULL
2825 	}
2826 };
2827 
2828 
2829 static struct config_real ConfigureNamesReal[] =
2830 {
2831 	{
2832 		{"seq_page_cost", PGC_USERSET, QUERY_TUNING_COST,
2833 			gettext_noop("Sets the planner's estimate of the cost of a "
2834 						 "sequentially fetched disk page."),
2835 			NULL
2836 		},
2837 		&seq_page_cost,
2838 		DEFAULT_SEQ_PAGE_COST, 0, DBL_MAX,
2839 		NULL, NULL, NULL
2840 	},
2841 	{
2842 		{"random_page_cost", PGC_USERSET, QUERY_TUNING_COST,
2843 			gettext_noop("Sets the planner's estimate of the cost of a "
2844 						 "nonsequentially fetched disk page."),
2845 			NULL
2846 		},
2847 		&random_page_cost,
2848 		DEFAULT_RANDOM_PAGE_COST, 0, DBL_MAX,
2849 		NULL, NULL, NULL
2850 	},
2851 	{
2852 		{"cpu_tuple_cost", PGC_USERSET, QUERY_TUNING_COST,
2853 			gettext_noop("Sets the planner's estimate of the cost of "
2854 						 "processing each tuple (row)."),
2855 			NULL
2856 		},
2857 		&cpu_tuple_cost,
2858 		DEFAULT_CPU_TUPLE_COST, 0, DBL_MAX,
2859 		NULL, NULL, NULL
2860 	},
2861 	{
2862 		{"cpu_index_tuple_cost", PGC_USERSET, QUERY_TUNING_COST,
2863 			gettext_noop("Sets the planner's estimate of the cost of "
2864 						 "processing each index entry during an index scan."),
2865 			NULL
2866 		},
2867 		&cpu_index_tuple_cost,
2868 		DEFAULT_CPU_INDEX_TUPLE_COST, 0, DBL_MAX,
2869 		NULL, NULL, NULL
2870 	},
2871 	{
2872 		{"cpu_operator_cost", PGC_USERSET, QUERY_TUNING_COST,
2873 			gettext_noop("Sets the planner's estimate of the cost of "
2874 						 "processing each operator or function call."),
2875 			NULL
2876 		},
2877 		&cpu_operator_cost,
2878 		DEFAULT_CPU_OPERATOR_COST, 0, DBL_MAX,
2879 		NULL, NULL, NULL
2880 	},
2881 	{
2882 		{"parallel_tuple_cost", PGC_USERSET, QUERY_TUNING_COST,
2883 			gettext_noop("Sets the planner's estimate of the cost of "
2884 				  "passing each tuple (row) from worker to master backend."),
2885 			NULL
2886 		},
2887 		&parallel_tuple_cost,
2888 		DEFAULT_PARALLEL_TUPLE_COST, 0, DBL_MAX,
2889 		NULL, NULL, NULL
2890 	},
2891 	{
2892 		{"parallel_setup_cost", PGC_USERSET, QUERY_TUNING_COST,
2893 			gettext_noop("Sets the planner's estimate of the cost of "
2894 						 "starting up worker processes for parallel query."),
2895 			NULL
2896 		},
2897 		&parallel_setup_cost,
2898 		DEFAULT_PARALLEL_SETUP_COST, 0, DBL_MAX,
2899 		NULL, NULL, NULL
2900 	},
2901 
2902 	{
2903 		{"cursor_tuple_fraction", PGC_USERSET, QUERY_TUNING_OTHER,
2904 			gettext_noop("Sets the planner's estimate of the fraction of "
2905 						 "a cursor's rows that will be retrieved."),
2906 			NULL
2907 		},
2908 		&cursor_tuple_fraction,
2909 		DEFAULT_CURSOR_TUPLE_FRACTION, 0.0, 1.0,
2910 		NULL, NULL, NULL
2911 	},
2912 
2913 	{
2914 		{"geqo_selection_bias", PGC_USERSET, QUERY_TUNING_GEQO,
2915 			gettext_noop("GEQO: selective pressure within the population."),
2916 			NULL
2917 		},
2918 		&Geqo_selection_bias,
2919 		DEFAULT_GEQO_SELECTION_BIAS,
2920 		MIN_GEQO_SELECTION_BIAS, MAX_GEQO_SELECTION_BIAS,
2921 		NULL, NULL, NULL
2922 	},
2923 	{
2924 		{"geqo_seed", PGC_USERSET, QUERY_TUNING_GEQO,
2925 			gettext_noop("GEQO: seed for random path selection."),
2926 			NULL
2927 		},
2928 		&Geqo_seed,
2929 		0.0, 0.0, 1.0,
2930 		NULL, NULL, NULL
2931 	},
2932 
2933 	{
2934 		{"bgwriter_lru_multiplier", PGC_SIGHUP, RESOURCES_BGWRITER,
2935 			gettext_noop("Multiple of the average buffer usage to free per round."),
2936 			NULL
2937 		},
2938 		&bgwriter_lru_multiplier,
2939 		2.0, 0.0, 10.0,
2940 		NULL, NULL, NULL
2941 	},
2942 
2943 	{
2944 		{"seed", PGC_USERSET, UNGROUPED,
2945 			gettext_noop("Sets the seed for random-number generation."),
2946 			NULL,
2947 			GUC_NO_SHOW_ALL | GUC_NO_RESET_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2948 		},
2949 		&phony_random_seed,
2950 		0.0, -1.0, 1.0,
2951 		check_random_seed, assign_random_seed, show_random_seed
2952 	},
2953 
2954 	{
2955 		{"autovacuum_vacuum_scale_factor", PGC_SIGHUP, AUTOVACUUM,
2956 			gettext_noop("Number of tuple updates or deletes prior to vacuum as a fraction of reltuples."),
2957 			NULL
2958 		},
2959 		&autovacuum_vac_scale,
2960 		0.2, 0.0, 100.0,
2961 		NULL, NULL, NULL
2962 	},
2963 	{
2964 		{"autovacuum_analyze_scale_factor", PGC_SIGHUP, AUTOVACUUM,
2965 			gettext_noop("Number of tuple inserts, updates, or deletes prior to analyze as a fraction of reltuples."),
2966 			NULL
2967 		},
2968 		&autovacuum_anl_scale,
2969 		0.1, 0.0, 100.0,
2970 		NULL, NULL, NULL
2971 	},
2972 
2973 	{
2974 		{"checkpoint_completion_target", PGC_SIGHUP, WAL_CHECKPOINTS,
2975 			gettext_noop("Time spent flushing dirty buffers during checkpoint, as fraction of checkpoint interval."),
2976 			NULL
2977 		},
2978 		&CheckPointCompletionTarget,
2979 		0.5, 0.0, 1.0,
2980 		NULL, NULL, NULL
2981 	},
2982 
2983 	/* End-of-list marker */
2984 	{
2985 		{NULL, 0, 0, NULL, NULL}, NULL, 0.0, 0.0, 0.0, NULL, NULL, NULL
2986 	}
2987 };
2988 
2989 
2990 static struct config_string ConfigureNamesString[] =
2991 {
2992 	{
2993 		{"archive_command", PGC_SIGHUP, WAL_ARCHIVING,
2994 			gettext_noop("Sets the shell command that will be called to archive a WAL file."),
2995 			NULL
2996 		},
2997 		&XLogArchiveCommand,
2998 		"",
2999 		NULL, NULL, show_archive_command
3000 	},
3001 
3002 	{
3003 		{"client_encoding", PGC_USERSET, CLIENT_CONN_LOCALE,
3004 			gettext_noop("Sets the client's character set encoding."),
3005 			NULL,
3006 			GUC_IS_NAME | GUC_REPORT
3007 		},
3008 		&client_encoding_string,
3009 		"SQL_ASCII",
3010 		check_client_encoding, assign_client_encoding, NULL
3011 	},
3012 
3013 	{
3014 		{"log_line_prefix", PGC_SIGHUP, LOGGING_WHAT,
3015 			gettext_noop("Controls information prefixed to each log line."),
3016 			gettext_noop("If blank, no prefix is used.")
3017 		},
3018 		&Log_line_prefix,
3019 		"",
3020 		NULL, NULL, NULL
3021 	},
3022 
3023 	{
3024 		{"log_timezone", PGC_SIGHUP, LOGGING_WHAT,
3025 			gettext_noop("Sets the time zone to use in log messages."),
3026 			NULL
3027 		},
3028 		&log_timezone_string,
3029 		"GMT",
3030 		check_log_timezone, assign_log_timezone, show_log_timezone
3031 	},
3032 
3033 	{
3034 		{"DateStyle", PGC_USERSET, CLIENT_CONN_LOCALE,
3035 			gettext_noop("Sets the display format for date and time values."),
3036 			gettext_noop("Also controls interpretation of ambiguous "
3037 						 "date inputs."),
3038 			GUC_LIST_INPUT | GUC_REPORT
3039 		},
3040 		&datestyle_string,
3041 		"ISO, MDY",
3042 		check_datestyle, assign_datestyle, NULL
3043 	},
3044 
3045 	{
3046 		{"default_tablespace", PGC_USERSET, CLIENT_CONN_STATEMENT,
3047 			gettext_noop("Sets the default tablespace to create tables and indexes in."),
3048 			gettext_noop("An empty string selects the database's default tablespace."),
3049 			GUC_IS_NAME
3050 		},
3051 		&default_tablespace,
3052 		"",
3053 		check_default_tablespace, NULL, NULL
3054 	},
3055 
3056 	{
3057 		{"temp_tablespaces", PGC_USERSET, CLIENT_CONN_STATEMENT,
3058 			gettext_noop("Sets the tablespace(s) to use for temporary tables and sort files."),
3059 			NULL,
3060 			GUC_LIST_INPUT | GUC_LIST_QUOTE
3061 		},
3062 		&temp_tablespaces,
3063 		"",
3064 		check_temp_tablespaces, assign_temp_tablespaces, NULL
3065 	},
3066 
3067 	{
3068 		{"dynamic_library_path", PGC_SUSET, CLIENT_CONN_OTHER,
3069 			gettext_noop("Sets the path for dynamically loadable modules."),
3070 			gettext_noop("If a dynamically loadable module needs to be opened and "
3071 						 "the specified name does not have a directory component (i.e., the "
3072 						 "name does not contain a slash), the system will search this path for "
3073 						 "the specified file."),
3074 			GUC_SUPERUSER_ONLY
3075 		},
3076 		&Dynamic_library_path,
3077 		"$libdir",
3078 		NULL, NULL, NULL
3079 	},
3080 
3081 	{
3082 		{"krb_server_keyfile", PGC_SIGHUP, CONN_AUTH_SECURITY,
3083 			gettext_noop("Sets the location of the Kerberos server key file."),
3084 			NULL,
3085 			GUC_SUPERUSER_ONLY
3086 		},
3087 		&pg_krb_server_keyfile,
3088 		PG_KRB_SRVTAB,
3089 		NULL, NULL, NULL
3090 	},
3091 
3092 	{
3093 		{"bonjour_name", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
3094 			gettext_noop("Sets the Bonjour service name."),
3095 			NULL
3096 		},
3097 		&bonjour_name,
3098 		"",
3099 		NULL, NULL, NULL
3100 	},
3101 
3102 	/* See main.c about why defaults for LC_foo are not all alike */
3103 
3104 	{
3105 		{"lc_collate", PGC_INTERNAL, CLIENT_CONN_LOCALE,
3106 			gettext_noop("Shows the collation order locale."),
3107 			NULL,
3108 			GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
3109 		},
3110 		&locale_collate,
3111 		"C",
3112 		NULL, NULL, NULL
3113 	},
3114 
3115 	{
3116 		{"lc_ctype", PGC_INTERNAL, CLIENT_CONN_LOCALE,
3117 			gettext_noop("Shows the character classification and case conversion locale."),
3118 			NULL,
3119 			GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
3120 		},
3121 		&locale_ctype,
3122 		"C",
3123 		NULL, NULL, NULL
3124 	},
3125 
3126 	{
3127 		{"lc_messages", PGC_SUSET, CLIENT_CONN_LOCALE,
3128 			gettext_noop("Sets the language in which messages are displayed."),
3129 			NULL
3130 		},
3131 		&locale_messages,
3132 		"",
3133 		check_locale_messages, assign_locale_messages, NULL
3134 	},
3135 
3136 	{
3137 		{"lc_monetary", PGC_USERSET, CLIENT_CONN_LOCALE,
3138 			gettext_noop("Sets the locale for formatting monetary amounts."),
3139 			NULL
3140 		},
3141 		&locale_monetary,
3142 		"C",
3143 		check_locale_monetary, assign_locale_monetary, NULL
3144 	},
3145 
3146 	{
3147 		{"lc_numeric", PGC_USERSET, CLIENT_CONN_LOCALE,
3148 			gettext_noop("Sets the locale for formatting numbers."),
3149 			NULL
3150 		},
3151 		&locale_numeric,
3152 		"C",
3153 		check_locale_numeric, assign_locale_numeric, NULL
3154 	},
3155 
3156 	{
3157 		{"lc_time", PGC_USERSET, CLIENT_CONN_LOCALE,
3158 			gettext_noop("Sets the locale for formatting date and time values."),
3159 			NULL
3160 		},
3161 		&locale_time,
3162 		"C",
3163 		check_locale_time, assign_locale_time, NULL
3164 	},
3165 
3166 	{
3167 		{"session_preload_libraries", PGC_SUSET, CLIENT_CONN_PRELOAD,
3168 			gettext_noop("Lists shared libraries to preload into each backend."),
3169 			NULL,
3170 			GUC_LIST_INPUT | GUC_LIST_QUOTE | GUC_SUPERUSER_ONLY
3171 		},
3172 		&session_preload_libraries_string,
3173 		"",
3174 		NULL, NULL, NULL
3175 	},
3176 
3177 	{
3178 		{"shared_preload_libraries", PGC_POSTMASTER, CLIENT_CONN_PRELOAD,
3179 			gettext_noop("Lists shared libraries to preload into server."),
3180 			NULL,
3181 			GUC_LIST_INPUT | GUC_LIST_QUOTE | GUC_SUPERUSER_ONLY
3182 		},
3183 		&shared_preload_libraries_string,
3184 		"",
3185 		NULL, NULL, NULL
3186 	},
3187 
3188 	{
3189 		{"local_preload_libraries", PGC_USERSET, CLIENT_CONN_PRELOAD,
3190 			gettext_noop("Lists unprivileged shared libraries to preload into each backend."),
3191 			NULL,
3192 			GUC_LIST_INPUT | GUC_LIST_QUOTE
3193 		},
3194 		&local_preload_libraries_string,
3195 		"",
3196 		NULL, NULL, NULL
3197 	},
3198 
3199 	{
3200 		{"search_path", PGC_USERSET, CLIENT_CONN_STATEMENT,
3201 			gettext_noop("Sets the schema search order for names that are not schema-qualified."),
3202 			NULL,
3203 			GUC_LIST_INPUT | GUC_LIST_QUOTE
3204 		},
3205 		&namespace_search_path,
3206 		"\"$user\", public",
3207 		check_search_path, assign_search_path, NULL
3208 	},
3209 
3210 	{
3211 		/* Can't be set in postgresql.conf */
3212 		{"server_encoding", PGC_INTERNAL, CLIENT_CONN_LOCALE,
3213 			gettext_noop("Sets the server (database) character set encoding."),
3214 			NULL,
3215 			GUC_IS_NAME | GUC_REPORT | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
3216 		},
3217 		&server_encoding_string,
3218 		"SQL_ASCII",
3219 		NULL, NULL, NULL
3220 	},
3221 
3222 	{
3223 		/* Can't be set in postgresql.conf */
3224 		{"server_version", PGC_INTERNAL, PRESET_OPTIONS,
3225 			gettext_noop("Shows the server version."),
3226 			NULL,
3227 			GUC_REPORT | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
3228 		},
3229 		&server_version_string,
3230 		PG_VERSION,
3231 		NULL, NULL, NULL
3232 	},
3233 
3234 	{
3235 		/* Not for general use --- used by SET ROLE */
3236 		{"role", PGC_USERSET, UNGROUPED,
3237 			gettext_noop("Sets the current role."),
3238 			NULL,
3239 			GUC_IS_NAME | GUC_NO_SHOW_ALL | GUC_NO_RESET_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE | GUC_NOT_WHILE_SEC_REST
3240 		},
3241 		&role_string,
3242 		"none",
3243 		check_role, assign_role, show_role
3244 	},
3245 
3246 	{
3247 		/* Not for general use --- used by SET SESSION AUTHORIZATION */
3248 		{"session_authorization", PGC_USERSET, UNGROUPED,
3249 			gettext_noop("Sets the session user name."),
3250 			NULL,
3251 			GUC_IS_NAME | GUC_REPORT | GUC_NO_SHOW_ALL | GUC_NO_RESET_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE | GUC_NOT_WHILE_SEC_REST
3252 		},
3253 		&session_authorization_string,
3254 		NULL,
3255 		check_session_authorization, assign_session_authorization, NULL
3256 	},
3257 
3258 	{
3259 		{"log_destination", PGC_SIGHUP, LOGGING_WHERE,
3260 			gettext_noop("Sets the destination for server log output."),
3261 			gettext_noop("Valid values are combinations of \"stderr\", "
3262 						 "\"syslog\", \"csvlog\", and \"eventlog\", "
3263 						 "depending on the platform."),
3264 			GUC_LIST_INPUT
3265 		},
3266 		&Log_destination_string,
3267 		"stderr",
3268 		check_log_destination, assign_log_destination, NULL
3269 	},
3270 	{
3271 		{"log_directory", PGC_SIGHUP, LOGGING_WHERE,
3272 			gettext_noop("Sets the destination directory for log files."),
3273 			gettext_noop("Can be specified as relative to the data directory "
3274 						 "or as absolute path."),
3275 			GUC_SUPERUSER_ONLY
3276 		},
3277 		&Log_directory,
3278 		"pg_log",
3279 		check_canonical_path, NULL, NULL
3280 	},
3281 	{
3282 		{"log_filename", PGC_SIGHUP, LOGGING_WHERE,
3283 			gettext_noop("Sets the file name pattern for log files."),
3284 			NULL,
3285 			GUC_SUPERUSER_ONLY
3286 		},
3287 		&Log_filename,
3288 		"postgresql-%Y-%m-%d_%H%M%S.log",
3289 		NULL, NULL, NULL
3290 	},
3291 
3292 	{
3293 		{"syslog_ident", PGC_SIGHUP, LOGGING_WHERE,
3294 			gettext_noop("Sets the program name used to identify PostgreSQL "
3295 						 "messages in syslog."),
3296 			NULL
3297 		},
3298 		&syslog_ident_str,
3299 		"postgres",
3300 		NULL, assign_syslog_ident, NULL
3301 	},
3302 
3303 	{
3304 		{"event_source", PGC_POSTMASTER, LOGGING_WHERE,
3305 			gettext_noop("Sets the application name used to identify "
3306 						 "PostgreSQL messages in the event log."),
3307 			NULL
3308 		},
3309 		&event_source,
3310 		DEFAULT_EVENT_SOURCE,
3311 		NULL, NULL, NULL
3312 	},
3313 
3314 	{
3315 		{"TimeZone", PGC_USERSET, CLIENT_CONN_LOCALE,
3316 			gettext_noop("Sets the time zone for displaying and interpreting time stamps."),
3317 			NULL,
3318 			GUC_REPORT
3319 		},
3320 		&timezone_string,
3321 		"GMT",
3322 		check_timezone, assign_timezone, show_timezone
3323 	},
3324 	{
3325 		{"timezone_abbreviations", PGC_USERSET, CLIENT_CONN_LOCALE,
3326 			gettext_noop("Selects a file of time zone abbreviations."),
3327 			NULL
3328 		},
3329 		&timezone_abbreviations_string,
3330 		NULL,
3331 		check_timezone_abbreviations, assign_timezone_abbreviations, NULL
3332 	},
3333 
3334 	{
3335 		{"transaction_isolation", PGC_USERSET, CLIENT_CONN_STATEMENT,
3336 			gettext_noop("Sets the current transaction's isolation level."),
3337 			NULL,
3338 			GUC_NO_RESET_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
3339 		},
3340 		&XactIsoLevel_string,
3341 		"default",
3342 		check_XactIsoLevel, assign_XactIsoLevel, show_XactIsoLevel
3343 	},
3344 
3345 	{
3346 		{"unix_socket_group", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
3347 			gettext_noop("Sets the owning group of the Unix-domain socket."),
3348 			gettext_noop("The owning user of the socket is always the user "
3349 						 "that starts the server.")
3350 		},
3351 		&Unix_socket_group,
3352 		"",
3353 		NULL, NULL, NULL
3354 	},
3355 
3356 	{
3357 		{"unix_socket_directories", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
3358 			gettext_noop("Sets the directories where Unix-domain sockets will be created."),
3359 			NULL,
3360 			GUC_SUPERUSER_ONLY
3361 		},
3362 		&Unix_socket_directories,
3363 #ifdef HAVE_UNIX_SOCKETS
3364 		DEFAULT_PGSOCKET_DIR,
3365 #else
3366 		"",
3367 #endif
3368 		NULL, NULL, NULL
3369 	},
3370 
3371 	{
3372 		{"listen_addresses", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
3373 			gettext_noop("Sets the host name or IP address(es) to listen to."),
3374 			NULL,
3375 			GUC_LIST_INPUT
3376 		},
3377 		&ListenAddresses,
3378 		"localhost",
3379 		NULL, NULL, NULL
3380 	},
3381 
3382 	{
3383 		/*
3384 		 * Can't be set by ALTER SYSTEM as it can lead to recursive definition
3385 		 * of data_directory.
3386 		 */
3387 		{"data_directory", PGC_POSTMASTER, FILE_LOCATIONS,
3388 			gettext_noop("Sets the server's data directory."),
3389 			NULL,
3390 			GUC_SUPERUSER_ONLY | GUC_DISALLOW_IN_AUTO_FILE
3391 		},
3392 		&data_directory,
3393 		NULL,
3394 		NULL, NULL, NULL
3395 	},
3396 
3397 	{
3398 		{"config_file", PGC_POSTMASTER, FILE_LOCATIONS,
3399 			gettext_noop("Sets the server's main configuration file."),
3400 			NULL,
3401 			GUC_DISALLOW_IN_FILE | GUC_SUPERUSER_ONLY
3402 		},
3403 		&ConfigFileName,
3404 		NULL,
3405 		NULL, NULL, NULL
3406 	},
3407 
3408 	{
3409 		{"hba_file", PGC_POSTMASTER, FILE_LOCATIONS,
3410 			gettext_noop("Sets the server's \"hba\" configuration file."),
3411 			NULL,
3412 			GUC_SUPERUSER_ONLY
3413 		},
3414 		&HbaFileName,
3415 		NULL,
3416 		NULL, NULL, NULL
3417 	},
3418 
3419 	{
3420 		{"ident_file", PGC_POSTMASTER, FILE_LOCATIONS,
3421 			gettext_noop("Sets the server's \"ident\" configuration file."),
3422 			NULL,
3423 			GUC_SUPERUSER_ONLY
3424 		},
3425 		&IdentFileName,
3426 		NULL,
3427 		NULL, NULL, NULL
3428 	},
3429 
3430 	{
3431 		{"external_pid_file", PGC_POSTMASTER, FILE_LOCATIONS,
3432 			gettext_noop("Writes the postmaster PID to the specified file."),
3433 			NULL,
3434 			GUC_SUPERUSER_ONLY
3435 		},
3436 		&external_pid_file,
3437 		NULL,
3438 		check_canonical_path, NULL, NULL
3439 	},
3440 
3441 	{
3442 		{"ssl_cert_file", PGC_POSTMASTER, CONN_AUTH_SECURITY,
3443 			gettext_noop("Location of the SSL server certificate file."),
3444 			NULL
3445 		},
3446 		&ssl_cert_file,
3447 		"server.crt",
3448 		NULL, NULL, NULL
3449 	},
3450 
3451 	{
3452 		{"ssl_key_file", PGC_POSTMASTER, CONN_AUTH_SECURITY,
3453 			gettext_noop("Location of the SSL server private key file."),
3454 			NULL
3455 		},
3456 		&ssl_key_file,
3457 		"server.key",
3458 		NULL, NULL, NULL
3459 	},
3460 
3461 	{
3462 		{"ssl_ca_file", PGC_POSTMASTER, CONN_AUTH_SECURITY,
3463 			gettext_noop("Location of the SSL certificate authority file."),
3464 			NULL
3465 		},
3466 		&ssl_ca_file,
3467 		"",
3468 		NULL, NULL, NULL
3469 	},
3470 
3471 	{
3472 		{"ssl_crl_file", PGC_POSTMASTER, CONN_AUTH_SECURITY,
3473 			gettext_noop("Location of the SSL certificate revocation list file."),
3474 			NULL
3475 		},
3476 		&ssl_crl_file,
3477 		"",
3478 		NULL, NULL, NULL
3479 	},
3480 
3481 	{
3482 		{"stats_temp_directory", PGC_SIGHUP, STATS_COLLECTOR,
3483 			gettext_noop("Writes temporary statistics files to the specified directory."),
3484 			NULL,
3485 			GUC_SUPERUSER_ONLY
3486 		},
3487 		&pgstat_temp_directory,
3488 		PG_STAT_TMP_DIR,
3489 		check_canonical_path, assign_pgstat_temp_directory, NULL
3490 	},
3491 
3492 	{
3493 		{"synchronous_standby_names", PGC_SIGHUP, REPLICATION_MASTER,
3494 			gettext_noop("Number of synchronous standbys and list of names of potential synchronous ones."),
3495 			NULL,
3496 			GUC_LIST_INPUT
3497 		},
3498 		&SyncRepStandbyNames,
3499 		"",
3500 		check_synchronous_standby_names, assign_synchronous_standby_names, NULL
3501 	},
3502 
3503 	{
3504 		{"default_text_search_config", PGC_USERSET, CLIENT_CONN_LOCALE,
3505 			gettext_noop("Sets default text search configuration."),
3506 			NULL
3507 		},
3508 		&TSCurrentConfig,
3509 		"pg_catalog.simple",
3510 		check_TSCurrentConfig, assign_TSCurrentConfig, NULL
3511 	},
3512 
3513 	{
3514 		{"ssl_ciphers", PGC_POSTMASTER, CONN_AUTH_SECURITY,
3515 			gettext_noop("Sets the list of allowed SSL ciphers."),
3516 			NULL,
3517 			GUC_SUPERUSER_ONLY
3518 		},
3519 		&SSLCipherSuites,
3520 #ifdef USE_SSL
3521 		"HIGH:MEDIUM:+3DES:!aNULL",
3522 #else
3523 		"none",
3524 #endif
3525 		NULL, NULL, NULL
3526 	},
3527 
3528 	{
3529 		{"ssl_ecdh_curve", PGC_POSTMASTER, CONN_AUTH_SECURITY,
3530 			gettext_noop("Sets the curve to use for ECDH."),
3531 			NULL,
3532 			GUC_SUPERUSER_ONLY
3533 		},
3534 		&SSLECDHCurve,
3535 #ifdef USE_SSL
3536 		"prime256v1",
3537 #else
3538 		"none",
3539 #endif
3540 		NULL, NULL, NULL
3541 	},
3542 
3543 	{
3544 		{"application_name", PGC_USERSET, LOGGING_WHAT,
3545 			gettext_noop("Sets the application name to be reported in statistics and logs."),
3546 			NULL,
3547 			GUC_IS_NAME | GUC_REPORT | GUC_NOT_IN_SAMPLE
3548 		},
3549 		&application_name,
3550 		"",
3551 		check_application_name, assign_application_name, NULL
3552 	},
3553 
3554 	{
3555 		{"cluster_name", PGC_POSTMASTER, PROCESS_TITLE,
3556 			gettext_noop("Sets the name of the cluster, which is included in the process title."),
3557 			NULL,
3558 			GUC_IS_NAME
3559 		},
3560 		&cluster_name,
3561 		"",
3562 		check_cluster_name, NULL, NULL
3563 	},
3564 
3565 	/* End-of-list marker */
3566 	{
3567 		{NULL, 0, 0, NULL, NULL}, NULL, NULL, NULL, NULL, NULL
3568 	}
3569 };
3570 
3571 
3572 static struct config_enum ConfigureNamesEnum[] =
3573 {
3574 	{
3575 		{"backslash_quote", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
3576 			gettext_noop("Sets whether \"\\'\" is allowed in string literals."),
3577 			NULL
3578 		},
3579 		&backslash_quote,
3580 		BACKSLASH_QUOTE_SAFE_ENCODING, backslash_quote_options,
3581 		NULL, NULL, NULL
3582 	},
3583 
3584 	{
3585 		{"bytea_output", PGC_USERSET, CLIENT_CONN_STATEMENT,
3586 			gettext_noop("Sets the output format for bytea."),
3587 			NULL
3588 		},
3589 		&bytea_output,
3590 		BYTEA_OUTPUT_HEX, bytea_output_options,
3591 		NULL, NULL, NULL
3592 	},
3593 
3594 	{
3595 		{"client_min_messages", PGC_USERSET, CLIENT_CONN_STATEMENT,
3596 			gettext_noop("Sets the message levels that are sent to the client."),
3597 			gettext_noop("Each level includes all the levels that follow it. The later"
3598 						 " the level, the fewer messages are sent.")
3599 		},
3600 		&client_min_messages,
3601 		NOTICE, client_message_level_options,
3602 		check_client_min_messages, NULL, NULL
3603 	},
3604 
3605 	{
3606 		{"constraint_exclusion", PGC_USERSET, QUERY_TUNING_OTHER,
3607 			gettext_noop("Enables the planner to use constraints to optimize queries."),
3608 			gettext_noop("Table scans will be skipped if their constraints"
3609 						 " guarantee that no rows match the query.")
3610 		},
3611 		&constraint_exclusion,
3612 		CONSTRAINT_EXCLUSION_PARTITION, constraint_exclusion_options,
3613 		NULL, NULL, NULL
3614 	},
3615 
3616 	{
3617 		{"default_transaction_isolation", PGC_USERSET, CLIENT_CONN_STATEMENT,
3618 			gettext_noop("Sets the transaction isolation level of each new transaction."),
3619 			NULL
3620 		},
3621 		&DefaultXactIsoLevel,
3622 		XACT_READ_COMMITTED, isolation_level_options,
3623 		NULL, NULL, NULL
3624 	},
3625 
3626 	{
3627 		{"IntervalStyle", PGC_USERSET, CLIENT_CONN_LOCALE,
3628 			gettext_noop("Sets the display format for interval values."),
3629 			NULL,
3630 			GUC_REPORT
3631 		},
3632 		&IntervalStyle,
3633 		INTSTYLE_POSTGRES, intervalstyle_options,
3634 		NULL, NULL, NULL
3635 	},
3636 
3637 	{
3638 		{"log_error_verbosity", PGC_SUSET, LOGGING_WHAT,
3639 			gettext_noop("Sets the verbosity of logged messages."),
3640 			NULL
3641 		},
3642 		&Log_error_verbosity,
3643 		PGERROR_DEFAULT, log_error_verbosity_options,
3644 		NULL, NULL, NULL
3645 	},
3646 
3647 	{
3648 		{"log_min_messages", PGC_SUSET, LOGGING_WHEN,
3649 			gettext_noop("Sets the message levels that are logged."),
3650 			gettext_noop("Each level includes all the levels that follow it. The later"
3651 						 " the level, the fewer messages are sent.")
3652 		},
3653 		&log_min_messages,
3654 		WARNING, server_message_level_options,
3655 		NULL, NULL, NULL
3656 	},
3657 
3658 	{
3659 		{"log_min_error_statement", PGC_SUSET, LOGGING_WHEN,
3660 			gettext_noop("Causes all statements generating error at or above this level to be logged."),
3661 			gettext_noop("Each level includes all the levels that follow it. The later"
3662 						 " the level, the fewer messages are sent.")
3663 		},
3664 		&log_min_error_statement,
3665 		ERROR, server_message_level_options,
3666 		NULL, NULL, NULL
3667 	},
3668 
3669 	{
3670 		{"log_statement", PGC_SUSET, LOGGING_WHAT,
3671 			gettext_noop("Sets the type of statements logged."),
3672 			NULL
3673 		},
3674 		&log_statement,
3675 		LOGSTMT_NONE, log_statement_options,
3676 		NULL, NULL, NULL
3677 	},
3678 
3679 	{
3680 		{"syslog_facility", PGC_SIGHUP, LOGGING_WHERE,
3681 			gettext_noop("Sets the syslog \"facility\" to be used when syslog enabled."),
3682 			NULL
3683 		},
3684 		&syslog_facility,
3685 #ifdef HAVE_SYSLOG
3686 		LOG_LOCAL0,
3687 #else
3688 		0,
3689 #endif
3690 		syslog_facility_options,
3691 		NULL, assign_syslog_facility, NULL
3692 	},
3693 
3694 	{
3695 		{"session_replication_role", PGC_SUSET, CLIENT_CONN_STATEMENT,
3696 			gettext_noop("Sets the session's behavior for triggers and rewrite rules."),
3697 			NULL
3698 		},
3699 		&SessionReplicationRole,
3700 		SESSION_REPLICATION_ROLE_ORIGIN, session_replication_role_options,
3701 		NULL, assign_session_replication_role, NULL
3702 	},
3703 
3704 	{
3705 		{"synchronous_commit", PGC_USERSET, WAL_SETTINGS,
3706 			gettext_noop("Sets the current transaction's synchronization level."),
3707 			NULL
3708 		},
3709 		&synchronous_commit,
3710 		SYNCHRONOUS_COMMIT_ON, synchronous_commit_options,
3711 		NULL, assign_synchronous_commit, NULL
3712 	},
3713 
3714 	{
3715 		{"archive_mode", PGC_POSTMASTER, WAL_ARCHIVING,
3716 			gettext_noop("Allows archiving of WAL files using archive_command."),
3717 			NULL
3718 		},
3719 		&XLogArchiveMode,
3720 		ARCHIVE_MODE_OFF, archive_mode_options,
3721 		NULL, NULL, NULL
3722 	},
3723 
3724 	{
3725 		{"trace_recovery_messages", PGC_SIGHUP, DEVELOPER_OPTIONS,
3726 			gettext_noop("Enables logging of recovery-related debugging information."),
3727 			gettext_noop("Each level includes all the levels that follow it. The later"
3728 						 " the level, the fewer messages are sent.")
3729 		},
3730 		&trace_recovery_messages,
3731 
3732 		/*
3733 		 * client_message_level_options allows too many values, really, but
3734 		 * it's not worth having a separate options array for this.
3735 		 */
3736 		LOG, client_message_level_options,
3737 		NULL, NULL, NULL
3738 	},
3739 
3740 	{
3741 		{"track_functions", PGC_SUSET, STATS_COLLECTOR,
3742 			gettext_noop("Collects function-level statistics on database activity."),
3743 			NULL
3744 		},
3745 		&pgstat_track_functions,
3746 		TRACK_FUNC_OFF, track_function_options,
3747 		NULL, NULL, NULL
3748 	},
3749 
3750 	{
3751 		{"wal_level", PGC_POSTMASTER, WAL_SETTINGS,
3752 			gettext_noop("Set the level of information written to the WAL."),
3753 			NULL
3754 		},
3755 		&wal_level,
3756 		WAL_LEVEL_MINIMAL, wal_level_options,
3757 		NULL, NULL, NULL
3758 	},
3759 
3760 	{
3761 		{"dynamic_shared_memory_type", PGC_POSTMASTER, RESOURCES_MEM,
3762 			gettext_noop("Selects the dynamic shared memory implementation used."),
3763 			NULL
3764 		},
3765 		&dynamic_shared_memory_type,
3766 		DEFAULT_DYNAMIC_SHARED_MEMORY_TYPE, dynamic_shared_memory_options,
3767 		NULL, NULL, NULL
3768 	},
3769 
3770 	{
3771 		{"wal_sync_method", PGC_SIGHUP, WAL_SETTINGS,
3772 			gettext_noop("Selects the method used for forcing WAL updates to disk."),
3773 			NULL
3774 		},
3775 		&sync_method,
3776 		DEFAULT_SYNC_METHOD, sync_method_options,
3777 		NULL, assign_xlog_sync_method, NULL
3778 	},
3779 
3780 	{
3781 		{"xmlbinary", PGC_USERSET, CLIENT_CONN_STATEMENT,
3782 			gettext_noop("Sets how binary values are to be encoded in XML."),
3783 			NULL
3784 		},
3785 		&xmlbinary,
3786 		XMLBINARY_BASE64, xmlbinary_options,
3787 		NULL, NULL, NULL
3788 	},
3789 
3790 	{
3791 		{"xmloption", PGC_USERSET, CLIENT_CONN_STATEMENT,
3792 			gettext_noop("Sets whether XML data in implicit parsing and serialization "
3793 						 "operations is to be considered as documents or content fragments."),
3794 			NULL
3795 		},
3796 		&xmloption,
3797 		XMLOPTION_CONTENT, xmloption_options,
3798 		NULL, NULL, NULL
3799 	},
3800 
3801 	{
3802 		{"huge_pages", PGC_POSTMASTER, RESOURCES_MEM,
3803 			gettext_noop("Use of huge pages on Linux."),
3804 			NULL
3805 		},
3806 		&huge_pages,
3807 		HUGE_PAGES_TRY, huge_pages_options,
3808 		NULL, NULL, NULL
3809 	},
3810 
3811 	{
3812 		{"force_parallel_mode", PGC_USERSET, QUERY_TUNING_OTHER,
3813 			gettext_noop("Forces use of parallel query facilities."),
3814 			gettext_noop("If possible, run query using a parallel worker and with parallel restrictions.")
3815 		},
3816 		&force_parallel_mode,
3817 		FORCE_PARALLEL_OFF, force_parallel_mode_options,
3818 		NULL, NULL, NULL
3819 	},
3820 
3821 	/* End-of-list marker */
3822 	{
3823 		{NULL, 0, 0, NULL, NULL}, NULL, 0, NULL, NULL, NULL, NULL
3824 	}
3825 };
3826 
3827 /******** end of options list ********/
3828 
3829 
3830 /*
3831  * To allow continued support of obsolete names for GUC variables, we apply
3832  * the following mappings to any unrecognized name.  Note that an old name
3833  * should be mapped to a new one only if the new variable has very similar
3834  * semantics to the old.
3835  */
3836 static const char *const map_old_guc_names[] = {
3837 	"sort_mem", "work_mem",
3838 	"vacuum_mem", "maintenance_work_mem",
3839 	NULL
3840 };
3841 
3842 
3843 /*
3844  * Actual lookup of variables is done through this single, sorted array.
3845  */
3846 static struct config_generic **guc_variables;
3847 
3848 /* Current number of variables contained in the vector */
3849 static int	num_guc_variables;
3850 
3851 /* Vector capacity */
3852 static int	size_guc_variables;
3853 
3854 
3855 static bool guc_dirty;			/* TRUE if need to do commit/abort work */
3856 
3857 static bool reporting_enabled;	/* TRUE to enable GUC_REPORT */
3858 
3859 static int	GUCNestLevel = 0;	/* 1 when in main transaction */
3860 
3861 
3862 static int	guc_var_compare(const void *a, const void *b);
3863 static int	guc_name_compare(const char *namea, const char *nameb);
3864 static void InitializeGUCOptionsFromEnvironment(void);
3865 static void InitializeOneGUCOption(struct config_generic * gconf);
3866 static void push_old_value(struct config_generic * gconf, GucAction action);
3867 static void ReportGUCOption(struct config_generic * record);
3868 static void reapply_stacked_values(struct config_generic * variable,
3869 					   struct config_string * pHolder,
3870 					   GucStack *stack,
3871 					   const char *curvalue,
3872 					   GucContext curscontext, GucSource cursource);
3873 static void ShowGUCConfigOption(const char *name, DestReceiver *dest);
3874 static void ShowAllGUCConfig(DestReceiver *dest);
3875 static char *_ShowOption(struct config_generic * record, bool use_units);
3876 static bool validate_option_array_item(const char *name, const char *value,
3877 						   bool skipIfNoPermissions);
3878 static void write_auto_conf_file(int fd, const char *filename, ConfigVariable *head_p);
3879 static void replace_auto_config_value(ConfigVariable **head_p, ConfigVariable **tail_p,
3880 						  const char *name, const char *value);
3881 
3882 
3883 /*
3884  * Some infrastructure for checking malloc/strdup/realloc calls
3885  */
3886 static void *
guc_malloc(int elevel,size_t size)3887 guc_malloc(int elevel, size_t size)
3888 {
3889 	void	   *data;
3890 
3891 	/* Avoid unportable behavior of malloc(0) */
3892 	if (size == 0)
3893 		size = 1;
3894 	data = malloc(size);
3895 	if (data == NULL)
3896 		ereport(elevel,
3897 				(errcode(ERRCODE_OUT_OF_MEMORY),
3898 				 errmsg("out of memory")));
3899 	return data;
3900 }
3901 
3902 static void *
guc_realloc(int elevel,void * old,size_t size)3903 guc_realloc(int elevel, void *old, size_t size)
3904 {
3905 	void	   *data;
3906 
3907 	/* Avoid unportable behavior of realloc(NULL, 0) */
3908 	if (old == NULL && size == 0)
3909 		size = 1;
3910 	data = realloc(old, size);
3911 	if (data == NULL)
3912 		ereport(elevel,
3913 				(errcode(ERRCODE_OUT_OF_MEMORY),
3914 				 errmsg("out of memory")));
3915 	return data;
3916 }
3917 
3918 static char *
guc_strdup(int elevel,const char * src)3919 guc_strdup(int elevel, const char *src)
3920 {
3921 	char	   *data;
3922 
3923 	data = strdup(src);
3924 	if (data == NULL)
3925 		ereport(elevel,
3926 				(errcode(ERRCODE_OUT_OF_MEMORY),
3927 				 errmsg("out of memory")));
3928 	return data;
3929 }
3930 
3931 
3932 /*
3933  * Detect whether strval is referenced anywhere in a GUC string item
3934  */
3935 static bool
string_field_used(struct config_string * conf,char * strval)3936 string_field_used(struct config_string * conf, char *strval)
3937 {
3938 	GucStack   *stack;
3939 
3940 	if (strval == *(conf->variable) ||
3941 		strval == conf->reset_val ||
3942 		strval == conf->boot_val)
3943 		return true;
3944 	for (stack = conf->gen.stack; stack; stack = stack->prev)
3945 	{
3946 		if (strval == stack->prior.val.stringval ||
3947 			strval == stack->masked.val.stringval)
3948 			return true;
3949 	}
3950 	return false;
3951 }
3952 
3953 /*
3954  * Support for assigning to a field of a string GUC item.  Free the prior
3955  * value if it's not referenced anywhere else in the item (including stacked
3956  * states).
3957  */
3958 static void
set_string_field(struct config_string * conf,char ** field,char * newval)3959 set_string_field(struct config_string * conf, char **field, char *newval)
3960 {
3961 	char	   *oldval = *field;
3962 
3963 	/* Do the assignment */
3964 	*field = newval;
3965 
3966 	/* Free old value if it's not NULL and isn't referenced anymore */
3967 	if (oldval && !string_field_used(conf, oldval))
3968 		free(oldval);
3969 }
3970 
3971 /*
3972  * Detect whether an "extra" struct is referenced anywhere in a GUC item
3973  */
3974 static bool
extra_field_used(struct config_generic * gconf,void * extra)3975 extra_field_used(struct config_generic * gconf, void *extra)
3976 {
3977 	GucStack   *stack;
3978 
3979 	if (extra == gconf->extra)
3980 		return true;
3981 	switch (gconf->vartype)
3982 	{
3983 		case PGC_BOOL:
3984 			if (extra == ((struct config_bool *) gconf)->reset_extra)
3985 				return true;
3986 			break;
3987 		case PGC_INT:
3988 			if (extra == ((struct config_int *) gconf)->reset_extra)
3989 				return true;
3990 			break;
3991 		case PGC_REAL:
3992 			if (extra == ((struct config_real *) gconf)->reset_extra)
3993 				return true;
3994 			break;
3995 		case PGC_STRING:
3996 			if (extra == ((struct config_string *) gconf)->reset_extra)
3997 				return true;
3998 			break;
3999 		case PGC_ENUM:
4000 			if (extra == ((struct config_enum *) gconf)->reset_extra)
4001 				return true;
4002 			break;
4003 	}
4004 	for (stack = gconf->stack; stack; stack = stack->prev)
4005 	{
4006 		if (extra == stack->prior.extra ||
4007 			extra == stack->masked.extra)
4008 			return true;
4009 	}
4010 
4011 	return false;
4012 }
4013 
4014 /*
4015  * Support for assigning to an "extra" field of a GUC item.  Free the prior
4016  * value if it's not referenced anywhere else in the item (including stacked
4017  * states).
4018  */
4019 static void
set_extra_field(struct config_generic * gconf,void ** field,void * newval)4020 set_extra_field(struct config_generic * gconf, void **field, void *newval)
4021 {
4022 	void	   *oldval = *field;
4023 
4024 	/* Do the assignment */
4025 	*field = newval;
4026 
4027 	/* Free old value if it's not NULL and isn't referenced anymore */
4028 	if (oldval && !extra_field_used(gconf, oldval))
4029 		free(oldval);
4030 }
4031 
4032 /*
4033  * Support for copying a variable's active value into a stack entry.
4034  * The "extra" field associated with the active value is copied, too.
4035  *
4036  * NB: be sure stringval and extra fields of a new stack entry are
4037  * initialized to NULL before this is used, else we'll try to free() them.
4038  */
4039 static void
set_stack_value(struct config_generic * gconf,config_var_value * val)4040 set_stack_value(struct config_generic * gconf, config_var_value *val)
4041 {
4042 	switch (gconf->vartype)
4043 	{
4044 		case PGC_BOOL:
4045 			val->val.boolval =
4046 				*((struct config_bool *) gconf)->variable;
4047 			break;
4048 		case PGC_INT:
4049 			val->val.intval =
4050 				*((struct config_int *) gconf)->variable;
4051 			break;
4052 		case PGC_REAL:
4053 			val->val.realval =
4054 				*((struct config_real *) gconf)->variable;
4055 			break;
4056 		case PGC_STRING:
4057 			set_string_field((struct config_string *) gconf,
4058 							 &(val->val.stringval),
4059 							 *((struct config_string *) gconf)->variable);
4060 			break;
4061 		case PGC_ENUM:
4062 			val->val.enumval =
4063 				*((struct config_enum *) gconf)->variable;
4064 			break;
4065 	}
4066 	set_extra_field(gconf, &(val->extra), gconf->extra);
4067 }
4068 
4069 /*
4070  * Support for discarding a no-longer-needed value in a stack entry.
4071  * The "extra" field associated with the stack entry is cleared, too.
4072  */
4073 static void
discard_stack_value(struct config_generic * gconf,config_var_value * val)4074 discard_stack_value(struct config_generic * gconf, config_var_value *val)
4075 {
4076 	switch (gconf->vartype)
4077 	{
4078 		case PGC_BOOL:
4079 		case PGC_INT:
4080 		case PGC_REAL:
4081 		case PGC_ENUM:
4082 			/* no need to do anything */
4083 			break;
4084 		case PGC_STRING:
4085 			set_string_field((struct config_string *) gconf,
4086 							 &(val->val.stringval),
4087 							 NULL);
4088 			break;
4089 	}
4090 	set_extra_field(gconf, &(val->extra), NULL);
4091 }
4092 
4093 
4094 /*
4095  * Fetch the sorted array pointer (exported for help_config.c's use ONLY)
4096  */
4097 struct config_generic **
get_guc_variables(void)4098 get_guc_variables(void)
4099 {
4100 	return guc_variables;
4101 }
4102 
4103 
4104 /*
4105  * Build the sorted array.  This is split out so that it could be
4106  * re-executed after startup (e.g., we could allow loadable modules to
4107  * add vars, and then we'd need to re-sort).
4108  */
4109 void
build_guc_variables(void)4110 build_guc_variables(void)
4111 {
4112 	int			size_vars;
4113 	int			num_vars = 0;
4114 	struct config_generic **guc_vars;
4115 	int			i;
4116 
4117 	for (i = 0; ConfigureNamesBool[i].gen.name; i++)
4118 	{
4119 		struct config_bool *conf = &ConfigureNamesBool[i];
4120 
4121 		/* Rather than requiring vartype to be filled in by hand, do this: */
4122 		conf->gen.vartype = PGC_BOOL;
4123 		num_vars++;
4124 	}
4125 
4126 	for (i = 0; ConfigureNamesInt[i].gen.name; i++)
4127 	{
4128 		struct config_int *conf = &ConfigureNamesInt[i];
4129 
4130 		conf->gen.vartype = PGC_INT;
4131 		num_vars++;
4132 	}
4133 
4134 	for (i = 0; ConfigureNamesReal[i].gen.name; i++)
4135 	{
4136 		struct config_real *conf = &ConfigureNamesReal[i];
4137 
4138 		conf->gen.vartype = PGC_REAL;
4139 		num_vars++;
4140 	}
4141 
4142 	for (i = 0; ConfigureNamesString[i].gen.name; i++)
4143 	{
4144 		struct config_string *conf = &ConfigureNamesString[i];
4145 
4146 		conf->gen.vartype = PGC_STRING;
4147 		num_vars++;
4148 	}
4149 
4150 	for (i = 0; ConfigureNamesEnum[i].gen.name; i++)
4151 	{
4152 		struct config_enum *conf = &ConfigureNamesEnum[i];
4153 
4154 		conf->gen.vartype = PGC_ENUM;
4155 		num_vars++;
4156 	}
4157 
4158 	/*
4159 	 * Create table with 20% slack
4160 	 */
4161 	size_vars = num_vars + num_vars / 4;
4162 
4163 	guc_vars = (struct config_generic **)
4164 		guc_malloc(FATAL, size_vars * sizeof(struct config_generic *));
4165 
4166 	num_vars = 0;
4167 
4168 	for (i = 0; ConfigureNamesBool[i].gen.name; i++)
4169 		guc_vars[num_vars++] = &ConfigureNamesBool[i].gen;
4170 
4171 	for (i = 0; ConfigureNamesInt[i].gen.name; i++)
4172 		guc_vars[num_vars++] = &ConfigureNamesInt[i].gen;
4173 
4174 	for (i = 0; ConfigureNamesReal[i].gen.name; i++)
4175 		guc_vars[num_vars++] = &ConfigureNamesReal[i].gen;
4176 
4177 	for (i = 0; ConfigureNamesString[i].gen.name; i++)
4178 		guc_vars[num_vars++] = &ConfigureNamesString[i].gen;
4179 
4180 	for (i = 0; ConfigureNamesEnum[i].gen.name; i++)
4181 		guc_vars[num_vars++] = &ConfigureNamesEnum[i].gen;
4182 
4183 	if (guc_variables)
4184 		free(guc_variables);
4185 	guc_variables = guc_vars;
4186 	num_guc_variables = num_vars;
4187 	size_guc_variables = size_vars;
4188 	qsort((void *) guc_variables, num_guc_variables,
4189 		  sizeof(struct config_generic *), guc_var_compare);
4190 }
4191 
4192 /*
4193  * Add a new GUC variable to the list of known variables. The
4194  * list is expanded if needed.
4195  */
4196 static bool
add_guc_variable(struct config_generic * var,int elevel)4197 add_guc_variable(struct config_generic * var, int elevel)
4198 {
4199 	if (num_guc_variables + 1 >= size_guc_variables)
4200 	{
4201 		/*
4202 		 * Increase the vector by 25%
4203 		 */
4204 		int			size_vars = size_guc_variables + size_guc_variables / 4;
4205 		struct config_generic **guc_vars;
4206 
4207 		if (size_vars == 0)
4208 		{
4209 			size_vars = 100;
4210 			guc_vars = (struct config_generic **)
4211 				guc_malloc(elevel, size_vars * sizeof(struct config_generic *));
4212 		}
4213 		else
4214 		{
4215 			guc_vars = (struct config_generic **)
4216 				guc_realloc(elevel, guc_variables, size_vars * sizeof(struct config_generic *));
4217 		}
4218 
4219 		if (guc_vars == NULL)
4220 			return false;		/* out of memory */
4221 
4222 		guc_variables = guc_vars;
4223 		size_guc_variables = size_vars;
4224 	}
4225 	guc_variables[num_guc_variables++] = var;
4226 	qsort((void *) guc_variables, num_guc_variables,
4227 		  sizeof(struct config_generic *), guc_var_compare);
4228 	return true;
4229 }
4230 
4231 /*
4232  * Create and add a placeholder variable for a custom variable name.
4233  */
4234 static struct config_generic *
add_placeholder_variable(const char * name,int elevel)4235 add_placeholder_variable(const char *name, int elevel)
4236 {
4237 	size_t		sz = sizeof(struct config_string) + sizeof(char *);
4238 	struct config_string *var;
4239 	struct config_generic *gen;
4240 
4241 	var = (struct config_string *) guc_malloc(elevel, sz);
4242 	if (var == NULL)
4243 		return NULL;
4244 	memset(var, 0, sz);
4245 	gen = &var->gen;
4246 
4247 	gen->name = guc_strdup(elevel, name);
4248 	if (gen->name == NULL)
4249 	{
4250 		free(var);
4251 		return NULL;
4252 	}
4253 
4254 	gen->context = PGC_USERSET;
4255 	gen->group = CUSTOM_OPTIONS;
4256 	gen->short_desc = "GUC placeholder variable";
4257 	gen->flags = GUC_NO_SHOW_ALL | GUC_NOT_IN_SAMPLE | GUC_CUSTOM_PLACEHOLDER;
4258 	gen->vartype = PGC_STRING;
4259 
4260 	/*
4261 	 * The char* is allocated at the end of the struct since we have no
4262 	 * 'static' place to point to.  Note that the current value, as well as
4263 	 * the boot and reset values, start out NULL.
4264 	 */
4265 	var->variable = (char **) (var + 1);
4266 
4267 	if (!add_guc_variable((struct config_generic *) var, elevel))
4268 	{
4269 		free((void *) gen->name);
4270 		free(var);
4271 		return NULL;
4272 	}
4273 
4274 	return gen;
4275 }
4276 
4277 /*
4278  * Look up option NAME.  If it exists, return a pointer to its record,
4279  * else return NULL.  If create_placeholders is TRUE, we'll create a
4280  * placeholder record for a valid-looking custom variable name.
4281  */
4282 static struct config_generic *
find_option(const char * name,bool create_placeholders,int elevel)4283 find_option(const char *name, bool create_placeholders, int elevel)
4284 {
4285 	const char **key = &name;
4286 	struct config_generic **res;
4287 	int			i;
4288 
4289 	Assert(name);
4290 
4291 	/*
4292 	 * By equating const char ** with struct config_generic *, we are assuming
4293 	 * the name field is first in config_generic.
4294 	 */
4295 	res = (struct config_generic **) bsearch((void *) &key,
4296 											 (void *) guc_variables,
4297 											 num_guc_variables,
4298 											 sizeof(struct config_generic *),
4299 											 guc_var_compare);
4300 	if (res)
4301 		return *res;
4302 
4303 	/*
4304 	 * See if the name is an obsolete name for a variable.  We assume that the
4305 	 * set of supported old names is short enough that a brute-force search is
4306 	 * the best way.
4307 	 */
4308 	for (i = 0; map_old_guc_names[i] != NULL; i += 2)
4309 	{
4310 		if (guc_name_compare(name, map_old_guc_names[i]) == 0)
4311 			return find_option(map_old_guc_names[i + 1], false, elevel);
4312 	}
4313 
4314 	if (create_placeholders)
4315 	{
4316 		/*
4317 		 * Check if the name is qualified, and if so, add a placeholder.
4318 		 */
4319 		if (strchr(name, GUC_QUALIFIER_SEPARATOR) != NULL)
4320 			return add_placeholder_variable(name, elevel);
4321 	}
4322 
4323 	/* Unknown name */
4324 	return NULL;
4325 }
4326 
4327 
4328 /*
4329  * comparator for qsorting and bsearching guc_variables array
4330  */
4331 static int
guc_var_compare(const void * a,const void * b)4332 guc_var_compare(const void *a, const void *b)
4333 {
4334 	const struct config_generic *confa = *(struct config_generic * const *) a;
4335 	const struct config_generic *confb = *(struct config_generic * const *) b;
4336 
4337 	return guc_name_compare(confa->name, confb->name);
4338 }
4339 
4340 /*
4341  * the bare comparison function for GUC names
4342  */
4343 static int
guc_name_compare(const char * namea,const char * nameb)4344 guc_name_compare(const char *namea, const char *nameb)
4345 {
4346 	/*
4347 	 * The temptation to use strcasecmp() here must be resisted, because the
4348 	 * array ordering has to remain stable across setlocale() calls. So, build
4349 	 * our own with a simple ASCII-only downcasing.
4350 	 */
4351 	while (*namea && *nameb)
4352 	{
4353 		char		cha = *namea++;
4354 		char		chb = *nameb++;
4355 
4356 		if (cha >= 'A' && cha <= 'Z')
4357 			cha += 'a' - 'A';
4358 		if (chb >= 'A' && chb <= 'Z')
4359 			chb += 'a' - 'A';
4360 		if (cha != chb)
4361 			return cha - chb;
4362 	}
4363 	if (*namea)
4364 		return 1;				/* a is longer */
4365 	if (*nameb)
4366 		return -1;				/* b is longer */
4367 	return 0;
4368 }
4369 
4370 
4371 /*
4372  * Initialize GUC options during program startup.
4373  *
4374  * Note that we cannot read the config file yet, since we have not yet
4375  * processed command-line switches.
4376  */
4377 void
InitializeGUCOptions(void)4378 InitializeGUCOptions(void)
4379 {
4380 	int			i;
4381 
4382 	/*
4383 	 * Before log_line_prefix could possibly receive a nonempty setting, make
4384 	 * sure that timezone processing is minimally alive (see elog.c).
4385 	 */
4386 	pg_timezone_initialize();
4387 
4388 	/*
4389 	 * Build sorted array of all GUC variables.
4390 	 */
4391 	build_guc_variables();
4392 
4393 	/*
4394 	 * Load all variables with their compiled-in defaults, and initialize
4395 	 * status fields as needed.
4396 	 */
4397 	for (i = 0; i < num_guc_variables; i++)
4398 	{
4399 		InitializeOneGUCOption(guc_variables[i]);
4400 	}
4401 
4402 	guc_dirty = false;
4403 
4404 	reporting_enabled = false;
4405 
4406 	/*
4407 	 * Prevent any attempt to override the transaction modes from
4408 	 * non-interactive sources.
4409 	 */
4410 	SetConfigOption("transaction_isolation", "default",
4411 					PGC_POSTMASTER, PGC_S_OVERRIDE);
4412 	SetConfigOption("transaction_read_only", "no",
4413 					PGC_POSTMASTER, PGC_S_OVERRIDE);
4414 	SetConfigOption("transaction_deferrable", "no",
4415 					PGC_POSTMASTER, PGC_S_OVERRIDE);
4416 
4417 	/*
4418 	 * For historical reasons, some GUC parameters can receive defaults from
4419 	 * environment variables.  Process those settings.
4420 	 */
4421 	InitializeGUCOptionsFromEnvironment();
4422 }
4423 
4424 /*
4425  * Assign any GUC values that can come from the server's environment.
4426  *
4427  * This is called from InitializeGUCOptions, and also from ProcessConfigFile
4428  * to deal with the possibility that a setting has been removed from
4429  * postgresql.conf and should now get a value from the environment.
4430  * (The latter is a kludge that should probably go away someday; if so,
4431  * fold this back into InitializeGUCOptions.)
4432  */
4433 static void
InitializeGUCOptionsFromEnvironment(void)4434 InitializeGUCOptionsFromEnvironment(void)
4435 {
4436 	char	   *env;
4437 	long		stack_rlimit;
4438 
4439 	env = getenv("PGPORT");
4440 	if (env != NULL)
4441 		SetConfigOption("port", env, PGC_POSTMASTER, PGC_S_ENV_VAR);
4442 
4443 	env = getenv("PGDATESTYLE");
4444 	if (env != NULL)
4445 		SetConfigOption("datestyle", env, PGC_POSTMASTER, PGC_S_ENV_VAR);
4446 
4447 	env = getenv("PGCLIENTENCODING");
4448 	if (env != NULL)
4449 		SetConfigOption("client_encoding", env, PGC_POSTMASTER, PGC_S_ENV_VAR);
4450 
4451 	/*
4452 	 * rlimit isn't exactly an "environment variable", but it behaves about
4453 	 * the same.  If we can identify the platform stack depth rlimit, increase
4454 	 * default stack depth setting up to whatever is safe (but at most 2MB).
4455 	 */
4456 	stack_rlimit = get_stack_depth_rlimit();
4457 	if (stack_rlimit > 0)
4458 	{
4459 		long		new_limit = (stack_rlimit - STACK_DEPTH_SLOP) / 1024L;
4460 
4461 		if (new_limit > 100)
4462 		{
4463 			char		limbuf[16];
4464 
4465 			new_limit = Min(new_limit, 2048);
4466 			sprintf(limbuf, "%ld", new_limit);
4467 			SetConfigOption("max_stack_depth", limbuf,
4468 							PGC_POSTMASTER, PGC_S_ENV_VAR);
4469 		}
4470 	}
4471 }
4472 
4473 /*
4474  * Initialize one GUC option variable to its compiled-in default.
4475  *
4476  * Note: the reason for calling check_hooks is not that we think the boot_val
4477  * might fail, but that the hooks might wish to compute an "extra" struct.
4478  */
4479 static void
InitializeOneGUCOption(struct config_generic * gconf)4480 InitializeOneGUCOption(struct config_generic * gconf)
4481 {
4482 	gconf->status = 0;
4483 	gconf->source = PGC_S_DEFAULT;
4484 	gconf->reset_source = PGC_S_DEFAULT;
4485 	gconf->scontext = PGC_INTERNAL;
4486 	gconf->reset_scontext = PGC_INTERNAL;
4487 	gconf->stack = NULL;
4488 	gconf->extra = NULL;
4489 	gconf->sourcefile = NULL;
4490 	gconf->sourceline = 0;
4491 
4492 	switch (gconf->vartype)
4493 	{
4494 		case PGC_BOOL:
4495 			{
4496 				struct config_bool *conf = (struct config_bool *) gconf;
4497 				bool		newval = conf->boot_val;
4498 				void	   *extra = NULL;
4499 
4500 				if (!call_bool_check_hook(conf, &newval, &extra,
4501 										  PGC_S_DEFAULT, LOG))
4502 					elog(FATAL, "failed to initialize %s to %d",
4503 						 conf->gen.name, (int) newval);
4504 				if (conf->assign_hook)
4505 					(*conf->assign_hook) (newval, extra);
4506 				*conf->variable = conf->reset_val = newval;
4507 				conf->gen.extra = conf->reset_extra = extra;
4508 				break;
4509 			}
4510 		case PGC_INT:
4511 			{
4512 				struct config_int *conf = (struct config_int *) gconf;
4513 				int			newval = conf->boot_val;
4514 				void	   *extra = NULL;
4515 
4516 				Assert(newval >= conf->min);
4517 				Assert(newval <= conf->max);
4518 				if (!call_int_check_hook(conf, &newval, &extra,
4519 										 PGC_S_DEFAULT, LOG))
4520 					elog(FATAL, "failed to initialize %s to %d",
4521 						 conf->gen.name, newval);
4522 				if (conf->assign_hook)
4523 					(*conf->assign_hook) (newval, extra);
4524 				*conf->variable = conf->reset_val = newval;
4525 				conf->gen.extra = conf->reset_extra = extra;
4526 				break;
4527 			}
4528 		case PGC_REAL:
4529 			{
4530 				struct config_real *conf = (struct config_real *) gconf;
4531 				double		newval = conf->boot_val;
4532 				void	   *extra = NULL;
4533 
4534 				Assert(newval >= conf->min);
4535 				Assert(newval <= conf->max);
4536 				if (!call_real_check_hook(conf, &newval, &extra,
4537 										  PGC_S_DEFAULT, LOG))
4538 					elog(FATAL, "failed to initialize %s to %g",
4539 						 conf->gen.name, newval);
4540 				if (conf->assign_hook)
4541 					(*conf->assign_hook) (newval, extra);
4542 				*conf->variable = conf->reset_val = newval;
4543 				conf->gen.extra = conf->reset_extra = extra;
4544 				break;
4545 			}
4546 		case PGC_STRING:
4547 			{
4548 				struct config_string *conf = (struct config_string *) gconf;
4549 				char	   *newval;
4550 				void	   *extra = NULL;
4551 
4552 				/* non-NULL boot_val must always get strdup'd */
4553 				if (conf->boot_val != NULL)
4554 					newval = guc_strdup(FATAL, conf->boot_val);
4555 				else
4556 					newval = NULL;
4557 
4558 				if (!call_string_check_hook(conf, &newval, &extra,
4559 											PGC_S_DEFAULT, LOG))
4560 					elog(FATAL, "failed to initialize %s to \"%s\"",
4561 						 conf->gen.name, newval ? newval : "");
4562 				if (conf->assign_hook)
4563 					(*conf->assign_hook) (newval, extra);
4564 				*conf->variable = conf->reset_val = newval;
4565 				conf->gen.extra = conf->reset_extra = extra;
4566 				break;
4567 			}
4568 		case PGC_ENUM:
4569 			{
4570 				struct config_enum *conf = (struct config_enum *) gconf;
4571 				int			newval = conf->boot_val;
4572 				void	   *extra = NULL;
4573 
4574 				if (!call_enum_check_hook(conf, &newval, &extra,
4575 										  PGC_S_DEFAULT, LOG))
4576 					elog(FATAL, "failed to initialize %s to %d",
4577 						 conf->gen.name, newval);
4578 				if (conf->assign_hook)
4579 					(*conf->assign_hook) (newval, extra);
4580 				*conf->variable = conf->reset_val = newval;
4581 				conf->gen.extra = conf->reset_extra = extra;
4582 				break;
4583 			}
4584 	}
4585 }
4586 
4587 
4588 /*
4589  * Select the configuration files and data directory to be used, and
4590  * do the initial read of postgresql.conf.
4591  *
4592  * This is called after processing command-line switches.
4593  *		userDoption is the -D switch value if any (NULL if unspecified).
4594  *		progname is just for use in error messages.
4595  *
4596  * Returns true on success; on failure, prints a suitable error message
4597  * to stderr and returns false.
4598  */
4599 bool
SelectConfigFiles(const char * userDoption,const char * progname)4600 SelectConfigFiles(const char *userDoption, const char *progname)
4601 {
4602 	char	   *configdir;
4603 	char	   *fname;
4604 	struct stat stat_buf;
4605 
4606 	/* configdir is -D option, or $PGDATA if no -D */
4607 	if (userDoption)
4608 		configdir = make_absolute_path(userDoption);
4609 	else
4610 		configdir = make_absolute_path(getenv("PGDATA"));
4611 
4612 	if (configdir && stat(configdir, &stat_buf) != 0)
4613 	{
4614 		write_stderr("%s: could not access directory \"%s\": %s\n",
4615 					 progname,
4616 					 configdir,
4617 					 strerror(errno));
4618 		if (errno == ENOENT)
4619 			write_stderr("Run initdb or pg_basebackup to initialize a PostgreSQL data directory.\n");
4620 		return false;
4621 	}
4622 
4623 	/*
4624 	 * Find the configuration file: if config_file was specified on the
4625 	 * command line, use it, else use configdir/postgresql.conf.  In any case
4626 	 * ensure the result is an absolute path, so that it will be interpreted
4627 	 * the same way by future backends.
4628 	 */
4629 	if (ConfigFileName)
4630 		fname = make_absolute_path(ConfigFileName);
4631 	else if (configdir)
4632 	{
4633 		fname = guc_malloc(FATAL,
4634 						   strlen(configdir) + strlen(CONFIG_FILENAME) + 2);
4635 		sprintf(fname, "%s/%s", configdir, CONFIG_FILENAME);
4636 	}
4637 	else
4638 	{
4639 		write_stderr("%s does not know where to find the server configuration file.\n"
4640 					 "You must specify the --config-file or -D invocation "
4641 					 "option or set the PGDATA environment variable.\n",
4642 					 progname);
4643 		return false;
4644 	}
4645 
4646 	/*
4647 	 * Set the ConfigFileName GUC variable to its final value, ensuring that
4648 	 * it can't be overridden later.
4649 	 */
4650 	SetConfigOption("config_file", fname, PGC_POSTMASTER, PGC_S_OVERRIDE);
4651 	free(fname);
4652 
4653 	/*
4654 	 * Now read the config file for the first time.
4655 	 */
4656 	if (stat(ConfigFileName, &stat_buf) != 0)
4657 	{
4658 		write_stderr("%s: could not access the server configuration file \"%s\": %s\n",
4659 					 progname, ConfigFileName, strerror(errno));
4660 		free(configdir);
4661 		return false;
4662 	}
4663 
4664 	/*
4665 	 * Read the configuration file for the first time.  This time only the
4666 	 * data_directory parameter is picked up to determine the data directory,
4667 	 * so that we can read the PG_AUTOCONF_FILENAME file next time.
4668 	 */
4669 	ProcessConfigFile(PGC_POSTMASTER);
4670 
4671 	/*
4672 	 * If the data_directory GUC variable has been set, use that as DataDir;
4673 	 * otherwise use configdir if set; else punt.
4674 	 *
4675 	 * Note: SetDataDir will copy and absolute-ize its argument, so we don't
4676 	 * have to.
4677 	 */
4678 	if (data_directory)
4679 		SetDataDir(data_directory);
4680 	else if (configdir)
4681 		SetDataDir(configdir);
4682 	else
4683 	{
4684 		write_stderr("%s does not know where to find the database system data.\n"
4685 					 "This can be specified as \"data_directory\" in \"%s\", "
4686 					 "or by the -D invocation option, or by the "
4687 					 "PGDATA environment variable.\n",
4688 					 progname, ConfigFileName);
4689 		return false;
4690 	}
4691 
4692 	/*
4693 	 * Reflect the final DataDir value back into the data_directory GUC var.
4694 	 * (If you are wondering why we don't just make them a single variable,
4695 	 * it's because the EXEC_BACKEND case needs DataDir to be transmitted to
4696 	 * child backends specially.  XXX is that still true?  Given that we now
4697 	 * chdir to DataDir, EXEC_BACKEND can read the config file without knowing
4698 	 * DataDir in advance.)
4699 	 */
4700 	SetConfigOption("data_directory", DataDir, PGC_POSTMASTER, PGC_S_OVERRIDE);
4701 
4702 	/*
4703 	 * Now read the config file a second time, allowing any settings in the
4704 	 * PG_AUTOCONF_FILENAME file to take effect.  (This is pretty ugly, but
4705 	 * since we have to determine the DataDir before we can find the autoconf
4706 	 * file, the alternatives seem worse.)
4707 	 */
4708 	ProcessConfigFile(PGC_POSTMASTER);
4709 
4710 	/*
4711 	 * If timezone_abbreviations wasn't set in the configuration file, install
4712 	 * the default value.  We do it this way because we can't safely install a
4713 	 * "real" value until my_exec_path is set, which may not have happened
4714 	 * when InitializeGUCOptions runs, so the bootstrap default value cannot
4715 	 * be the real desired default.
4716 	 */
4717 	pg_timezone_abbrev_initialize();
4718 
4719 	/*
4720 	 * Figure out where pg_hba.conf is, and make sure the path is absolute.
4721 	 */
4722 	if (HbaFileName)
4723 		fname = make_absolute_path(HbaFileName);
4724 	else if (configdir)
4725 	{
4726 		fname = guc_malloc(FATAL,
4727 						   strlen(configdir) + strlen(HBA_FILENAME) + 2);
4728 		sprintf(fname, "%s/%s", configdir, HBA_FILENAME);
4729 	}
4730 	else
4731 	{
4732 		write_stderr("%s does not know where to find the \"hba\" configuration file.\n"
4733 					 "This can be specified as \"hba_file\" in \"%s\", "
4734 					 "or by the -D invocation option, or by the "
4735 					 "PGDATA environment variable.\n",
4736 					 progname, ConfigFileName);
4737 		return false;
4738 	}
4739 	SetConfigOption("hba_file", fname, PGC_POSTMASTER, PGC_S_OVERRIDE);
4740 	free(fname);
4741 
4742 	/*
4743 	 * Likewise for pg_ident.conf.
4744 	 */
4745 	if (IdentFileName)
4746 		fname = make_absolute_path(IdentFileName);
4747 	else if (configdir)
4748 	{
4749 		fname = guc_malloc(FATAL,
4750 						   strlen(configdir) + strlen(IDENT_FILENAME) + 2);
4751 		sprintf(fname, "%s/%s", configdir, IDENT_FILENAME);
4752 	}
4753 	else
4754 	{
4755 		write_stderr("%s does not know where to find the \"ident\" configuration file.\n"
4756 					 "This can be specified as \"ident_file\" in \"%s\", "
4757 					 "or by the -D invocation option, or by the "
4758 					 "PGDATA environment variable.\n",
4759 					 progname, ConfigFileName);
4760 		return false;
4761 	}
4762 	SetConfigOption("ident_file", fname, PGC_POSTMASTER, PGC_S_OVERRIDE);
4763 	free(fname);
4764 
4765 	free(configdir);
4766 
4767 	return true;
4768 }
4769 
4770 
4771 /*
4772  * Reset all options to their saved default values (implements RESET ALL)
4773  */
4774 void
ResetAllOptions(void)4775 ResetAllOptions(void)
4776 {
4777 	int			i;
4778 
4779 	for (i = 0; i < num_guc_variables; i++)
4780 	{
4781 		struct config_generic *gconf = guc_variables[i];
4782 
4783 		/* Don't reset non-SET-able values */
4784 		if (gconf->context != PGC_SUSET &&
4785 			gconf->context != PGC_USERSET)
4786 			continue;
4787 		/* Don't reset if special exclusion from RESET ALL */
4788 		if (gconf->flags & GUC_NO_RESET_ALL)
4789 			continue;
4790 		/* No need to reset if wasn't SET */
4791 		if (gconf->source <= PGC_S_OVERRIDE)
4792 			continue;
4793 
4794 		/* Save old value to support transaction abort */
4795 		push_old_value(gconf, GUC_ACTION_SET);
4796 
4797 		switch (gconf->vartype)
4798 		{
4799 			case PGC_BOOL:
4800 				{
4801 					struct config_bool *conf = (struct config_bool *) gconf;
4802 
4803 					if (conf->assign_hook)
4804 						(*conf->assign_hook) (conf->reset_val,
4805 											  conf->reset_extra);
4806 					*conf->variable = conf->reset_val;
4807 					set_extra_field(&conf->gen, &conf->gen.extra,
4808 									conf->reset_extra);
4809 					break;
4810 				}
4811 			case PGC_INT:
4812 				{
4813 					struct config_int *conf = (struct config_int *) gconf;
4814 
4815 					if (conf->assign_hook)
4816 						(*conf->assign_hook) (conf->reset_val,
4817 											  conf->reset_extra);
4818 					*conf->variable = conf->reset_val;
4819 					set_extra_field(&conf->gen, &conf->gen.extra,
4820 									conf->reset_extra);
4821 					break;
4822 				}
4823 			case PGC_REAL:
4824 				{
4825 					struct config_real *conf = (struct config_real *) gconf;
4826 
4827 					if (conf->assign_hook)
4828 						(*conf->assign_hook) (conf->reset_val,
4829 											  conf->reset_extra);
4830 					*conf->variable = conf->reset_val;
4831 					set_extra_field(&conf->gen, &conf->gen.extra,
4832 									conf->reset_extra);
4833 					break;
4834 				}
4835 			case PGC_STRING:
4836 				{
4837 					struct config_string *conf = (struct config_string *) gconf;
4838 
4839 					if (conf->assign_hook)
4840 						(*conf->assign_hook) (conf->reset_val,
4841 											  conf->reset_extra);
4842 					set_string_field(conf, conf->variable, conf->reset_val);
4843 					set_extra_field(&conf->gen, &conf->gen.extra,
4844 									conf->reset_extra);
4845 					break;
4846 				}
4847 			case PGC_ENUM:
4848 				{
4849 					struct config_enum *conf = (struct config_enum *) gconf;
4850 
4851 					if (conf->assign_hook)
4852 						(*conf->assign_hook) (conf->reset_val,
4853 											  conf->reset_extra);
4854 					*conf->variable = conf->reset_val;
4855 					set_extra_field(&conf->gen, &conf->gen.extra,
4856 									conf->reset_extra);
4857 					break;
4858 				}
4859 		}
4860 
4861 		gconf->source = gconf->reset_source;
4862 		gconf->scontext = gconf->reset_scontext;
4863 
4864 		if (gconf->flags & GUC_REPORT)
4865 			ReportGUCOption(gconf);
4866 	}
4867 }
4868 
4869 
4870 /*
4871  * push_old_value
4872  *		Push previous state during transactional assignment to a GUC variable.
4873  */
4874 static void
push_old_value(struct config_generic * gconf,GucAction action)4875 push_old_value(struct config_generic * gconf, GucAction action)
4876 {
4877 	GucStack   *stack;
4878 
4879 	/* If we're not inside a nest level, do nothing */
4880 	if (GUCNestLevel == 0)
4881 		return;
4882 
4883 	/* Do we already have a stack entry of the current nest level? */
4884 	stack = gconf->stack;
4885 	if (stack && stack->nest_level >= GUCNestLevel)
4886 	{
4887 		/* Yes, so adjust its state if necessary */
4888 		Assert(stack->nest_level == GUCNestLevel);
4889 		switch (action)
4890 		{
4891 			case GUC_ACTION_SET:
4892 				/* SET overrides any prior action at same nest level */
4893 				if (stack->state == GUC_SET_LOCAL)
4894 				{
4895 					/* must discard old masked value */
4896 					discard_stack_value(gconf, &stack->masked);
4897 				}
4898 				stack->state = GUC_SET;
4899 				break;
4900 			case GUC_ACTION_LOCAL:
4901 				if (stack->state == GUC_SET)
4902 				{
4903 					/* SET followed by SET LOCAL, remember SET's value */
4904 					stack->masked_scontext = gconf->scontext;
4905 					set_stack_value(gconf, &stack->masked);
4906 					stack->state = GUC_SET_LOCAL;
4907 				}
4908 				/* in all other cases, no change to stack entry */
4909 				break;
4910 			case GUC_ACTION_SAVE:
4911 				/* Could only have a prior SAVE of same variable */
4912 				Assert(stack->state == GUC_SAVE);
4913 				break;
4914 		}
4915 		Assert(guc_dirty);		/* must be set already */
4916 		return;
4917 	}
4918 
4919 	/*
4920 	 * Push a new stack entry
4921 	 *
4922 	 * We keep all the stack entries in TopTransactionContext for simplicity.
4923 	 */
4924 	stack = (GucStack *) MemoryContextAllocZero(TopTransactionContext,
4925 												sizeof(GucStack));
4926 
4927 	stack->prev = gconf->stack;
4928 	stack->nest_level = GUCNestLevel;
4929 	switch (action)
4930 	{
4931 		case GUC_ACTION_SET:
4932 			stack->state = GUC_SET;
4933 			break;
4934 		case GUC_ACTION_LOCAL:
4935 			stack->state = GUC_LOCAL;
4936 			break;
4937 		case GUC_ACTION_SAVE:
4938 			stack->state = GUC_SAVE;
4939 			break;
4940 	}
4941 	stack->source = gconf->source;
4942 	stack->scontext = gconf->scontext;
4943 	set_stack_value(gconf, &stack->prior);
4944 
4945 	gconf->stack = stack;
4946 
4947 	/* Ensure we remember to pop at end of xact */
4948 	guc_dirty = true;
4949 }
4950 
4951 
4952 /*
4953  * Do GUC processing at main transaction start.
4954  */
4955 void
AtStart_GUC(void)4956 AtStart_GUC(void)
4957 {
4958 	/*
4959 	 * The nest level should be 0 between transactions; if it isn't, somebody
4960 	 * didn't call AtEOXact_GUC, or called it with the wrong nestLevel.  We
4961 	 * throw a warning but make no other effort to clean up.
4962 	 */
4963 	if (GUCNestLevel != 0)
4964 		elog(WARNING, "GUC nest level = %d at transaction start",
4965 			 GUCNestLevel);
4966 	GUCNestLevel = 1;
4967 }
4968 
4969 /*
4970  * Enter a new nesting level for GUC values.  This is called at subtransaction
4971  * start, and when entering a function that has proconfig settings, and in
4972  * some other places where we want to set GUC variables transiently.
4973  * NOTE we must not risk error here, else subtransaction start will be unhappy.
4974  */
4975 int
NewGUCNestLevel(void)4976 NewGUCNestLevel(void)
4977 {
4978 	return ++GUCNestLevel;
4979 }
4980 
4981 /*
4982  * Do GUC processing at transaction or subtransaction commit or abort, or
4983  * when exiting a function that has proconfig settings, or when undoing a
4984  * transient assignment to some GUC variables.  (The name is thus a bit of
4985  * a misnomer; perhaps it should be ExitGUCNestLevel or some such.)
4986  * During abort, we discard all GUC settings that were applied at nesting
4987  * levels >= nestLevel.  nestLevel == 1 corresponds to the main transaction.
4988  */
4989 void
AtEOXact_GUC(bool isCommit,int nestLevel)4990 AtEOXact_GUC(bool isCommit, int nestLevel)
4991 {
4992 	bool		still_dirty;
4993 	int			i;
4994 
4995 	/*
4996 	 * Note: it's possible to get here with GUCNestLevel == nestLevel-1 during
4997 	 * abort, if there is a failure during transaction start before
4998 	 * AtStart_GUC is called.
4999 	 */
5000 	Assert(nestLevel > 0 &&
5001 		   (nestLevel <= GUCNestLevel ||
5002 			(nestLevel == GUCNestLevel + 1 && !isCommit)));
5003 
5004 	/* Quick exit if nothing's changed in this transaction */
5005 	if (!guc_dirty)
5006 	{
5007 		GUCNestLevel = nestLevel - 1;
5008 		return;
5009 	}
5010 
5011 	still_dirty = false;
5012 	for (i = 0; i < num_guc_variables; i++)
5013 	{
5014 		struct config_generic *gconf = guc_variables[i];
5015 		GucStack   *stack;
5016 
5017 		/*
5018 		 * Process and pop each stack entry within the nest level. To simplify
5019 		 * fmgr_security_definer() and other places that use GUC_ACTION_SAVE,
5020 		 * we allow failure exit from code that uses a local nest level to be
5021 		 * recovered at the surrounding transaction or subtransaction abort;
5022 		 * so there could be more than one stack entry to pop.
5023 		 */
5024 		while ((stack = gconf->stack) != NULL &&
5025 			   stack->nest_level >= nestLevel)
5026 		{
5027 			GucStack   *prev = stack->prev;
5028 			bool		restorePrior = false;
5029 			bool		restoreMasked = false;
5030 			bool		changed;
5031 
5032 			/*
5033 			 * In this next bit, if we don't set either restorePrior or
5034 			 * restoreMasked, we must "discard" any unwanted fields of the
5035 			 * stack entries to avoid leaking memory.  If we do set one of
5036 			 * those flags, unused fields will be cleaned up after restoring.
5037 			 */
5038 			if (!isCommit)		/* if abort, always restore prior value */
5039 				restorePrior = true;
5040 			else if (stack->state == GUC_SAVE)
5041 				restorePrior = true;
5042 			else if (stack->nest_level == 1)
5043 			{
5044 				/* transaction commit */
5045 				if (stack->state == GUC_SET_LOCAL)
5046 					restoreMasked = true;
5047 				else if (stack->state == GUC_SET)
5048 				{
5049 					/* we keep the current active value */
5050 					discard_stack_value(gconf, &stack->prior);
5051 				}
5052 				else	/* must be GUC_LOCAL */
5053 					restorePrior = true;
5054 			}
5055 			else if (prev == NULL ||
5056 					 prev->nest_level < stack->nest_level - 1)
5057 			{
5058 				/* decrement entry's level and do not pop it */
5059 				stack->nest_level--;
5060 				continue;
5061 			}
5062 			else
5063 			{
5064 				/*
5065 				 * We have to merge this stack entry into prev. See README for
5066 				 * discussion of this bit.
5067 				 */
5068 				switch (stack->state)
5069 				{
5070 					case GUC_SAVE:
5071 						Assert(false);	/* can't get here */
5072 
5073 					case GUC_SET:
5074 						/* next level always becomes SET */
5075 						discard_stack_value(gconf, &stack->prior);
5076 						if (prev->state == GUC_SET_LOCAL)
5077 							discard_stack_value(gconf, &prev->masked);
5078 						prev->state = GUC_SET;
5079 						break;
5080 
5081 					case GUC_LOCAL:
5082 						if (prev->state == GUC_SET)
5083 						{
5084 							/* LOCAL migrates down */
5085 							prev->masked_scontext = stack->scontext;
5086 							prev->masked = stack->prior;
5087 							prev->state = GUC_SET_LOCAL;
5088 						}
5089 						else
5090 						{
5091 							/* else just forget this stack level */
5092 							discard_stack_value(gconf, &stack->prior);
5093 						}
5094 						break;
5095 
5096 					case GUC_SET_LOCAL:
5097 						/* prior state at this level no longer wanted */
5098 						discard_stack_value(gconf, &stack->prior);
5099 						/* copy down the masked state */
5100 						prev->masked_scontext = stack->masked_scontext;
5101 						if (prev->state == GUC_SET_LOCAL)
5102 							discard_stack_value(gconf, &prev->masked);
5103 						prev->masked = stack->masked;
5104 						prev->state = GUC_SET_LOCAL;
5105 						break;
5106 				}
5107 			}
5108 
5109 			changed = false;
5110 
5111 			if (restorePrior || restoreMasked)
5112 			{
5113 				/* Perform appropriate restoration of the stacked value */
5114 				config_var_value newvalue;
5115 				GucSource	newsource;
5116 				GucContext	newscontext;
5117 
5118 				if (restoreMasked)
5119 				{
5120 					newvalue = stack->masked;
5121 					newsource = PGC_S_SESSION;
5122 					newscontext = stack->masked_scontext;
5123 				}
5124 				else
5125 				{
5126 					newvalue = stack->prior;
5127 					newsource = stack->source;
5128 					newscontext = stack->scontext;
5129 				}
5130 
5131 				switch (gconf->vartype)
5132 				{
5133 					case PGC_BOOL:
5134 						{
5135 							struct config_bool *conf = (struct config_bool *) gconf;
5136 							bool		newval = newvalue.val.boolval;
5137 							void	   *newextra = newvalue.extra;
5138 
5139 							if (*conf->variable != newval ||
5140 								conf->gen.extra != newextra)
5141 							{
5142 								if (conf->assign_hook)
5143 									(*conf->assign_hook) (newval, newextra);
5144 								*conf->variable = newval;
5145 								set_extra_field(&conf->gen, &conf->gen.extra,
5146 												newextra);
5147 								changed = true;
5148 							}
5149 							break;
5150 						}
5151 					case PGC_INT:
5152 						{
5153 							struct config_int *conf = (struct config_int *) gconf;
5154 							int			newval = newvalue.val.intval;
5155 							void	   *newextra = newvalue.extra;
5156 
5157 							if (*conf->variable != newval ||
5158 								conf->gen.extra != newextra)
5159 							{
5160 								if (conf->assign_hook)
5161 									(*conf->assign_hook) (newval, newextra);
5162 								*conf->variable = newval;
5163 								set_extra_field(&conf->gen, &conf->gen.extra,
5164 												newextra);
5165 								changed = true;
5166 							}
5167 							break;
5168 						}
5169 					case PGC_REAL:
5170 						{
5171 							struct config_real *conf = (struct config_real *) gconf;
5172 							double		newval = newvalue.val.realval;
5173 							void	   *newextra = newvalue.extra;
5174 
5175 							if (*conf->variable != newval ||
5176 								conf->gen.extra != newextra)
5177 							{
5178 								if (conf->assign_hook)
5179 									(*conf->assign_hook) (newval, newextra);
5180 								*conf->variable = newval;
5181 								set_extra_field(&conf->gen, &conf->gen.extra,
5182 												newextra);
5183 								changed = true;
5184 							}
5185 							break;
5186 						}
5187 					case PGC_STRING:
5188 						{
5189 							struct config_string *conf = (struct config_string *) gconf;
5190 							char	   *newval = newvalue.val.stringval;
5191 							void	   *newextra = newvalue.extra;
5192 
5193 							if (*conf->variable != newval ||
5194 								conf->gen.extra != newextra)
5195 							{
5196 								if (conf->assign_hook)
5197 									(*conf->assign_hook) (newval, newextra);
5198 								set_string_field(conf, conf->variable, newval);
5199 								set_extra_field(&conf->gen, &conf->gen.extra,
5200 												newextra);
5201 								changed = true;
5202 							}
5203 
5204 							/*
5205 							 * Release stacked values if not used anymore. We
5206 							 * could use discard_stack_value() here, but since
5207 							 * we have type-specific code anyway, might as
5208 							 * well inline it.
5209 							 */
5210 							set_string_field(conf, &stack->prior.val.stringval, NULL);
5211 							set_string_field(conf, &stack->masked.val.stringval, NULL);
5212 							break;
5213 						}
5214 					case PGC_ENUM:
5215 						{
5216 							struct config_enum *conf = (struct config_enum *) gconf;
5217 							int			newval = newvalue.val.enumval;
5218 							void	   *newextra = newvalue.extra;
5219 
5220 							if (*conf->variable != newval ||
5221 								conf->gen.extra != newextra)
5222 							{
5223 								if (conf->assign_hook)
5224 									(*conf->assign_hook) (newval, newextra);
5225 								*conf->variable = newval;
5226 								set_extra_field(&conf->gen, &conf->gen.extra,
5227 												newextra);
5228 								changed = true;
5229 							}
5230 							break;
5231 						}
5232 				}
5233 
5234 				/*
5235 				 * Release stacked extra values if not used anymore.
5236 				 */
5237 				set_extra_field(gconf, &(stack->prior.extra), NULL);
5238 				set_extra_field(gconf, &(stack->masked.extra), NULL);
5239 
5240 				/* And restore source information */
5241 				gconf->source = newsource;
5242 				gconf->scontext = newscontext;
5243 			}
5244 
5245 			/* Finish popping the state stack */
5246 			gconf->stack = prev;
5247 			pfree(stack);
5248 
5249 			/* Report new value if we changed it */
5250 			if (changed && (gconf->flags & GUC_REPORT))
5251 				ReportGUCOption(gconf);
5252 		}						/* end of stack-popping loop */
5253 
5254 		if (stack != NULL)
5255 			still_dirty = true;
5256 	}
5257 
5258 	/* If there are no remaining stack entries, we can reset guc_dirty */
5259 	guc_dirty = still_dirty;
5260 
5261 	/* Update nesting level */
5262 	GUCNestLevel = nestLevel - 1;
5263 }
5264 
5265 
5266 /*
5267  * Start up automatic reporting of changes to variables marked GUC_REPORT.
5268  * This is executed at completion of backend startup.
5269  */
5270 void
BeginReportingGUCOptions(void)5271 BeginReportingGUCOptions(void)
5272 {
5273 	int			i;
5274 
5275 	/*
5276 	 * Don't do anything unless talking to an interactive frontend of protocol
5277 	 * 3.0 or later.
5278 	 */
5279 	if (whereToSendOutput != DestRemote ||
5280 		PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
5281 		return;
5282 
5283 	reporting_enabled = true;
5284 
5285 	/* Transmit initial values of interesting variables */
5286 	for (i = 0; i < num_guc_variables; i++)
5287 	{
5288 		struct config_generic *conf = guc_variables[i];
5289 
5290 		if (conf->flags & GUC_REPORT)
5291 			ReportGUCOption(conf);
5292 	}
5293 }
5294 
5295 /*
5296  * ReportGUCOption: if appropriate, transmit option value to frontend
5297  */
5298 static void
ReportGUCOption(struct config_generic * record)5299 ReportGUCOption(struct config_generic * record)
5300 {
5301 	if (reporting_enabled && (record->flags & GUC_REPORT))
5302 	{
5303 		char	   *val = _ShowOption(record, false);
5304 		StringInfoData msgbuf;
5305 
5306 		pq_beginmessage(&msgbuf, 'S');
5307 		pq_sendstring(&msgbuf, record->name);
5308 		pq_sendstring(&msgbuf, val);
5309 		pq_endmessage(&msgbuf);
5310 
5311 		pfree(val);
5312 	}
5313 }
5314 
5315 /*
5316  * Convert a value from one of the human-friendly units ("kB", "min" etc.)
5317  * to the given base unit.  'value' and 'unit' are the input value and unit
5318  * to convert from.  The converted value is stored in *base_value.
5319  *
5320  * Returns true on success, false if the input unit is not recognized.
5321  */
5322 static bool
convert_to_base_unit(int64 value,const char * unit,int base_unit,int64 * base_value)5323 convert_to_base_unit(int64 value, const char *unit,
5324 					 int base_unit, int64 *base_value)
5325 {
5326 	const unit_conversion *table;
5327 	int			i;
5328 
5329 	if (base_unit & GUC_UNIT_MEMORY)
5330 		table = memory_unit_conversion_table;
5331 	else
5332 		table = time_unit_conversion_table;
5333 
5334 	for (i = 0; *table[i].unit; i++)
5335 	{
5336 		if (base_unit == table[i].base_unit &&
5337 			strcmp(unit, table[i].unit) == 0)
5338 		{
5339 			if (table[i].multiplier < 0)
5340 				*base_value = value / (-table[i].multiplier);
5341 			else
5342 				*base_value = value * table[i].multiplier;
5343 			return true;
5344 		}
5345 	}
5346 	return false;
5347 }
5348 
5349 /*
5350  * Convert a value in some base unit to a human-friendly unit.  The output
5351  * unit is chosen so that it's the greatest unit that can represent the value
5352  * without loss.  For example, if the base unit is GUC_UNIT_KB, 1024 is
5353  * converted to 1 MB, but 1025 is represented as 1025 kB.
5354  */
5355 static void
convert_from_base_unit(int64 base_value,int base_unit,int64 * value,const char ** unit)5356 convert_from_base_unit(int64 base_value, int base_unit,
5357 					   int64 *value, const char **unit)
5358 {
5359 	const unit_conversion *table;
5360 	int			i;
5361 
5362 	*unit = NULL;
5363 
5364 	if (base_unit & GUC_UNIT_MEMORY)
5365 		table = memory_unit_conversion_table;
5366 	else
5367 		table = time_unit_conversion_table;
5368 
5369 	for (i = 0; *table[i].unit; i++)
5370 	{
5371 		if (base_unit == table[i].base_unit)
5372 		{
5373 			/*
5374 			 * Accept the first conversion that divides the value evenly. We
5375 			 * assume that the conversions for each base unit are ordered from
5376 			 * greatest unit to the smallest!
5377 			 */
5378 			if (table[i].multiplier < 0)
5379 			{
5380 				*value = base_value * (-table[i].multiplier);
5381 				*unit = table[i].unit;
5382 				break;
5383 			}
5384 			else if (base_value % table[i].multiplier == 0)
5385 			{
5386 				*value = base_value / table[i].multiplier;
5387 				*unit = table[i].unit;
5388 				break;
5389 			}
5390 		}
5391 	}
5392 
5393 	Assert(*unit != NULL);
5394 }
5395 
5396 
5397 /*
5398  * Try to parse value as an integer.  The accepted formats are the
5399  * usual decimal, octal, or hexadecimal formats, optionally followed by
5400  * a unit name if "flags" indicates a unit is allowed.
5401  *
5402  * If the string parses okay, return true, else false.
5403  * If okay and result is not NULL, return the value in *result.
5404  * If not okay and hintmsg is not NULL, *hintmsg is set to a suitable
5405  *	HINT message, or NULL if no hint provided.
5406  */
5407 bool
parse_int(const char * value,int * result,int flags,const char ** hintmsg)5408 parse_int(const char *value, int *result, int flags, const char **hintmsg)
5409 {
5410 	int64		val;
5411 	char	   *endptr;
5412 
5413 	/* To suppress compiler warnings, always set output params */
5414 	if (result)
5415 		*result = 0;
5416 	if (hintmsg)
5417 		*hintmsg = NULL;
5418 
5419 	/* We assume here that int64 is at least as wide as long */
5420 	errno = 0;
5421 	val = strtol(value, &endptr, 0);
5422 
5423 	if (endptr == value)
5424 		return false;			/* no HINT for integer syntax error */
5425 
5426 	if (errno == ERANGE || val != (int64) ((int32) val))
5427 	{
5428 		if (hintmsg)
5429 			*hintmsg = gettext_noop("Value exceeds integer range.");
5430 		return false;
5431 	}
5432 
5433 	/* allow whitespace between integer and unit */
5434 	while (isspace((unsigned char) *endptr))
5435 		endptr++;
5436 
5437 	/* Handle possible unit */
5438 	if (*endptr != '\0')
5439 	{
5440 		char		unit[MAX_UNIT_LEN + 1];
5441 		int			unitlen;
5442 		bool		converted = false;
5443 
5444 		if ((flags & GUC_UNIT) == 0)
5445 			return false;		/* this setting does not accept a unit */
5446 
5447 		unitlen = 0;
5448 		while (*endptr != '\0' && !isspace((unsigned char) *endptr) &&
5449 			   unitlen < MAX_UNIT_LEN)
5450 			unit[unitlen++] = *(endptr++);
5451 		unit[unitlen] = '\0';
5452 		/* allow whitespace after unit */
5453 		while (isspace((unsigned char) *endptr))
5454 			endptr++;
5455 
5456 		if (*endptr == '\0')
5457 			converted = convert_to_base_unit(val, unit, (flags & GUC_UNIT),
5458 											 &val);
5459 		if (!converted)
5460 		{
5461 			/* invalid unit, or garbage after the unit; set hint and fail. */
5462 			if (hintmsg)
5463 			{
5464 				if (flags & GUC_UNIT_MEMORY)
5465 					*hintmsg = memory_units_hint;
5466 				else
5467 					*hintmsg = time_units_hint;
5468 			}
5469 			return false;
5470 		}
5471 
5472 		/* Check for overflow due to units conversion */
5473 		if (val != (int64) ((int32) val))
5474 		{
5475 			if (hintmsg)
5476 				*hintmsg = gettext_noop("Value exceeds integer range.");
5477 			return false;
5478 		}
5479 	}
5480 
5481 	if (result)
5482 		*result = (int) val;
5483 	return true;
5484 }
5485 
5486 
5487 
5488 /*
5489  * Try to parse value as a floating point number in the usual format.
5490  * If the string parses okay, return true, else false.
5491  * If okay and result is not NULL, return the value in *result.
5492  */
5493 bool
parse_real(const char * value,double * result)5494 parse_real(const char *value, double *result)
5495 {
5496 	double		val;
5497 	char	   *endptr;
5498 
5499 	if (result)
5500 		*result = 0;			/* suppress compiler warning */
5501 
5502 	errno = 0;
5503 	val = strtod(value, &endptr);
5504 	if (endptr == value || errno == ERANGE)
5505 		return false;
5506 
5507 	/* reject NaN (infinities will fail range checks later) */
5508 	if (isnan(val))
5509 		return false;
5510 
5511 	/* allow whitespace after number */
5512 	while (isspace((unsigned char) *endptr))
5513 		endptr++;
5514 	if (*endptr != '\0')
5515 		return false;
5516 
5517 	if (result)
5518 		*result = val;
5519 	return true;
5520 }
5521 
5522 
5523 /*
5524  * Lookup the name for an enum option with the selected value.
5525  * Should only ever be called with known-valid values, so throws
5526  * an elog(ERROR) if the enum option is not found.
5527  *
5528  * The returned string is a pointer to static data and not
5529  * allocated for modification.
5530  */
5531 const char *
config_enum_lookup_by_value(struct config_enum * record,int val)5532 config_enum_lookup_by_value(struct config_enum * record, int val)
5533 {
5534 	const struct config_enum_entry *entry;
5535 
5536 	for (entry = record->options; entry && entry->name; entry++)
5537 	{
5538 		if (entry->val == val)
5539 			return entry->name;
5540 	}
5541 
5542 	elog(ERROR, "could not find enum option %d for %s",
5543 		 val, record->gen.name);
5544 	return NULL;				/* silence compiler */
5545 }
5546 
5547 
5548 /*
5549  * Lookup the value for an enum option with the selected name
5550  * (case-insensitive).
5551  * If the enum option is found, sets the retval value and returns
5552  * true. If it's not found, return FALSE and retval is set to 0.
5553  */
5554 bool
config_enum_lookup_by_name(struct config_enum * record,const char * value,int * retval)5555 config_enum_lookup_by_name(struct config_enum * record, const char *value,
5556 						   int *retval)
5557 {
5558 	const struct config_enum_entry *entry;
5559 
5560 	for (entry = record->options; entry && entry->name; entry++)
5561 	{
5562 		if (pg_strcasecmp(value, entry->name) == 0)
5563 		{
5564 			*retval = entry->val;
5565 			return TRUE;
5566 		}
5567 	}
5568 
5569 	*retval = 0;
5570 	return FALSE;
5571 }
5572 
5573 
5574 /*
5575  * Return a list of all available options for an enum, excluding
5576  * hidden ones, separated by the given separator.
5577  * If prefix is non-NULL, it is added before the first enum value.
5578  * If suffix is non-NULL, it is added to the end of the string.
5579  */
5580 static char *
config_enum_get_options(struct config_enum * record,const char * prefix,const char * suffix,const char * separator)5581 config_enum_get_options(struct config_enum * record, const char *prefix,
5582 						const char *suffix, const char *separator)
5583 {
5584 	const struct config_enum_entry *entry;
5585 	StringInfoData retstr;
5586 	int			seplen;
5587 
5588 	initStringInfo(&retstr);
5589 	appendStringInfoString(&retstr, prefix);
5590 
5591 	seplen = strlen(separator);
5592 	for (entry = record->options; entry && entry->name; entry++)
5593 	{
5594 		if (!entry->hidden)
5595 		{
5596 			appendStringInfoString(&retstr, entry->name);
5597 			appendBinaryStringInfo(&retstr, separator, seplen);
5598 		}
5599 	}
5600 
5601 	/*
5602 	 * All the entries may have been hidden, leaving the string empty if no
5603 	 * prefix was given. This indicates a broken GUC setup, since there is no
5604 	 * use for an enum without any values, so we just check to make sure we
5605 	 * don't write to invalid memory instead of actually trying to do
5606 	 * something smart with it.
5607 	 */
5608 	if (retstr.len >= seplen)
5609 	{
5610 		/* Replace final separator */
5611 		retstr.data[retstr.len - seplen] = '\0';
5612 		retstr.len -= seplen;
5613 	}
5614 
5615 	appendStringInfoString(&retstr, suffix);
5616 
5617 	return retstr.data;
5618 }
5619 
5620 /*
5621  * Parse and validate a proposed value for the specified configuration
5622  * parameter.
5623  *
5624  * This does built-in checks (such as range limits for an integer parameter)
5625  * and also calls any check hook the parameter may have.
5626  *
5627  * record: GUC variable's info record
5628  * name: variable name (should match the record of course)
5629  * value: proposed value, as a string
5630  * source: identifies source of value (check hooks may need this)
5631  * elevel: level to log any error reports at
5632  * newval: on success, converted parameter value is returned here
5633  * newextra: on success, receives any "extra" data returned by check hook
5634  *	(caller must initialize *newextra to NULL)
5635  *
5636  * Returns true if OK, false if not (or throws error, if elevel >= ERROR)
5637  */
5638 static bool
parse_and_validate_value(struct config_generic * record,const char * name,const char * value,GucSource source,int elevel,union config_var_val * newval,void ** newextra)5639 parse_and_validate_value(struct config_generic * record,
5640 						 const char *name, const char *value,
5641 						 GucSource source, int elevel,
5642 						 union config_var_val * newval, void **newextra)
5643 {
5644 	switch (record->vartype)
5645 	{
5646 		case PGC_BOOL:
5647 			{
5648 				struct config_bool *conf = (struct config_bool *) record;
5649 
5650 				if (!parse_bool(value, &newval->boolval))
5651 				{
5652 					ereport(elevel,
5653 							(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5654 						  errmsg("parameter \"%s\" requires a Boolean value",
5655 								 name)));
5656 					return false;
5657 				}
5658 
5659 				if (!call_bool_check_hook(conf, &newval->boolval, newextra,
5660 										  source, elevel))
5661 					return false;
5662 			}
5663 			break;
5664 		case PGC_INT:
5665 			{
5666 				struct config_int *conf = (struct config_int *) record;
5667 				const char *hintmsg;
5668 
5669 				if (!parse_int(value, &newval->intval,
5670 							   conf->gen.flags, &hintmsg))
5671 				{
5672 					ereport(elevel,
5673 							(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5674 						 errmsg("invalid value for parameter \"%s\": \"%s\"",
5675 								name, value),
5676 							 hintmsg ? errhint("%s", _(hintmsg)) : 0));
5677 					return false;
5678 				}
5679 
5680 				if (newval->intval < conf->min || newval->intval > conf->max)
5681 				{
5682 					ereport(elevel,
5683 							(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5684 							 errmsg("%d is outside the valid range for parameter \"%s\" (%d .. %d)",
5685 									newval->intval, name,
5686 									conf->min, conf->max)));
5687 					return false;
5688 				}
5689 
5690 				if (!call_int_check_hook(conf, &newval->intval, newextra,
5691 										 source, elevel))
5692 					return false;
5693 			}
5694 			break;
5695 		case PGC_REAL:
5696 			{
5697 				struct config_real *conf = (struct config_real *) record;
5698 
5699 				if (!parse_real(value, &newval->realval))
5700 				{
5701 					ereport(elevel,
5702 							(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5703 						  errmsg("parameter \"%s\" requires a numeric value",
5704 								 name)));
5705 					return false;
5706 				}
5707 
5708 				if (newval->realval < conf->min || newval->realval > conf->max)
5709 				{
5710 					ereport(elevel,
5711 							(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5712 							 errmsg("%g is outside the valid range for parameter \"%s\" (%g .. %g)",
5713 									newval->realval, name,
5714 									conf->min, conf->max)));
5715 					return false;
5716 				}
5717 
5718 				if (!call_real_check_hook(conf, &newval->realval, newextra,
5719 										  source, elevel))
5720 					return false;
5721 			}
5722 			break;
5723 		case PGC_STRING:
5724 			{
5725 				struct config_string *conf = (struct config_string *) record;
5726 
5727 				/*
5728 				 * The value passed by the caller could be transient, so we
5729 				 * always strdup it.
5730 				 */
5731 				newval->stringval = guc_strdup(elevel, value);
5732 				if (newval->stringval == NULL)
5733 					return false;
5734 
5735 				/*
5736 				 * The only built-in "parsing" check we have is to apply
5737 				 * truncation if GUC_IS_NAME.
5738 				 */
5739 				if (conf->gen.flags & GUC_IS_NAME)
5740 					truncate_identifier(newval->stringval,
5741 										strlen(newval->stringval),
5742 										true);
5743 
5744 				if (!call_string_check_hook(conf, &newval->stringval, newextra,
5745 											source, elevel))
5746 				{
5747 					free(newval->stringval);
5748 					newval->stringval = NULL;
5749 					return false;
5750 				}
5751 			}
5752 			break;
5753 		case PGC_ENUM:
5754 			{
5755 				struct config_enum *conf = (struct config_enum *) record;
5756 
5757 				if (!config_enum_lookup_by_name(conf, value, &newval->enumval))
5758 				{
5759 					char	   *hintmsg;
5760 
5761 					hintmsg = config_enum_get_options(conf,
5762 													  "Available values: ",
5763 													  ".", ", ");
5764 
5765 					ereport(elevel,
5766 							(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5767 						 errmsg("invalid value for parameter \"%s\": \"%s\"",
5768 								name, value),
5769 							 hintmsg ? errhint("%s", _(hintmsg)) : 0));
5770 
5771 					if (hintmsg)
5772 						pfree(hintmsg);
5773 					return false;
5774 				}
5775 
5776 				if (!call_enum_check_hook(conf, &newval->enumval, newextra,
5777 										  source, elevel))
5778 					return false;
5779 			}
5780 			break;
5781 	}
5782 
5783 	return true;
5784 }
5785 
5786 
5787 /*
5788  * Sets option `name' to given value.
5789  *
5790  * The value should be a string, which will be parsed and converted to
5791  * the appropriate data type.  The context and source parameters indicate
5792  * in which context this function is being called, so that it can apply the
5793  * access restrictions properly.
5794  *
5795  * If value is NULL, set the option to its default value (normally the
5796  * reset_val, but if source == PGC_S_DEFAULT we instead use the boot_val).
5797  *
5798  * action indicates whether to set the value globally in the session, locally
5799  * to the current top transaction, or just for the duration of a function call.
5800  *
5801  * If changeVal is false then don't really set the option but do all
5802  * the checks to see if it would work.
5803  *
5804  * elevel should normally be passed as zero, allowing this function to make
5805  * its standard choice of ereport level.  However some callers need to be
5806  * able to override that choice; they should pass the ereport level to use.
5807  *
5808  * Return value:
5809  *	+1: the value is valid and was successfully applied.
5810  *	0:	the name or value is invalid (but see below).
5811  *	-1: the value was not applied because of context, priority, or changeVal.
5812  *
5813  * If there is an error (non-existing option, invalid value) then an
5814  * ereport(ERROR) is thrown *unless* this is called for a source for which
5815  * we don't want an ERROR (currently, those are defaults, the config file,
5816  * and per-database or per-user settings, as well as callers who specify
5817  * a less-than-ERROR elevel).  In those cases we write a suitable error
5818  * message via ereport() and return 0.
5819  *
5820  * See also SetConfigOption for an external interface.
5821  */
5822 int
set_config_option(const char * name,const char * value,GucContext context,GucSource source,GucAction action,bool changeVal,int elevel,bool is_reload)5823 set_config_option(const char *name, const char *value,
5824 				  GucContext context, GucSource source,
5825 				  GucAction action, bool changeVal, int elevel,
5826 				  bool is_reload)
5827 {
5828 	struct config_generic *record;
5829 	union config_var_val newval_union;
5830 	void	   *newextra = NULL;
5831 	bool		prohibitValueChange = false;
5832 	bool		makeDefault;
5833 
5834 	if (elevel == 0)
5835 	{
5836 		if (source == PGC_S_DEFAULT || source == PGC_S_FILE)
5837 		{
5838 			/*
5839 			 * To avoid cluttering the log, only the postmaster bleats loudly
5840 			 * about problems with the config file.
5841 			 */
5842 			elevel = IsUnderPostmaster ? DEBUG3 : LOG;
5843 		}
5844 		else if (source == PGC_S_GLOBAL ||
5845 				 source == PGC_S_DATABASE ||
5846 				 source == PGC_S_USER ||
5847 				 source == PGC_S_DATABASE_USER)
5848 			elevel = WARNING;
5849 		else
5850 			elevel = ERROR;
5851 	}
5852 
5853 	/*
5854 	 * GUC_ACTION_SAVE changes are acceptable during a parallel operation,
5855 	 * because the current worker will also pop the change.  We're probably
5856 	 * dealing with a function having a proconfig entry.  Only the function's
5857 	 * body should observe the change, and peer workers do not share in the
5858 	 * execution of a function call started by this worker.
5859 	 *
5860 	 * Other changes might need to affect other workers, so forbid them.
5861 	 */
5862 	if (IsInParallelMode() && changeVal && action != GUC_ACTION_SAVE)
5863 		ereport(elevel,
5864 				(errcode(ERRCODE_INVALID_TRANSACTION_STATE),
5865 			   errmsg("cannot set parameters during a parallel operation")));
5866 
5867 	record = find_option(name, true, elevel);
5868 	if (record == NULL)
5869 	{
5870 		ereport(elevel,
5871 				(errcode(ERRCODE_UNDEFINED_OBJECT),
5872 			   errmsg("unrecognized configuration parameter \"%s\"", name)));
5873 		return 0;
5874 	}
5875 
5876 	/*
5877 	 * Check if the option can be set at this time. See guc.h for the precise
5878 	 * rules.
5879 	 */
5880 	switch (record->context)
5881 	{
5882 		case PGC_INTERNAL:
5883 			if (context != PGC_INTERNAL)
5884 			{
5885 				ereport(elevel,
5886 						(errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5887 						 errmsg("parameter \"%s\" cannot be changed",
5888 								name)));
5889 				return 0;
5890 			}
5891 			break;
5892 		case PGC_POSTMASTER:
5893 			if (context == PGC_SIGHUP)
5894 			{
5895 				/*
5896 				 * We are re-reading a PGC_POSTMASTER variable from
5897 				 * postgresql.conf.  We can't change the setting, so we should
5898 				 * give a warning if the DBA tries to change it.  However,
5899 				 * because of variant formats, canonicalization by check
5900 				 * hooks, etc, we can't just compare the given string directly
5901 				 * to what's stored.  Set a flag to check below after we have
5902 				 * the final storable value.
5903 				 */
5904 				prohibitValueChange = true;
5905 			}
5906 			else if (context != PGC_POSTMASTER)
5907 			{
5908 				ereport(elevel,
5909 						(errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5910 						 errmsg("parameter \"%s\" cannot be changed without restarting the server",
5911 								name)));
5912 				return 0;
5913 			}
5914 			break;
5915 		case PGC_SIGHUP:
5916 			if (context != PGC_SIGHUP && context != PGC_POSTMASTER)
5917 			{
5918 				ereport(elevel,
5919 						(errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5920 						 errmsg("parameter \"%s\" cannot be changed now",
5921 								name)));
5922 				return 0;
5923 			}
5924 
5925 			/*
5926 			 * Hmm, the idea of the SIGHUP context is "ought to be global, but
5927 			 * can be changed after postmaster start". But there's nothing
5928 			 * that prevents a crafty administrator from sending SIGHUP
5929 			 * signals to individual backends only.
5930 			 */
5931 			break;
5932 		case PGC_SU_BACKEND:
5933 			/* Reject if we're connecting but user is not superuser */
5934 			if (context == PGC_BACKEND)
5935 			{
5936 				ereport(elevel,
5937 						(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
5938 						 errmsg("permission denied to set parameter \"%s\"",
5939 								name)));
5940 				return 0;
5941 			}
5942 			/* FALL THRU to process the same as PGC_BACKEND */
5943 		case PGC_BACKEND:
5944 			if (context == PGC_SIGHUP)
5945 			{
5946 				/*
5947 				 * If a PGC_BACKEND or PGC_SU_BACKEND parameter is changed in
5948 				 * the config file, we want to accept the new value in the
5949 				 * postmaster (whence it will propagate to
5950 				 * subsequently-started backends), but ignore it in existing
5951 				 * backends.  This is a tad klugy, but necessary because we
5952 				 * don't re-read the config file during backend start.
5953 				 *
5954 				 * In EXEC_BACKEND builds, this works differently: we load all
5955 				 * non-default settings from the CONFIG_EXEC_PARAMS file
5956 				 * during backend start.  In that case we must accept
5957 				 * PGC_SIGHUP settings, so as to have the same value as if
5958 				 * we'd forked from the postmaster.  This can also happen when
5959 				 * using RestoreGUCState() within a background worker that
5960 				 * needs to have the same settings as the user backend that
5961 				 * started it. is_reload will be true when either situation
5962 				 * applies.
5963 				 */
5964 				if (IsUnderPostmaster && !is_reload)
5965 					return -1;
5966 			}
5967 			else if (context != PGC_POSTMASTER &&
5968 					 context != PGC_BACKEND &&
5969 					 context != PGC_SU_BACKEND &&
5970 					 source != PGC_S_CLIENT)
5971 			{
5972 				ereport(elevel,
5973 						(errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5974 						 errmsg("parameter \"%s\" cannot be set after connection start",
5975 								name)));
5976 				return 0;
5977 			}
5978 			break;
5979 		case PGC_SUSET:
5980 			if (context == PGC_USERSET || context == PGC_BACKEND)
5981 			{
5982 				ereport(elevel,
5983 						(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
5984 						 errmsg("permission denied to set parameter \"%s\"",
5985 								name)));
5986 				return 0;
5987 			}
5988 			break;
5989 		case PGC_USERSET:
5990 			/* always okay */
5991 			break;
5992 	}
5993 
5994 	/*
5995 	 * Disallow changing GUC_NOT_WHILE_SEC_REST values if we are inside a
5996 	 * security restriction context.  We can reject this regardless of the GUC
5997 	 * context or source, mainly because sources that it might be reasonable
5998 	 * to override for won't be seen while inside a function.
5999 	 *
6000 	 * Note: variables marked GUC_NOT_WHILE_SEC_REST should usually be marked
6001 	 * GUC_NO_RESET_ALL as well, because ResetAllOptions() doesn't check this.
6002 	 * An exception might be made if the reset value is assumed to be "safe".
6003 	 *
6004 	 * Note: this flag is currently used for "session_authorization" and
6005 	 * "role".  We need to prohibit changing these inside a local userid
6006 	 * context because when we exit it, GUC won't be notified, leaving things
6007 	 * out of sync.  (This could be fixed by forcing a new GUC nesting level,
6008 	 * but that would change behavior in possibly-undesirable ways.)  Also, we
6009 	 * prohibit changing these in a security-restricted operation because
6010 	 * otherwise RESET could be used to regain the session user's privileges.
6011 	 */
6012 	if (record->flags & GUC_NOT_WHILE_SEC_REST)
6013 	{
6014 		if (InLocalUserIdChange())
6015 		{
6016 			/*
6017 			 * Phrasing of this error message is historical, but it's the most
6018 			 * common case.
6019 			 */
6020 			ereport(elevel,
6021 					(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6022 					 errmsg("cannot set parameter \"%s\" within security-definer function",
6023 							name)));
6024 			return 0;
6025 		}
6026 		if (InSecurityRestrictedOperation())
6027 		{
6028 			ereport(elevel,
6029 					(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6030 					 errmsg("cannot set parameter \"%s\" within security-restricted operation",
6031 							name)));
6032 			return 0;
6033 		}
6034 	}
6035 
6036 	/*
6037 	 * Should we set reset/stacked values?	(If so, the behavior is not
6038 	 * transactional.)	This is done either when we get a default value from
6039 	 * the database's/user's/client's default settings or when we reset a
6040 	 * value to its default.
6041 	 */
6042 	makeDefault = changeVal && (source <= PGC_S_OVERRIDE) &&
6043 		((value != NULL) || source == PGC_S_DEFAULT);
6044 
6045 	/*
6046 	 * Ignore attempted set if overridden by previously processed setting.
6047 	 * However, if changeVal is false then plow ahead anyway since we are
6048 	 * trying to find out if the value is potentially good, not actually use
6049 	 * it. Also keep going if makeDefault is true, since we may want to set
6050 	 * the reset/stacked values even if we can't set the variable itself.
6051 	 */
6052 	if (record->source > source)
6053 	{
6054 		if (changeVal && !makeDefault)
6055 		{
6056 			elog(DEBUG3, "\"%s\": setting ignored because previous source is higher priority",
6057 				 name);
6058 			return -1;
6059 		}
6060 		changeVal = false;
6061 	}
6062 
6063 	/*
6064 	 * Evaluate value and set variable.
6065 	 */
6066 	switch (record->vartype)
6067 	{
6068 		case PGC_BOOL:
6069 			{
6070 				struct config_bool *conf = (struct config_bool *) record;
6071 
6072 #define newval (newval_union.boolval)
6073 
6074 				if (value)
6075 				{
6076 					if (!parse_and_validate_value(record, name, value,
6077 												  source, elevel,
6078 												  &newval_union, &newextra))
6079 						return 0;
6080 				}
6081 				else if (source == PGC_S_DEFAULT)
6082 				{
6083 					newval = conf->boot_val;
6084 					if (!call_bool_check_hook(conf, &newval, &newextra,
6085 											  source, elevel))
6086 						return 0;
6087 				}
6088 				else
6089 				{
6090 					newval = conf->reset_val;
6091 					newextra = conf->reset_extra;
6092 					source = conf->gen.reset_source;
6093 					context = conf->gen.reset_scontext;
6094 				}
6095 
6096 				if (prohibitValueChange)
6097 				{
6098 					/* Release newextra, unless it's reset_extra */
6099 					if (newextra && !extra_field_used(&conf->gen, newextra))
6100 						free(newextra);
6101 
6102 					if (*conf->variable != newval)
6103 					{
6104 						record->status |= GUC_PENDING_RESTART;
6105 						ereport(elevel,
6106 								(errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
6107 								 errmsg("parameter \"%s\" cannot be changed without restarting the server",
6108 										name)));
6109 						return 0;
6110 					}
6111 					record->status &= ~GUC_PENDING_RESTART;
6112 					return -1;
6113 				}
6114 
6115 				if (changeVal)
6116 				{
6117 					/* Save old value to support transaction abort */
6118 					if (!makeDefault)
6119 						push_old_value(&conf->gen, action);
6120 
6121 					if (conf->assign_hook)
6122 						(*conf->assign_hook) (newval, newextra);
6123 					*conf->variable = newval;
6124 					set_extra_field(&conf->gen, &conf->gen.extra,
6125 									newextra);
6126 					conf->gen.source = source;
6127 					conf->gen.scontext = context;
6128 				}
6129 				if (makeDefault)
6130 				{
6131 					GucStack   *stack;
6132 
6133 					if (conf->gen.reset_source <= source)
6134 					{
6135 						conf->reset_val = newval;
6136 						set_extra_field(&conf->gen, &conf->reset_extra,
6137 										newextra);
6138 						conf->gen.reset_source = source;
6139 						conf->gen.reset_scontext = context;
6140 					}
6141 					for (stack = conf->gen.stack; stack; stack = stack->prev)
6142 					{
6143 						if (stack->source <= source)
6144 						{
6145 							stack->prior.val.boolval = newval;
6146 							set_extra_field(&conf->gen, &stack->prior.extra,
6147 											newextra);
6148 							stack->source = source;
6149 							stack->scontext = context;
6150 						}
6151 					}
6152 				}
6153 
6154 				/* Perhaps we didn't install newextra anywhere */
6155 				if (newextra && !extra_field_used(&conf->gen, newextra))
6156 					free(newextra);
6157 				break;
6158 
6159 #undef newval
6160 			}
6161 
6162 		case PGC_INT:
6163 			{
6164 				struct config_int *conf = (struct config_int *) record;
6165 
6166 #define newval (newval_union.intval)
6167 
6168 				if (value)
6169 				{
6170 					if (!parse_and_validate_value(record, name, value,
6171 												  source, elevel,
6172 												  &newval_union, &newextra))
6173 						return 0;
6174 				}
6175 				else if (source == PGC_S_DEFAULT)
6176 				{
6177 					newval = conf->boot_val;
6178 					if (!call_int_check_hook(conf, &newval, &newextra,
6179 											 source, elevel))
6180 						return 0;
6181 				}
6182 				else
6183 				{
6184 					newval = conf->reset_val;
6185 					newextra = conf->reset_extra;
6186 					source = conf->gen.reset_source;
6187 					context = conf->gen.reset_scontext;
6188 				}
6189 
6190 				if (prohibitValueChange)
6191 				{
6192 					/* Release newextra, unless it's reset_extra */
6193 					if (newextra && !extra_field_used(&conf->gen, newextra))
6194 						free(newextra);
6195 
6196 					if (*conf->variable != newval)
6197 					{
6198 						record->status |= GUC_PENDING_RESTART;
6199 						ereport(elevel,
6200 								(errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
6201 								 errmsg("parameter \"%s\" cannot be changed without restarting the server",
6202 										name)));
6203 						return 0;
6204 					}
6205 					record->status &= ~GUC_PENDING_RESTART;
6206 					return -1;
6207 				}
6208 
6209 				if (changeVal)
6210 				{
6211 					/* Save old value to support transaction abort */
6212 					if (!makeDefault)
6213 						push_old_value(&conf->gen, action);
6214 
6215 					if (conf->assign_hook)
6216 						(*conf->assign_hook) (newval, newextra);
6217 					*conf->variable = newval;
6218 					set_extra_field(&conf->gen, &conf->gen.extra,
6219 									newextra);
6220 					conf->gen.source = source;
6221 					conf->gen.scontext = context;
6222 				}
6223 				if (makeDefault)
6224 				{
6225 					GucStack   *stack;
6226 
6227 					if (conf->gen.reset_source <= source)
6228 					{
6229 						conf->reset_val = newval;
6230 						set_extra_field(&conf->gen, &conf->reset_extra,
6231 										newextra);
6232 						conf->gen.reset_source = source;
6233 						conf->gen.reset_scontext = context;
6234 					}
6235 					for (stack = conf->gen.stack; stack; stack = stack->prev)
6236 					{
6237 						if (stack->source <= source)
6238 						{
6239 							stack->prior.val.intval = newval;
6240 							set_extra_field(&conf->gen, &stack->prior.extra,
6241 											newextra);
6242 							stack->source = source;
6243 							stack->scontext = context;
6244 						}
6245 					}
6246 				}
6247 
6248 				/* Perhaps we didn't install newextra anywhere */
6249 				if (newextra && !extra_field_used(&conf->gen, newextra))
6250 					free(newextra);
6251 				break;
6252 
6253 #undef newval
6254 			}
6255 
6256 		case PGC_REAL:
6257 			{
6258 				struct config_real *conf = (struct config_real *) record;
6259 
6260 #define newval (newval_union.realval)
6261 
6262 				if (value)
6263 				{
6264 					if (!parse_and_validate_value(record, name, value,
6265 												  source, elevel,
6266 												  &newval_union, &newextra))
6267 						return 0;
6268 				}
6269 				else if (source == PGC_S_DEFAULT)
6270 				{
6271 					newval = conf->boot_val;
6272 					if (!call_real_check_hook(conf, &newval, &newextra,
6273 											  source, elevel))
6274 						return 0;
6275 				}
6276 				else
6277 				{
6278 					newval = conf->reset_val;
6279 					newextra = conf->reset_extra;
6280 					source = conf->gen.reset_source;
6281 					context = conf->gen.reset_scontext;
6282 				}
6283 
6284 				if (prohibitValueChange)
6285 				{
6286 					/* Release newextra, unless it's reset_extra */
6287 					if (newextra && !extra_field_used(&conf->gen, newextra))
6288 						free(newextra);
6289 
6290 					if (*conf->variable != newval)
6291 					{
6292 						record->status |= GUC_PENDING_RESTART;
6293 						ereport(elevel,
6294 								(errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
6295 								 errmsg("parameter \"%s\" cannot be changed without restarting the server",
6296 										name)));
6297 						return 0;
6298 					}
6299 					record->status &= ~GUC_PENDING_RESTART;
6300 					return -1;
6301 				}
6302 
6303 				if (changeVal)
6304 				{
6305 					/* Save old value to support transaction abort */
6306 					if (!makeDefault)
6307 						push_old_value(&conf->gen, action);
6308 
6309 					if (conf->assign_hook)
6310 						(*conf->assign_hook) (newval, newextra);
6311 					*conf->variable = newval;
6312 					set_extra_field(&conf->gen, &conf->gen.extra,
6313 									newextra);
6314 					conf->gen.source = source;
6315 					conf->gen.scontext = context;
6316 				}
6317 				if (makeDefault)
6318 				{
6319 					GucStack   *stack;
6320 
6321 					if (conf->gen.reset_source <= source)
6322 					{
6323 						conf->reset_val = newval;
6324 						set_extra_field(&conf->gen, &conf->reset_extra,
6325 										newextra);
6326 						conf->gen.reset_source = source;
6327 						conf->gen.reset_scontext = context;
6328 					}
6329 					for (stack = conf->gen.stack; stack; stack = stack->prev)
6330 					{
6331 						if (stack->source <= source)
6332 						{
6333 							stack->prior.val.realval = newval;
6334 							set_extra_field(&conf->gen, &stack->prior.extra,
6335 											newextra);
6336 							stack->source = source;
6337 							stack->scontext = context;
6338 						}
6339 					}
6340 				}
6341 
6342 				/* Perhaps we didn't install newextra anywhere */
6343 				if (newextra && !extra_field_used(&conf->gen, newextra))
6344 					free(newextra);
6345 				break;
6346 
6347 #undef newval
6348 			}
6349 
6350 		case PGC_STRING:
6351 			{
6352 				struct config_string *conf = (struct config_string *) record;
6353 
6354 #define newval (newval_union.stringval)
6355 
6356 				if (value)
6357 				{
6358 					if (!parse_and_validate_value(record, name, value,
6359 												  source, elevel,
6360 												  &newval_union, &newextra))
6361 						return 0;
6362 				}
6363 				else if (source == PGC_S_DEFAULT)
6364 				{
6365 					/* non-NULL boot_val must always get strdup'd */
6366 					if (conf->boot_val != NULL)
6367 					{
6368 						newval = guc_strdup(elevel, conf->boot_val);
6369 						if (newval == NULL)
6370 							return 0;
6371 					}
6372 					else
6373 						newval = NULL;
6374 
6375 					if (!call_string_check_hook(conf, &newval, &newextra,
6376 												source, elevel))
6377 					{
6378 						free(newval);
6379 						return 0;
6380 					}
6381 				}
6382 				else
6383 				{
6384 					/*
6385 					 * strdup not needed, since reset_val is already under
6386 					 * guc.c's control
6387 					 */
6388 					newval = conf->reset_val;
6389 					newextra = conf->reset_extra;
6390 					source = conf->gen.reset_source;
6391 					context = conf->gen.reset_scontext;
6392 				}
6393 
6394 				if (prohibitValueChange)
6395 				{
6396 					bool		newval_different;
6397 
6398 					/* newval shouldn't be NULL, so we're a bit sloppy here */
6399 					newval_different = (*conf->variable == NULL ||
6400 										newval == NULL ||
6401 										strcmp(*conf->variable, newval) != 0);
6402 
6403 					/* Release newval, unless it's reset_val */
6404 					if (newval && !string_field_used(conf, newval))
6405 						free(newval);
6406 					/* Release newextra, unless it's reset_extra */
6407 					if (newextra && !extra_field_used(&conf->gen, newextra))
6408 						free(newextra);
6409 
6410 					if (newval_different)
6411 					{
6412 						record->status |= GUC_PENDING_RESTART;
6413 						ereport(elevel,
6414 								(errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
6415 								 errmsg("parameter \"%s\" cannot be changed without restarting the server",
6416 										name)));
6417 						return 0;
6418 					}
6419 					record->status &= ~GUC_PENDING_RESTART;
6420 					return -1;
6421 				}
6422 
6423 				if (changeVal)
6424 				{
6425 					/* Save old value to support transaction abort */
6426 					if (!makeDefault)
6427 						push_old_value(&conf->gen, action);
6428 
6429 					if (conf->assign_hook)
6430 						(*conf->assign_hook) (newval, newextra);
6431 					set_string_field(conf, conf->variable, newval);
6432 					set_extra_field(&conf->gen, &conf->gen.extra,
6433 									newextra);
6434 					conf->gen.source = source;
6435 					conf->gen.scontext = context;
6436 				}
6437 
6438 				if (makeDefault)
6439 				{
6440 					GucStack   *stack;
6441 
6442 					if (conf->gen.reset_source <= source)
6443 					{
6444 						set_string_field(conf, &conf->reset_val, newval);
6445 						set_extra_field(&conf->gen, &conf->reset_extra,
6446 										newextra);
6447 						conf->gen.reset_source = source;
6448 						conf->gen.reset_scontext = context;
6449 					}
6450 					for (stack = conf->gen.stack; stack; stack = stack->prev)
6451 					{
6452 						if (stack->source <= source)
6453 						{
6454 							set_string_field(conf, &stack->prior.val.stringval,
6455 											 newval);
6456 							set_extra_field(&conf->gen, &stack->prior.extra,
6457 											newextra);
6458 							stack->source = source;
6459 							stack->scontext = context;
6460 						}
6461 					}
6462 				}
6463 
6464 				/* Perhaps we didn't install newval anywhere */
6465 				if (newval && !string_field_used(conf, newval))
6466 					free(newval);
6467 				/* Perhaps we didn't install newextra anywhere */
6468 				if (newextra && !extra_field_used(&conf->gen, newextra))
6469 					free(newextra);
6470 				break;
6471 
6472 #undef newval
6473 			}
6474 
6475 		case PGC_ENUM:
6476 			{
6477 				struct config_enum *conf = (struct config_enum *) record;
6478 
6479 #define newval (newval_union.enumval)
6480 
6481 				if (value)
6482 				{
6483 					if (!parse_and_validate_value(record, name, value,
6484 												  source, elevel,
6485 												  &newval_union, &newextra))
6486 						return 0;
6487 				}
6488 				else if (source == PGC_S_DEFAULT)
6489 				{
6490 					newval = conf->boot_val;
6491 					if (!call_enum_check_hook(conf, &newval, &newextra,
6492 											  source, elevel))
6493 						return 0;
6494 				}
6495 				else
6496 				{
6497 					newval = conf->reset_val;
6498 					newextra = conf->reset_extra;
6499 					source = conf->gen.reset_source;
6500 					context = conf->gen.reset_scontext;
6501 				}
6502 
6503 				if (prohibitValueChange)
6504 				{
6505 					/* Release newextra, unless it's reset_extra */
6506 					if (newextra && !extra_field_used(&conf->gen, newextra))
6507 						free(newextra);
6508 
6509 					if (*conf->variable != newval)
6510 					{
6511 						record->status |= GUC_PENDING_RESTART;
6512 						ereport(elevel,
6513 								(errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
6514 								 errmsg("parameter \"%s\" cannot be changed without restarting the server",
6515 										name)));
6516 						return 0;
6517 					}
6518 					record->status &= ~GUC_PENDING_RESTART;
6519 					return -1;
6520 				}
6521 
6522 				if (changeVal)
6523 				{
6524 					/* Save old value to support transaction abort */
6525 					if (!makeDefault)
6526 						push_old_value(&conf->gen, action);
6527 
6528 					if (conf->assign_hook)
6529 						(*conf->assign_hook) (newval, newextra);
6530 					*conf->variable = newval;
6531 					set_extra_field(&conf->gen, &conf->gen.extra,
6532 									newextra);
6533 					conf->gen.source = source;
6534 					conf->gen.scontext = context;
6535 				}
6536 				if (makeDefault)
6537 				{
6538 					GucStack   *stack;
6539 
6540 					if (conf->gen.reset_source <= source)
6541 					{
6542 						conf->reset_val = newval;
6543 						set_extra_field(&conf->gen, &conf->reset_extra,
6544 										newextra);
6545 						conf->gen.reset_source = source;
6546 						conf->gen.reset_scontext = context;
6547 					}
6548 					for (stack = conf->gen.stack; stack; stack = stack->prev)
6549 					{
6550 						if (stack->source <= source)
6551 						{
6552 							stack->prior.val.enumval = newval;
6553 							set_extra_field(&conf->gen, &stack->prior.extra,
6554 											newextra);
6555 							stack->source = source;
6556 							stack->scontext = context;
6557 						}
6558 					}
6559 				}
6560 
6561 				/* Perhaps we didn't install newextra anywhere */
6562 				if (newextra && !extra_field_used(&conf->gen, newextra))
6563 					free(newextra);
6564 				break;
6565 
6566 #undef newval
6567 			}
6568 	}
6569 
6570 	if (changeVal && (record->flags & GUC_REPORT))
6571 		ReportGUCOption(record);
6572 
6573 	return changeVal ? 1 : -1;
6574 }
6575 
6576 
6577 /*
6578  * Set the fields for source file and line number the setting came from.
6579  */
6580 static void
set_config_sourcefile(const char * name,char * sourcefile,int sourceline)6581 set_config_sourcefile(const char *name, char *sourcefile, int sourceline)
6582 {
6583 	struct config_generic *record;
6584 	int			elevel;
6585 
6586 	/*
6587 	 * To avoid cluttering the log, only the postmaster bleats loudly about
6588 	 * problems with the config file.
6589 	 */
6590 	elevel = IsUnderPostmaster ? DEBUG3 : LOG;
6591 
6592 	record = find_option(name, true, elevel);
6593 	/* should not happen */
6594 	if (record == NULL)
6595 		elog(ERROR, "unrecognized configuration parameter \"%s\"", name);
6596 
6597 	sourcefile = guc_strdup(elevel, sourcefile);
6598 	if (record->sourcefile)
6599 		free(record->sourcefile);
6600 	record->sourcefile = sourcefile;
6601 	record->sourceline = sourceline;
6602 }
6603 
6604 /*
6605  * Set a config option to the given value.
6606  *
6607  * See also set_config_option; this is just the wrapper to be called from
6608  * outside GUC.  (This function should be used when possible, because its API
6609  * is more stable than set_config_option's.)
6610  *
6611  * Note: there is no support here for setting source file/line, as it
6612  * is currently not needed.
6613  */
6614 void
SetConfigOption(const char * name,const char * value,GucContext context,GucSource source)6615 SetConfigOption(const char *name, const char *value,
6616 				GucContext context, GucSource source)
6617 {
6618 	(void) set_config_option(name, value, context, source,
6619 							 GUC_ACTION_SET, true, 0, false);
6620 }
6621 
6622 
6623 
6624 /*
6625  * Fetch the current value of the option `name', as a string.
6626  *
6627  * If the option doesn't exist, return NULL if missing_ok is true (NOTE that
6628  * this cannot be distinguished from a string variable with a NULL value!),
6629  * otherwise throw an ereport and don't return.
6630  *
6631  * If restrict_superuser is true, we also enforce that only superusers can
6632  * see GUC_SUPERUSER_ONLY variables.  This should only be passed as true
6633  * in user-driven calls.
6634  *
6635  * The string is *not* allocated for modification and is really only
6636  * valid until the next call to configuration related functions.
6637  */
6638 const char *
GetConfigOption(const char * name,bool missing_ok,bool restrict_superuser)6639 GetConfigOption(const char *name, bool missing_ok, bool restrict_superuser)
6640 {
6641 	struct config_generic *record;
6642 	static char buffer[256];
6643 
6644 	record = find_option(name, false, ERROR);
6645 	if (record == NULL)
6646 	{
6647 		if (missing_ok)
6648 			return NULL;
6649 		ereport(ERROR,
6650 				(errcode(ERRCODE_UNDEFINED_OBJECT),
6651 				 errmsg("unrecognized configuration parameter \"%s\"",
6652 						name)));
6653 	}
6654 	if (restrict_superuser &&
6655 		(record->flags & GUC_SUPERUSER_ONLY) &&
6656 		!superuser())
6657 		ereport(ERROR,
6658 				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6659 				 errmsg("must be superuser to examine \"%s\"", name)));
6660 
6661 	switch (record->vartype)
6662 	{
6663 		case PGC_BOOL:
6664 			return *((struct config_bool *) record)->variable ? "on" : "off";
6665 
6666 		case PGC_INT:
6667 			snprintf(buffer, sizeof(buffer), "%d",
6668 					 *((struct config_int *) record)->variable);
6669 			return buffer;
6670 
6671 		case PGC_REAL:
6672 			snprintf(buffer, sizeof(buffer), "%g",
6673 					 *((struct config_real *) record)->variable);
6674 			return buffer;
6675 
6676 		case PGC_STRING:
6677 			return *((struct config_string *) record)->variable;
6678 
6679 		case PGC_ENUM:
6680 			return config_enum_lookup_by_value((struct config_enum *) record,
6681 								 *((struct config_enum *) record)->variable);
6682 	}
6683 	return NULL;
6684 }
6685 
6686 /*
6687  * Get the RESET value associated with the given option.
6688  *
6689  * Note: this is not re-entrant, due to use of static result buffer;
6690  * not to mention that a string variable could have its reset_val changed.
6691  * Beware of assuming the result value is good for very long.
6692  */
6693 const char *
GetConfigOptionResetString(const char * name)6694 GetConfigOptionResetString(const char *name)
6695 {
6696 	struct config_generic *record;
6697 	static char buffer[256];
6698 
6699 	record = find_option(name, false, ERROR);
6700 	if (record == NULL)
6701 		ereport(ERROR,
6702 				(errcode(ERRCODE_UNDEFINED_OBJECT),
6703 			   errmsg("unrecognized configuration parameter \"%s\"", name)));
6704 	if ((record->flags & GUC_SUPERUSER_ONLY) && !superuser())
6705 		ereport(ERROR,
6706 				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6707 				 errmsg("must be superuser to examine \"%s\"", name)));
6708 
6709 	switch (record->vartype)
6710 	{
6711 		case PGC_BOOL:
6712 			return ((struct config_bool *) record)->reset_val ? "on" : "off";
6713 
6714 		case PGC_INT:
6715 			snprintf(buffer, sizeof(buffer), "%d",
6716 					 ((struct config_int *) record)->reset_val);
6717 			return buffer;
6718 
6719 		case PGC_REAL:
6720 			snprintf(buffer, sizeof(buffer), "%g",
6721 					 ((struct config_real *) record)->reset_val);
6722 			return buffer;
6723 
6724 		case PGC_STRING:
6725 			return ((struct config_string *) record)->reset_val;
6726 
6727 		case PGC_ENUM:
6728 			return config_enum_lookup_by_value((struct config_enum *) record,
6729 								 ((struct config_enum *) record)->reset_val);
6730 	}
6731 	return NULL;
6732 }
6733 
6734 /*
6735  * Get the GUC flags associated with the given option.
6736  *
6737  * If the option doesn't exist, return 0 if missing_ok is true,
6738  * otherwise throw an ereport and don't return.
6739  */
6740 int
GetConfigOptionFlags(const char * name,bool missing_ok)6741 GetConfigOptionFlags(const char *name, bool missing_ok)
6742 {
6743 	struct config_generic *record;
6744 
6745 	record = find_option(name, false, WARNING);
6746 	if (record == NULL)
6747 	{
6748 		if (missing_ok)
6749 			return 0;
6750 		ereport(ERROR,
6751 				(errcode(ERRCODE_UNDEFINED_OBJECT),
6752 				 errmsg("unrecognized configuration parameter \"%s\"",
6753 						name)));
6754 	}
6755 	return record->flags;
6756 }
6757 
6758 
6759 /*
6760  * flatten_set_variable_args
6761  *		Given a parsenode List as emitted by the grammar for SET,
6762  *		convert to the flat string representation used by GUC.
6763  *
6764  * We need to be told the name of the variable the args are for, because
6765  * the flattening rules vary (ugh).
6766  *
6767  * The result is NULL if args is NIL (i.e., SET ... TO DEFAULT), otherwise
6768  * a palloc'd string.
6769  */
6770 static char *
flatten_set_variable_args(const char * name,List * args)6771 flatten_set_variable_args(const char *name, List *args)
6772 {
6773 	struct config_generic *record;
6774 	int			flags;
6775 	StringInfoData buf;
6776 	ListCell   *l;
6777 
6778 	/* Fast path if just DEFAULT */
6779 	if (args == NIL)
6780 		return NULL;
6781 
6782 	/*
6783 	 * Get flags for the variable; if it's not known, use default flags.
6784 	 * (Caller might throw error later, but not our business to do so here.)
6785 	 */
6786 	record = find_option(name, false, WARNING);
6787 	if (record)
6788 		flags = record->flags;
6789 	else
6790 		flags = 0;
6791 
6792 	/* Complain if list input and non-list variable */
6793 	if ((flags & GUC_LIST_INPUT) == 0 &&
6794 		list_length(args) != 1)
6795 		ereport(ERROR,
6796 				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6797 				 errmsg("SET %s takes only one argument", name)));
6798 
6799 	initStringInfo(&buf);
6800 
6801 	/*
6802 	 * Each list member may be a plain A_Const node, or an A_Const within a
6803 	 * TypeCast; the latter case is supported only for ConstInterval arguments
6804 	 * (for SET TIME ZONE).
6805 	 */
6806 	foreach(l, args)
6807 	{
6808 		Node	   *arg = (Node *) lfirst(l);
6809 		char	   *val;
6810 		TypeName   *typeName = NULL;
6811 		A_Const    *con;
6812 
6813 		if (l != list_head(args))
6814 			appendStringInfoString(&buf, ", ");
6815 
6816 		if (IsA(arg, TypeCast))
6817 		{
6818 			TypeCast   *tc = (TypeCast *) arg;
6819 
6820 			arg = tc->arg;
6821 			typeName = tc->typeName;
6822 		}
6823 
6824 		if (!IsA(arg, A_Const))
6825 			elog(ERROR, "unrecognized node type: %d", (int) nodeTag(arg));
6826 		con = (A_Const *) arg;
6827 
6828 		switch (nodeTag(&con->val))
6829 		{
6830 			case T_Integer:
6831 				appendStringInfo(&buf, "%ld", intVal(&con->val));
6832 				break;
6833 			case T_Float:
6834 				/* represented as a string, so just copy it */
6835 				appendStringInfoString(&buf, strVal(&con->val));
6836 				break;
6837 			case T_String:
6838 				val = strVal(&con->val);
6839 				if (typeName != NULL)
6840 				{
6841 					/*
6842 					 * Must be a ConstInterval argument for TIME ZONE. Coerce
6843 					 * to interval and back to normalize the value and account
6844 					 * for any typmod.
6845 					 */
6846 					Oid			typoid;
6847 					int32		typmod;
6848 					Datum		interval;
6849 					char	   *intervalout;
6850 
6851 					typenameTypeIdAndMod(NULL, typeName, &typoid, &typmod);
6852 					Assert(typoid == INTERVALOID);
6853 
6854 					interval =
6855 						DirectFunctionCall3(interval_in,
6856 											CStringGetDatum(val),
6857 											ObjectIdGetDatum(InvalidOid),
6858 											Int32GetDatum(typmod));
6859 
6860 					intervalout =
6861 						DatumGetCString(DirectFunctionCall1(interval_out,
6862 															interval));
6863 					appendStringInfo(&buf, "INTERVAL '%s'", intervalout);
6864 				}
6865 				else
6866 				{
6867 					/*
6868 					 * Plain string literal or identifier.  For quote mode,
6869 					 * quote it if it's not a vanilla identifier.
6870 					 */
6871 					if (flags & GUC_LIST_QUOTE)
6872 						appendStringInfoString(&buf, quote_identifier(val));
6873 					else
6874 						appendStringInfoString(&buf, val);
6875 				}
6876 				break;
6877 			default:
6878 				elog(ERROR, "unrecognized node type: %d",
6879 					 (int) nodeTag(&con->val));
6880 				break;
6881 		}
6882 	}
6883 
6884 	return buf.data;
6885 }
6886 
6887 /*
6888  * Write updated configuration parameter values into a temporary file.
6889  * This function traverses the list of parameters and quotes the string
6890  * values before writing them.
6891  */
6892 static void
write_auto_conf_file(int fd,const char * filename,ConfigVariable * head)6893 write_auto_conf_file(int fd, const char *filename, ConfigVariable *head)
6894 {
6895 	StringInfoData buf;
6896 	ConfigVariable *item;
6897 
6898 	initStringInfo(&buf);
6899 
6900 	/* Emit file header containing warning comment */
6901 	appendStringInfoString(&buf, "# Do not edit this file manually!\n");
6902 	appendStringInfoString(&buf, "# It will be overwritten by the ALTER SYSTEM command.\n");
6903 
6904 	errno = 0;
6905 	if (write(fd, buf.data, buf.len) != buf.len)
6906 	{
6907 		/* if write didn't set errno, assume problem is no disk space */
6908 		if (errno == 0)
6909 			errno = ENOSPC;
6910 		ereport(ERROR,
6911 				(errcode_for_file_access(),
6912 				 errmsg("could not write to file \"%s\": %m", filename)));
6913 	}
6914 
6915 	/* Emit each parameter, properly quoting the value */
6916 	for (item = head; item != NULL; item = item->next)
6917 	{
6918 		char	   *escaped;
6919 
6920 		resetStringInfo(&buf);
6921 
6922 		appendStringInfoString(&buf, item->name);
6923 		appendStringInfoString(&buf, " = '");
6924 
6925 		escaped = escape_single_quotes_ascii(item->value);
6926 		if (!escaped)
6927 			ereport(ERROR,
6928 					(errcode(ERRCODE_OUT_OF_MEMORY),
6929 					 errmsg("out of memory")));
6930 		appendStringInfoString(&buf, escaped);
6931 		free(escaped);
6932 
6933 		appendStringInfoString(&buf, "'\n");
6934 
6935 		errno = 0;
6936 		if (write(fd, buf.data, buf.len) != buf.len)
6937 		{
6938 			/* if write didn't set errno, assume problem is no disk space */
6939 			if (errno == 0)
6940 				errno = ENOSPC;
6941 			ereport(ERROR,
6942 					(errcode_for_file_access(),
6943 					 errmsg("could not write to file \"%s\": %m", filename)));
6944 		}
6945 	}
6946 
6947 	/* fsync before considering the write to be successful */
6948 	if (pg_fsync(fd) != 0)
6949 		ereport(ERROR,
6950 				(errcode_for_file_access(),
6951 				 errmsg("could not fsync file \"%s\": %m", filename)));
6952 
6953 	pfree(buf.data);
6954 }
6955 
6956 /*
6957  * Update the given list of configuration parameters, adding, replacing
6958  * or deleting the entry for item "name" (delete if "value" == NULL).
6959  */
6960 static void
replace_auto_config_value(ConfigVariable ** head_p,ConfigVariable ** tail_p,const char * name,const char * value)6961 replace_auto_config_value(ConfigVariable **head_p, ConfigVariable **tail_p,
6962 						  const char *name, const char *value)
6963 {
6964 	ConfigVariable *item,
6965 			   *next,
6966 			   *prev = NULL;
6967 
6968 	/*
6969 	 * Remove any existing match(es) for "name".  Normally there'd be at most
6970 	 * one, but if external tools have modified the config file, there could
6971 	 * be more.
6972 	 */
6973 	for (item = *head_p; item != NULL; item = next)
6974 	{
6975 		next = item->next;
6976 		if (guc_name_compare(item->name, name) == 0)
6977 		{
6978 			/* found a match, delete it */
6979 			if (prev)
6980 				prev->next = next;
6981 			else
6982 				*head_p = next;
6983 			if (next == NULL)
6984 				*tail_p = prev;
6985 
6986 			pfree(item->name);
6987 			pfree(item->value);
6988 			pfree(item->filename);
6989 			pfree(item);
6990 		}
6991 		else
6992 			prev = item;
6993 	}
6994 
6995 	/* Done if we're trying to delete it */
6996 	if (value == NULL)
6997 		return;
6998 
6999 	/* OK, append a new entry */
7000 	item = palloc(sizeof *item);
7001 	item->name = pstrdup(name);
7002 	item->value = pstrdup(value);
7003 	item->errmsg = NULL;
7004 	item->filename = pstrdup("");		/* new item has no location */
7005 	item->sourceline = 0;
7006 	item->ignore = false;
7007 	item->applied = false;
7008 	item->next = NULL;
7009 
7010 	if (*head_p == NULL)
7011 		*head_p = item;
7012 	else
7013 		(*tail_p)->next = item;
7014 	*tail_p = item;
7015 }
7016 
7017 
7018 /*
7019  * Execute ALTER SYSTEM statement.
7020  *
7021  * Read the old PG_AUTOCONF_FILENAME file, merge in the new variable value,
7022  * and write out an updated file.  If the command is ALTER SYSTEM RESET ALL,
7023  * we can skip reading the old file and just write an empty file.
7024  *
7025  * An LWLock is used to serialize updates of the configuration file.
7026  *
7027  * In case of an error, we leave the original automatic
7028  * configuration file (PG_AUTOCONF_FILENAME) intact.
7029  */
7030 void
AlterSystemSetConfigFile(AlterSystemStmt * altersysstmt)7031 AlterSystemSetConfigFile(AlterSystemStmt *altersysstmt)
7032 {
7033 	char	   *name;
7034 	char	   *value;
7035 	bool		resetall = false;
7036 	ConfigVariable *head = NULL;
7037 	ConfigVariable *tail = NULL;
7038 	volatile int Tmpfd;
7039 	char		AutoConfFileName[MAXPGPATH];
7040 	char		AutoConfTmpFileName[MAXPGPATH];
7041 
7042 	if (!superuser())
7043 		ereport(ERROR,
7044 				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
7045 			 (errmsg("must be superuser to execute ALTER SYSTEM command"))));
7046 
7047 	/*
7048 	 * Extract statement arguments
7049 	 */
7050 	name = altersysstmt->setstmt->name;
7051 
7052 	switch (altersysstmt->setstmt->kind)
7053 	{
7054 		case VAR_SET_VALUE:
7055 			value = ExtractSetVariableArgs(altersysstmt->setstmt);
7056 			break;
7057 
7058 		case VAR_SET_DEFAULT:
7059 		case VAR_RESET:
7060 			value = NULL;
7061 			break;
7062 
7063 		case VAR_RESET_ALL:
7064 			value = NULL;
7065 			resetall = true;
7066 			break;
7067 
7068 		default:
7069 			elog(ERROR, "unrecognized alter system stmt type: %d",
7070 				 altersysstmt->setstmt->kind);
7071 			break;
7072 	}
7073 
7074 	/*
7075 	 * Unless it's RESET_ALL, validate the target variable and value
7076 	 */
7077 	if (!resetall)
7078 	{
7079 		struct config_generic *record;
7080 
7081 		record = find_option(name, false, ERROR);
7082 		if (record == NULL)
7083 			ereport(ERROR,
7084 					(errcode(ERRCODE_UNDEFINED_OBJECT),
7085 					 errmsg("unrecognized configuration parameter \"%s\"",
7086 							name)));
7087 
7088 		/*
7089 		 * Don't allow parameters that can't be set in configuration files to
7090 		 * be set in PG_AUTOCONF_FILENAME file.
7091 		 */
7092 		if ((record->context == PGC_INTERNAL) ||
7093 			(record->flags & GUC_DISALLOW_IN_FILE) ||
7094 			(record->flags & GUC_DISALLOW_IN_AUTO_FILE))
7095 			ereport(ERROR,
7096 					(errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
7097 					 errmsg("parameter \"%s\" cannot be changed",
7098 							name)));
7099 
7100 		/*
7101 		 * If a value is specified, verify that it's sane.
7102 		 */
7103 		if (value)
7104 		{
7105 			union config_var_val newval;
7106 			void	   *newextra = NULL;
7107 
7108 			/* Check that it's acceptable for the indicated parameter */
7109 			if (!parse_and_validate_value(record, name, value,
7110 										  PGC_S_FILE, ERROR,
7111 										  &newval, &newextra))
7112 				ereport(ERROR,
7113 						(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
7114 						 errmsg("invalid value for parameter \"%s\": \"%s\"",
7115 								name, value)));
7116 
7117 			if (record->vartype == PGC_STRING && newval.stringval != NULL)
7118 				free(newval.stringval);
7119 			if (newextra)
7120 				free(newextra);
7121 
7122 			/*
7123 			 * We must also reject values containing newlines, because the
7124 			 * grammar for config files doesn't support embedded newlines in
7125 			 * string literals.
7126 			 */
7127 			if (strchr(value, '\n'))
7128 				ereport(ERROR,
7129 						(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
7130 						 errmsg("parameter value for ALTER SYSTEM must not contain a newline")));
7131 		}
7132 	}
7133 
7134 	/*
7135 	 * PG_AUTOCONF_FILENAME and its corresponding temporary file are always in
7136 	 * the data directory, so we can reference them by simple relative paths.
7137 	 */
7138 	snprintf(AutoConfFileName, sizeof(AutoConfFileName), "%s",
7139 			 PG_AUTOCONF_FILENAME);
7140 	snprintf(AutoConfTmpFileName, sizeof(AutoConfTmpFileName), "%s.%s",
7141 			 AutoConfFileName,
7142 			 "tmp");
7143 
7144 	/*
7145 	 * Only one backend is allowed to operate on PG_AUTOCONF_FILENAME at a
7146 	 * time.  Use AutoFileLock to ensure that.  We must hold the lock while
7147 	 * reading the old file contents.
7148 	 */
7149 	LWLockAcquire(AutoFileLock, LW_EXCLUSIVE);
7150 
7151 	/*
7152 	 * If we're going to reset everything, then no need to open or parse the
7153 	 * old file.  We'll just write out an empty list.
7154 	 */
7155 	if (!resetall)
7156 	{
7157 		struct stat st;
7158 
7159 		if (stat(AutoConfFileName, &st) == 0)
7160 		{
7161 			/* open old file PG_AUTOCONF_FILENAME */
7162 			FILE	   *infile;
7163 
7164 			infile = AllocateFile(AutoConfFileName, "r");
7165 			if (infile == NULL)
7166 				ereport(ERROR,
7167 						(errcode_for_file_access(),
7168 						 errmsg("could not open file \"%s\": %m",
7169 								AutoConfFileName)));
7170 
7171 			/* parse it */
7172 			if (!ParseConfigFp(infile, AutoConfFileName, 0, LOG, &head, &tail))
7173 				ereport(ERROR,
7174 						(errcode(ERRCODE_CONFIG_FILE_ERROR),
7175 						 errmsg("could not parse contents of file \"%s\"",
7176 								AutoConfFileName)));
7177 
7178 			FreeFile(infile);
7179 		}
7180 
7181 		/*
7182 		 * Now, replace any existing entry with the new value, or add it if
7183 		 * not present.
7184 		 */
7185 		replace_auto_config_value(&head, &tail, name, value);
7186 	}
7187 
7188 	/*
7189 	 * To ensure crash safety, first write the new file data to a temp file,
7190 	 * then atomically rename it into place.
7191 	 *
7192 	 * If there is a temp file left over due to a previous crash, it's okay to
7193 	 * truncate and reuse it.
7194 	 */
7195 	Tmpfd = BasicOpenFile(AutoConfTmpFileName,
7196 						  O_CREAT | O_RDWR | O_TRUNC,
7197 						  S_IRUSR | S_IWUSR);
7198 	if (Tmpfd < 0)
7199 		ereport(ERROR,
7200 				(errcode_for_file_access(),
7201 				 errmsg("could not open file \"%s\": %m",
7202 						AutoConfTmpFileName)));
7203 
7204 	/*
7205 	 * Use a TRY block to clean up the file if we fail.  Since we need a TRY
7206 	 * block anyway, OK to use BasicOpenFile rather than OpenTransientFile.
7207 	 */
7208 	PG_TRY();
7209 	{
7210 		/* Write and sync the new contents to the temporary file */
7211 		write_auto_conf_file(Tmpfd, AutoConfTmpFileName, head);
7212 
7213 		/* Close before renaming; may be required on some platforms */
7214 		close(Tmpfd);
7215 		Tmpfd = -1;
7216 
7217 		/*
7218 		 * As the rename is atomic operation, if any problem occurs after this
7219 		 * at worst it can lose the parameters set by last ALTER SYSTEM
7220 		 * command.
7221 		 */
7222 		durable_rename(AutoConfTmpFileName, AutoConfFileName, ERROR);
7223 	}
7224 	PG_CATCH();
7225 	{
7226 		/* Close file first, else unlink might fail on some platforms */
7227 		if (Tmpfd >= 0)
7228 			close(Tmpfd);
7229 
7230 		/* Unlink, but ignore any error */
7231 		(void) unlink(AutoConfTmpFileName);
7232 
7233 		PG_RE_THROW();
7234 	}
7235 	PG_END_TRY();
7236 
7237 	FreeConfigVariables(head);
7238 
7239 	LWLockRelease(AutoFileLock);
7240 }
7241 
7242 /*
7243  * SET command
7244  */
7245 void
ExecSetVariableStmt(VariableSetStmt * stmt,bool isTopLevel)7246 ExecSetVariableStmt(VariableSetStmt *stmt, bool isTopLevel)
7247 {
7248 	GucAction	action = stmt->is_local ? GUC_ACTION_LOCAL : GUC_ACTION_SET;
7249 
7250 	/*
7251 	 * Workers synchronize these parameters at the start of the parallel
7252 	 * operation; then, we block SET during the operation.
7253 	 */
7254 	if (IsInParallelMode())
7255 		ereport(ERROR,
7256 				(errcode(ERRCODE_INVALID_TRANSACTION_STATE),
7257 			   errmsg("cannot set parameters during a parallel operation")));
7258 
7259 	switch (stmt->kind)
7260 	{
7261 		case VAR_SET_VALUE:
7262 		case VAR_SET_CURRENT:
7263 			if (stmt->is_local)
7264 				WarnNoTransactionChain(isTopLevel, "SET LOCAL");
7265 			(void) set_config_option(stmt->name,
7266 									 ExtractSetVariableArgs(stmt),
7267 									 (superuser() ? PGC_SUSET : PGC_USERSET),
7268 									 PGC_S_SESSION,
7269 									 action, true, 0, false);
7270 			break;
7271 		case VAR_SET_MULTI:
7272 
7273 			/*
7274 			 * Special-case SQL syntaxes.  The TRANSACTION and SESSION
7275 			 * CHARACTERISTICS cases effectively set more than one variable
7276 			 * per statement.  TRANSACTION SNAPSHOT only takes one argument,
7277 			 * but we put it here anyway since it's a special case and not
7278 			 * related to any GUC variable.
7279 			 */
7280 			if (strcmp(stmt->name, "TRANSACTION") == 0)
7281 			{
7282 				ListCell   *head;
7283 
7284 				WarnNoTransactionChain(isTopLevel, "SET TRANSACTION");
7285 
7286 				foreach(head, stmt->args)
7287 				{
7288 					DefElem    *item = (DefElem *) lfirst(head);
7289 
7290 					if (strcmp(item->defname, "transaction_isolation") == 0)
7291 						SetPGVariable("transaction_isolation",
7292 									  list_make1(item->arg), stmt->is_local);
7293 					else if (strcmp(item->defname, "transaction_read_only") == 0)
7294 						SetPGVariable("transaction_read_only",
7295 									  list_make1(item->arg), stmt->is_local);
7296 					else if (strcmp(item->defname, "transaction_deferrable") == 0)
7297 						SetPGVariable("transaction_deferrable",
7298 									  list_make1(item->arg), stmt->is_local);
7299 					else
7300 						elog(ERROR, "unexpected SET TRANSACTION element: %s",
7301 							 item->defname);
7302 				}
7303 			}
7304 			else if (strcmp(stmt->name, "SESSION CHARACTERISTICS") == 0)
7305 			{
7306 				ListCell   *head;
7307 
7308 				foreach(head, stmt->args)
7309 				{
7310 					DefElem    *item = (DefElem *) lfirst(head);
7311 
7312 					if (strcmp(item->defname, "transaction_isolation") == 0)
7313 						SetPGVariable("default_transaction_isolation",
7314 									  list_make1(item->arg), stmt->is_local);
7315 					else if (strcmp(item->defname, "transaction_read_only") == 0)
7316 						SetPGVariable("default_transaction_read_only",
7317 									  list_make1(item->arg), stmt->is_local);
7318 					else if (strcmp(item->defname, "transaction_deferrable") == 0)
7319 						SetPGVariable("default_transaction_deferrable",
7320 									  list_make1(item->arg), stmt->is_local);
7321 					else
7322 						elog(ERROR, "unexpected SET SESSION element: %s",
7323 							 item->defname);
7324 				}
7325 			}
7326 			else if (strcmp(stmt->name, "TRANSACTION SNAPSHOT") == 0)
7327 			{
7328 				A_Const    *con = (A_Const *) linitial(stmt->args);
7329 
7330 				if (stmt->is_local)
7331 					ereport(ERROR,
7332 							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7333 							 errmsg("SET LOCAL TRANSACTION SNAPSHOT is not implemented")));
7334 
7335 				WarnNoTransactionChain(isTopLevel, "SET TRANSACTION");
7336 				Assert(IsA(con, A_Const));
7337 				Assert(nodeTag(&con->val) == T_String);
7338 				ImportSnapshot(strVal(&con->val));
7339 			}
7340 			else
7341 				elog(ERROR, "unexpected SET MULTI element: %s",
7342 					 stmt->name);
7343 			break;
7344 		case VAR_SET_DEFAULT:
7345 			if (stmt->is_local)
7346 				WarnNoTransactionChain(isTopLevel, "SET LOCAL");
7347 			/* fall through */
7348 		case VAR_RESET:
7349 			if (strcmp(stmt->name, "transaction_isolation") == 0)
7350 				WarnNoTransactionChain(isTopLevel, "RESET TRANSACTION");
7351 
7352 			(void) set_config_option(stmt->name,
7353 									 NULL,
7354 									 (superuser() ? PGC_SUSET : PGC_USERSET),
7355 									 PGC_S_SESSION,
7356 									 action, true, 0, false);
7357 			break;
7358 		case VAR_RESET_ALL:
7359 			ResetAllOptions();
7360 			break;
7361 	}
7362 }
7363 
7364 /*
7365  * Get the value to assign for a VariableSetStmt, or NULL if it's RESET.
7366  * The result is palloc'd.
7367  *
7368  * This is exported for use by actions such as ALTER ROLE SET.
7369  */
7370 char *
ExtractSetVariableArgs(VariableSetStmt * stmt)7371 ExtractSetVariableArgs(VariableSetStmt *stmt)
7372 {
7373 	switch (stmt->kind)
7374 	{
7375 		case VAR_SET_VALUE:
7376 			return flatten_set_variable_args(stmt->name, stmt->args);
7377 		case VAR_SET_CURRENT:
7378 			return GetConfigOptionByName(stmt->name, NULL, false);
7379 		default:
7380 			return NULL;
7381 	}
7382 }
7383 
7384 /*
7385  * SetPGVariable - SET command exported as an easily-C-callable function.
7386  *
7387  * This provides access to SET TO value, as well as SET TO DEFAULT (expressed
7388  * by passing args == NIL), but not SET FROM CURRENT functionality.
7389  */
7390 void
SetPGVariable(const char * name,List * args,bool is_local)7391 SetPGVariable(const char *name, List *args, bool is_local)
7392 {
7393 	char	   *argstring = flatten_set_variable_args(name, args);
7394 
7395 	/* Note SET DEFAULT (argstring == NULL) is equivalent to RESET */
7396 	(void) set_config_option(name,
7397 							 argstring,
7398 							 (superuser() ? PGC_SUSET : PGC_USERSET),
7399 							 PGC_S_SESSION,
7400 							 is_local ? GUC_ACTION_LOCAL : GUC_ACTION_SET,
7401 							 true, 0, false);
7402 }
7403 
7404 /*
7405  * SET command wrapped as a SQL callable function.
7406  */
7407 Datum
set_config_by_name(PG_FUNCTION_ARGS)7408 set_config_by_name(PG_FUNCTION_ARGS)
7409 {
7410 	char	   *name;
7411 	char	   *value;
7412 	char	   *new_value;
7413 	bool		is_local;
7414 
7415 	if (PG_ARGISNULL(0))
7416 		ereport(ERROR,
7417 				(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
7418 				 errmsg("SET requires parameter name")));
7419 
7420 	/* Get the GUC variable name */
7421 	name = TextDatumGetCString(PG_GETARG_DATUM(0));
7422 
7423 	/* Get the desired value or set to NULL for a reset request */
7424 	if (PG_ARGISNULL(1))
7425 		value = NULL;
7426 	else
7427 		value = TextDatumGetCString(PG_GETARG_DATUM(1));
7428 
7429 	/*
7430 	 * Get the desired state of is_local. Default to false if provided value
7431 	 * is NULL
7432 	 */
7433 	if (PG_ARGISNULL(2))
7434 		is_local = false;
7435 	else
7436 		is_local = PG_GETARG_BOOL(2);
7437 
7438 	/* Note SET DEFAULT (argstring == NULL) is equivalent to RESET */
7439 	(void) set_config_option(name,
7440 							 value,
7441 							 (superuser() ? PGC_SUSET : PGC_USERSET),
7442 							 PGC_S_SESSION,
7443 							 is_local ? GUC_ACTION_LOCAL : GUC_ACTION_SET,
7444 							 true, 0, false);
7445 
7446 	/* get the new current value */
7447 	new_value = GetConfigOptionByName(name, NULL, false);
7448 
7449 	/* Convert return string to text */
7450 	PG_RETURN_TEXT_P(cstring_to_text(new_value));
7451 }
7452 
7453 
7454 /*
7455  * Common code for DefineCustomXXXVariable subroutines: allocate the
7456  * new variable's config struct and fill in generic fields.
7457  */
7458 static struct config_generic *
init_custom_variable(const char * name,const char * short_desc,const char * long_desc,GucContext context,int flags,enum config_type type,size_t sz)7459 init_custom_variable(const char *name,
7460 					 const char *short_desc,
7461 					 const char *long_desc,
7462 					 GucContext context,
7463 					 int flags,
7464 					 enum config_type type,
7465 					 size_t sz)
7466 {
7467 	struct config_generic *gen;
7468 
7469 	/*
7470 	 * Only allow custom PGC_POSTMASTER variables to be created during shared
7471 	 * library preload; any later than that, we can't ensure that the value
7472 	 * doesn't change after startup.  This is a fatal elog if it happens; just
7473 	 * erroring out isn't safe because we don't know what the calling loadable
7474 	 * module might already have hooked into.
7475 	 */
7476 	if (context == PGC_POSTMASTER &&
7477 		!process_shared_preload_libraries_in_progress)
7478 		elog(FATAL, "cannot create PGC_POSTMASTER variables after startup");
7479 
7480 	/*
7481 	 * Before pljava commit 398f3b876ed402bdaec8bc804f29e2be95c75139
7482 	 * (2015-12-15), two of that module's PGC_USERSET variables facilitated
7483 	 * trivial escalation to superuser privileges.  Restrict the variables to
7484 	 * protect sites that have yet to upgrade pljava.
7485 	 */
7486 	if (context == PGC_USERSET &&
7487 		(strcmp(name, "pljava.classpath") == 0 ||
7488 		 strcmp(name, "pljava.vmoptions") == 0))
7489 		context = PGC_SUSET;
7490 
7491 	gen = (struct config_generic *) guc_malloc(ERROR, sz);
7492 	memset(gen, 0, sz);
7493 
7494 	gen->name = guc_strdup(ERROR, name);
7495 	gen->context = context;
7496 	gen->group = CUSTOM_OPTIONS;
7497 	gen->short_desc = short_desc;
7498 	gen->long_desc = long_desc;
7499 	gen->flags = flags;
7500 	gen->vartype = type;
7501 
7502 	return gen;
7503 }
7504 
7505 /*
7506  * Common code for DefineCustomXXXVariable subroutines: insert the new
7507  * variable into the GUC variable array, replacing any placeholder.
7508  */
7509 static void
define_custom_variable(struct config_generic * variable)7510 define_custom_variable(struct config_generic * variable)
7511 {
7512 	const char *name = variable->name;
7513 	const char **nameAddr = &name;
7514 	struct config_string *pHolder;
7515 	struct config_generic **res;
7516 
7517 	/*
7518 	 * See if there's a placeholder by the same name.
7519 	 */
7520 	res = (struct config_generic **) bsearch((void *) &nameAddr,
7521 											 (void *) guc_variables,
7522 											 num_guc_variables,
7523 											 sizeof(struct config_generic *),
7524 											 guc_var_compare);
7525 	if (res == NULL)
7526 	{
7527 		/*
7528 		 * No placeholder to replace, so we can just add it ... but first,
7529 		 * make sure it's initialized to its default value.
7530 		 */
7531 		InitializeOneGUCOption(variable);
7532 		add_guc_variable(variable, ERROR);
7533 		return;
7534 	}
7535 
7536 	/*
7537 	 * This better be a placeholder
7538 	 */
7539 	if (((*res)->flags & GUC_CUSTOM_PLACEHOLDER) == 0)
7540 		ereport(ERROR,
7541 				(errcode(ERRCODE_INTERNAL_ERROR),
7542 				 errmsg("attempt to redefine parameter \"%s\"", name)));
7543 
7544 	Assert((*res)->vartype == PGC_STRING);
7545 	pHolder = (struct config_string *) (*res);
7546 
7547 	/*
7548 	 * First, set the variable to its default value.  We must do this even
7549 	 * though we intend to immediately apply a new value, since it's possible
7550 	 * that the new value is invalid.
7551 	 */
7552 	InitializeOneGUCOption(variable);
7553 
7554 	/*
7555 	 * Replace the placeholder. We aren't changing the name, so no re-sorting
7556 	 * is necessary
7557 	 */
7558 	*res = variable;
7559 
7560 	/*
7561 	 * Assign the string value(s) stored in the placeholder to the real
7562 	 * variable.  Essentially, we need to duplicate all the active and stacked
7563 	 * values, but with appropriate validation and datatype adjustment.
7564 	 *
7565 	 * If an assignment fails, we report a WARNING and keep going.  We don't
7566 	 * want to throw ERROR for bad values, because it'd bollix the add-on
7567 	 * module that's presumably halfway through getting loaded.  In such cases
7568 	 * the default or previous state will become active instead.
7569 	 */
7570 
7571 	/* First, apply the reset value if any */
7572 	if (pHolder->reset_val)
7573 		(void) set_config_option(name, pHolder->reset_val,
7574 								 pHolder->gen.reset_scontext,
7575 								 pHolder->gen.reset_source,
7576 								 GUC_ACTION_SET, true, WARNING, false);
7577 	/* That should not have resulted in stacking anything */
7578 	Assert(variable->stack == NULL);
7579 
7580 	/* Now, apply current and stacked values, in the order they were stacked */
7581 	reapply_stacked_values(variable, pHolder, pHolder->gen.stack,
7582 						   *(pHolder->variable),
7583 						   pHolder->gen.scontext, pHolder->gen.source);
7584 
7585 	/* Also copy over any saved source-location information */
7586 	if (pHolder->gen.sourcefile)
7587 		set_config_sourcefile(name, pHolder->gen.sourcefile,
7588 							  pHolder->gen.sourceline);
7589 
7590 	/*
7591 	 * Free up as much as we conveniently can of the placeholder structure.
7592 	 * (This neglects any stack items, so it's possible for some memory to be
7593 	 * leaked.  Since this can only happen once per session per variable, it
7594 	 * doesn't seem worth spending much code on.)
7595 	 */
7596 	set_string_field(pHolder, pHolder->variable, NULL);
7597 	set_string_field(pHolder, &pHolder->reset_val, NULL);
7598 
7599 	free(pHolder);
7600 }
7601 
7602 /*
7603  * Recursive subroutine for define_custom_variable: reapply non-reset values
7604  *
7605  * We recurse so that the values are applied in the same order as originally.
7606  * At each recursion level, apply the upper-level value (passed in) in the
7607  * fashion implied by the stack entry.
7608  */
7609 static void
reapply_stacked_values(struct config_generic * variable,struct config_string * pHolder,GucStack * stack,const char * curvalue,GucContext curscontext,GucSource cursource)7610 reapply_stacked_values(struct config_generic * variable,
7611 					   struct config_string * pHolder,
7612 					   GucStack *stack,
7613 					   const char *curvalue,
7614 					   GucContext curscontext, GucSource cursource)
7615 {
7616 	const char *name = variable->name;
7617 	GucStack   *oldvarstack = variable->stack;
7618 
7619 	if (stack != NULL)
7620 	{
7621 		/* First, recurse, so that stack items are processed bottom to top */
7622 		reapply_stacked_values(variable, pHolder, stack->prev,
7623 							   stack->prior.val.stringval,
7624 							   stack->scontext, stack->source);
7625 
7626 		/* See how to apply the passed-in value */
7627 		switch (stack->state)
7628 		{
7629 			case GUC_SAVE:
7630 				(void) set_config_option(name, curvalue,
7631 										 curscontext, cursource,
7632 										 GUC_ACTION_SAVE, true,
7633 										 WARNING, false);
7634 				break;
7635 
7636 			case GUC_SET:
7637 				(void) set_config_option(name, curvalue,
7638 										 curscontext, cursource,
7639 										 GUC_ACTION_SET, true,
7640 										 WARNING, false);
7641 				break;
7642 
7643 			case GUC_LOCAL:
7644 				(void) set_config_option(name, curvalue,
7645 										 curscontext, cursource,
7646 										 GUC_ACTION_LOCAL, true,
7647 										 WARNING, false);
7648 				break;
7649 
7650 			case GUC_SET_LOCAL:
7651 				/* first, apply the masked value as SET */
7652 				(void) set_config_option(name, stack->masked.val.stringval,
7653 									   stack->masked_scontext, PGC_S_SESSION,
7654 										 GUC_ACTION_SET, true,
7655 										 WARNING, false);
7656 				/* then apply the current value as LOCAL */
7657 				(void) set_config_option(name, curvalue,
7658 										 curscontext, cursource,
7659 										 GUC_ACTION_LOCAL, true,
7660 										 WARNING, false);
7661 				break;
7662 		}
7663 
7664 		/* If we successfully made a stack entry, adjust its nest level */
7665 		if (variable->stack != oldvarstack)
7666 			variable->stack->nest_level = stack->nest_level;
7667 	}
7668 	else
7669 	{
7670 		/*
7671 		 * We are at the end of the stack.  If the active/previous value is
7672 		 * different from the reset value, it must represent a previously
7673 		 * committed session value.  Apply it, and then drop the stack entry
7674 		 * that set_config_option will have created under the impression that
7675 		 * this is to be just a transactional assignment.  (We leak the stack
7676 		 * entry.)
7677 		 */
7678 		if (curvalue != pHolder->reset_val ||
7679 			curscontext != pHolder->gen.reset_scontext ||
7680 			cursource != pHolder->gen.reset_source)
7681 		{
7682 			(void) set_config_option(name, curvalue,
7683 									 curscontext, cursource,
7684 									 GUC_ACTION_SET, true, WARNING, false);
7685 			variable->stack = NULL;
7686 		}
7687 	}
7688 }
7689 
7690 void
DefineCustomBoolVariable(const char * name,const char * short_desc,const char * long_desc,bool * valueAddr,bool bootValue,GucContext context,int flags,GucBoolCheckHook check_hook,GucBoolAssignHook assign_hook,GucShowHook show_hook)7691 DefineCustomBoolVariable(const char *name,
7692 						 const char *short_desc,
7693 						 const char *long_desc,
7694 						 bool *valueAddr,
7695 						 bool bootValue,
7696 						 GucContext context,
7697 						 int flags,
7698 						 GucBoolCheckHook check_hook,
7699 						 GucBoolAssignHook assign_hook,
7700 						 GucShowHook show_hook)
7701 {
7702 	struct config_bool *var;
7703 
7704 	var = (struct config_bool *)
7705 		init_custom_variable(name, short_desc, long_desc, context, flags,
7706 							 PGC_BOOL, sizeof(struct config_bool));
7707 	var->variable = valueAddr;
7708 	var->boot_val = bootValue;
7709 	var->reset_val = bootValue;
7710 	var->check_hook = check_hook;
7711 	var->assign_hook = assign_hook;
7712 	var->show_hook = show_hook;
7713 	define_custom_variable(&var->gen);
7714 }
7715 
7716 void
DefineCustomIntVariable(const char * name,const char * short_desc,const char * long_desc,int * valueAddr,int bootValue,int minValue,int maxValue,GucContext context,int flags,GucIntCheckHook check_hook,GucIntAssignHook assign_hook,GucShowHook show_hook)7717 DefineCustomIntVariable(const char *name,
7718 						const char *short_desc,
7719 						const char *long_desc,
7720 						int *valueAddr,
7721 						int bootValue,
7722 						int minValue,
7723 						int maxValue,
7724 						GucContext context,
7725 						int flags,
7726 						GucIntCheckHook check_hook,
7727 						GucIntAssignHook assign_hook,
7728 						GucShowHook show_hook)
7729 {
7730 	struct config_int *var;
7731 
7732 	var = (struct config_int *)
7733 		init_custom_variable(name, short_desc, long_desc, context, flags,
7734 							 PGC_INT, sizeof(struct config_int));
7735 	var->variable = valueAddr;
7736 	var->boot_val = bootValue;
7737 	var->reset_val = bootValue;
7738 	var->min = minValue;
7739 	var->max = maxValue;
7740 	var->check_hook = check_hook;
7741 	var->assign_hook = assign_hook;
7742 	var->show_hook = show_hook;
7743 	define_custom_variable(&var->gen);
7744 }
7745 
7746 void
DefineCustomRealVariable(const char * name,const char * short_desc,const char * long_desc,double * valueAddr,double bootValue,double minValue,double maxValue,GucContext context,int flags,GucRealCheckHook check_hook,GucRealAssignHook assign_hook,GucShowHook show_hook)7747 DefineCustomRealVariable(const char *name,
7748 						 const char *short_desc,
7749 						 const char *long_desc,
7750 						 double *valueAddr,
7751 						 double bootValue,
7752 						 double minValue,
7753 						 double maxValue,
7754 						 GucContext context,
7755 						 int flags,
7756 						 GucRealCheckHook check_hook,
7757 						 GucRealAssignHook assign_hook,
7758 						 GucShowHook show_hook)
7759 {
7760 	struct config_real *var;
7761 
7762 	var = (struct config_real *)
7763 		init_custom_variable(name, short_desc, long_desc, context, flags,
7764 							 PGC_REAL, sizeof(struct config_real));
7765 	var->variable = valueAddr;
7766 	var->boot_val = bootValue;
7767 	var->reset_val = bootValue;
7768 	var->min = minValue;
7769 	var->max = maxValue;
7770 	var->check_hook = check_hook;
7771 	var->assign_hook = assign_hook;
7772 	var->show_hook = show_hook;
7773 	define_custom_variable(&var->gen);
7774 }
7775 
7776 void
DefineCustomStringVariable(const char * name,const char * short_desc,const char * long_desc,char ** valueAddr,const char * bootValue,GucContext context,int flags,GucStringCheckHook check_hook,GucStringAssignHook assign_hook,GucShowHook show_hook)7777 DefineCustomStringVariable(const char *name,
7778 						   const char *short_desc,
7779 						   const char *long_desc,
7780 						   char **valueAddr,
7781 						   const char *bootValue,
7782 						   GucContext context,
7783 						   int flags,
7784 						   GucStringCheckHook check_hook,
7785 						   GucStringAssignHook assign_hook,
7786 						   GucShowHook show_hook)
7787 {
7788 	struct config_string *var;
7789 
7790 	var = (struct config_string *)
7791 		init_custom_variable(name, short_desc, long_desc, context, flags,
7792 							 PGC_STRING, sizeof(struct config_string));
7793 	var->variable = valueAddr;
7794 	var->boot_val = bootValue;
7795 	var->check_hook = check_hook;
7796 	var->assign_hook = assign_hook;
7797 	var->show_hook = show_hook;
7798 	define_custom_variable(&var->gen);
7799 }
7800 
7801 void
DefineCustomEnumVariable(const char * name,const char * short_desc,const char * long_desc,int * valueAddr,int bootValue,const struct config_enum_entry * options,GucContext context,int flags,GucEnumCheckHook check_hook,GucEnumAssignHook assign_hook,GucShowHook show_hook)7802 DefineCustomEnumVariable(const char *name,
7803 						 const char *short_desc,
7804 						 const char *long_desc,
7805 						 int *valueAddr,
7806 						 int bootValue,
7807 						 const struct config_enum_entry * options,
7808 						 GucContext context,
7809 						 int flags,
7810 						 GucEnumCheckHook check_hook,
7811 						 GucEnumAssignHook assign_hook,
7812 						 GucShowHook show_hook)
7813 {
7814 	struct config_enum *var;
7815 
7816 	var = (struct config_enum *)
7817 		init_custom_variable(name, short_desc, long_desc, context, flags,
7818 							 PGC_ENUM, sizeof(struct config_enum));
7819 	var->variable = valueAddr;
7820 	var->boot_val = bootValue;
7821 	var->reset_val = bootValue;
7822 	var->options = options;
7823 	var->check_hook = check_hook;
7824 	var->assign_hook = assign_hook;
7825 	var->show_hook = show_hook;
7826 	define_custom_variable(&var->gen);
7827 }
7828 
7829 void
EmitWarningsOnPlaceholders(const char * className)7830 EmitWarningsOnPlaceholders(const char *className)
7831 {
7832 	int			classLen = strlen(className);
7833 	int			i;
7834 
7835 	for (i = 0; i < num_guc_variables; i++)
7836 	{
7837 		struct config_generic *var = guc_variables[i];
7838 
7839 		if ((var->flags & GUC_CUSTOM_PLACEHOLDER) != 0 &&
7840 			strncmp(className, var->name, classLen) == 0 &&
7841 			var->name[classLen] == GUC_QUALIFIER_SEPARATOR)
7842 		{
7843 			ereport(WARNING,
7844 					(errcode(ERRCODE_UNDEFINED_OBJECT),
7845 					 errmsg("unrecognized configuration parameter \"%s\"",
7846 							var->name)));
7847 		}
7848 	}
7849 }
7850 
7851 
7852 /*
7853  * SHOW command
7854  */
7855 void
GetPGVariable(const char * name,DestReceiver * dest)7856 GetPGVariable(const char *name, DestReceiver *dest)
7857 {
7858 	if (guc_name_compare(name, "all") == 0)
7859 		ShowAllGUCConfig(dest);
7860 	else
7861 		ShowGUCConfigOption(name, dest);
7862 }
7863 
7864 TupleDesc
GetPGVariableResultDesc(const char * name)7865 GetPGVariableResultDesc(const char *name)
7866 {
7867 	TupleDesc	tupdesc;
7868 
7869 	if (guc_name_compare(name, "all") == 0)
7870 	{
7871 		/* need a tuple descriptor representing three TEXT columns */
7872 		tupdesc = CreateTemplateTupleDesc(3, false);
7873 		TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
7874 						   TEXTOID, -1, 0);
7875 		TupleDescInitEntry(tupdesc, (AttrNumber) 2, "setting",
7876 						   TEXTOID, -1, 0);
7877 		TupleDescInitEntry(tupdesc, (AttrNumber) 3, "description",
7878 						   TEXTOID, -1, 0);
7879 	}
7880 	else
7881 	{
7882 		const char *varname;
7883 
7884 		/* Get the canonical spelling of name */
7885 		(void) GetConfigOptionByName(name, &varname, false);
7886 
7887 		/* need a tuple descriptor representing a single TEXT column */
7888 		tupdesc = CreateTemplateTupleDesc(1, false);
7889 		TupleDescInitEntry(tupdesc, (AttrNumber) 1, varname,
7890 						   TEXTOID, -1, 0);
7891 	}
7892 	return tupdesc;
7893 }
7894 
7895 
7896 /*
7897  * SHOW command
7898  */
7899 static void
ShowGUCConfigOption(const char * name,DestReceiver * dest)7900 ShowGUCConfigOption(const char *name, DestReceiver *dest)
7901 {
7902 	TupOutputState *tstate;
7903 	TupleDesc	tupdesc;
7904 	const char *varname;
7905 	char	   *value;
7906 
7907 	/* Get the value and canonical spelling of name */
7908 	value = GetConfigOptionByName(name, &varname, false);
7909 
7910 	/* need a tuple descriptor representing a single TEXT column */
7911 	tupdesc = CreateTemplateTupleDesc(1, false);
7912 	TupleDescInitEntry(tupdesc, (AttrNumber) 1, varname,
7913 					   TEXTOID, -1, 0);
7914 
7915 	/* prepare for projection of tuples */
7916 	tstate = begin_tup_output_tupdesc(dest, tupdesc);
7917 
7918 	/* Send it */
7919 	do_text_output_oneline(tstate, value);
7920 
7921 	end_tup_output(tstate);
7922 }
7923 
7924 /*
7925  * SHOW ALL command
7926  */
7927 static void
ShowAllGUCConfig(DestReceiver * dest)7928 ShowAllGUCConfig(DestReceiver *dest)
7929 {
7930 	bool		am_superuser = superuser();
7931 	int			i;
7932 	TupOutputState *tstate;
7933 	TupleDesc	tupdesc;
7934 	Datum		values[3];
7935 	bool		isnull[3] = {false, false, false};
7936 
7937 	/* need a tuple descriptor representing three TEXT columns */
7938 	tupdesc = CreateTemplateTupleDesc(3, false);
7939 	TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
7940 					   TEXTOID, -1, 0);
7941 	TupleDescInitEntry(tupdesc, (AttrNumber) 2, "setting",
7942 					   TEXTOID, -1, 0);
7943 	TupleDescInitEntry(tupdesc, (AttrNumber) 3, "description",
7944 					   TEXTOID, -1, 0);
7945 
7946 	/* prepare for projection of tuples */
7947 	tstate = begin_tup_output_tupdesc(dest, tupdesc);
7948 
7949 	for (i = 0; i < num_guc_variables; i++)
7950 	{
7951 		struct config_generic *conf = guc_variables[i];
7952 		char	   *setting;
7953 
7954 		if ((conf->flags & GUC_NO_SHOW_ALL) ||
7955 			((conf->flags & GUC_SUPERUSER_ONLY) && !am_superuser))
7956 			continue;
7957 
7958 		/* assign to the values array */
7959 		values[0] = PointerGetDatum(cstring_to_text(conf->name));
7960 
7961 		setting = _ShowOption(conf, true);
7962 		if (setting)
7963 		{
7964 			values[1] = PointerGetDatum(cstring_to_text(setting));
7965 			isnull[1] = false;
7966 		}
7967 		else
7968 		{
7969 			values[1] = PointerGetDatum(NULL);
7970 			isnull[1] = true;
7971 		}
7972 
7973 		values[2] = PointerGetDatum(cstring_to_text(conf->short_desc));
7974 
7975 		/* send it to dest */
7976 		do_tup_output(tstate, values, isnull);
7977 
7978 		/* clean up */
7979 		pfree(DatumGetPointer(values[0]));
7980 		if (setting)
7981 		{
7982 			pfree(setting);
7983 			pfree(DatumGetPointer(values[1]));
7984 		}
7985 		pfree(DatumGetPointer(values[2]));
7986 	}
7987 
7988 	end_tup_output(tstate);
7989 }
7990 
7991 /*
7992  * Return GUC variable value by name; optionally return canonical form of
7993  * name.  If the GUC is unset, then throw an error unless missing_ok is true,
7994  * in which case return NULL.  Return value is palloc'd (but *varname isn't).
7995  */
7996 char *
GetConfigOptionByName(const char * name,const char ** varname,bool missing_ok)7997 GetConfigOptionByName(const char *name, const char **varname, bool missing_ok)
7998 {
7999 	struct config_generic *record;
8000 
8001 	record = find_option(name, false, ERROR);
8002 	if (record == NULL)
8003 	{
8004 		if (missing_ok)
8005 		{
8006 			if (varname)
8007 				*varname = NULL;
8008 			return NULL;
8009 		}
8010 
8011 		ereport(ERROR,
8012 				(errcode(ERRCODE_UNDEFINED_OBJECT),
8013 			   errmsg("unrecognized configuration parameter \"%s\"", name)));
8014 	}
8015 
8016 	if ((record->flags & GUC_SUPERUSER_ONLY) && !superuser())
8017 		ereport(ERROR,
8018 				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
8019 				 errmsg("must be superuser to examine \"%s\"", name)));
8020 
8021 	if (varname)
8022 		*varname = record->name;
8023 
8024 	return _ShowOption(record, true);
8025 }
8026 
8027 /*
8028  * Return GUC variable value by variable number; optionally return canonical
8029  * form of name.  Return value is palloc'd.
8030  */
8031 void
GetConfigOptionByNum(int varnum,const char ** values,bool * noshow)8032 GetConfigOptionByNum(int varnum, const char **values, bool *noshow)
8033 {
8034 	char		buffer[256];
8035 	struct config_generic *conf;
8036 
8037 	/* check requested variable number valid */
8038 	Assert((varnum >= 0) && (varnum < num_guc_variables));
8039 
8040 	conf = guc_variables[varnum];
8041 
8042 	if (noshow)
8043 	{
8044 		if ((conf->flags & GUC_NO_SHOW_ALL) ||
8045 			((conf->flags & GUC_SUPERUSER_ONLY) && !superuser()))
8046 			*noshow = true;
8047 		else
8048 			*noshow = false;
8049 	}
8050 
8051 	/* first get the generic attributes */
8052 
8053 	/* name */
8054 	values[0] = conf->name;
8055 
8056 	/* setting : use _ShowOption in order to avoid duplicating the logic */
8057 	values[1] = _ShowOption(conf, false);
8058 
8059 	/* unit */
8060 	if (conf->vartype == PGC_INT)
8061 	{
8062 		switch (conf->flags & (GUC_UNIT_MEMORY | GUC_UNIT_TIME))
8063 		{
8064 			case GUC_UNIT_KB:
8065 				values[2] = "kB";
8066 				break;
8067 			case GUC_UNIT_BLOCKS:
8068 				snprintf(buffer, sizeof(buffer), "%dkB", BLCKSZ / 1024);
8069 				values[2] = pstrdup(buffer);
8070 				break;
8071 			case GUC_UNIT_XBLOCKS:
8072 				snprintf(buffer, sizeof(buffer), "%dkB", XLOG_BLCKSZ / 1024);
8073 				values[2] = pstrdup(buffer);
8074 				break;
8075 			case GUC_UNIT_XSEGS:
8076 				snprintf(buffer, sizeof(buffer), "%dMB",
8077 						 XLOG_SEG_SIZE / (1024 * 1024));
8078 				values[2] = pstrdup(buffer);
8079 				break;
8080 			case GUC_UNIT_MS:
8081 				values[2] = "ms";
8082 				break;
8083 			case GUC_UNIT_S:
8084 				values[2] = "s";
8085 				break;
8086 			case GUC_UNIT_MIN:
8087 				values[2] = "min";
8088 				break;
8089 			case 0:
8090 				values[2] = NULL;
8091 				break;
8092 			default:
8093 				elog(ERROR, "unrecognized GUC units value: %d",
8094 					 conf->flags & (GUC_UNIT_MEMORY | GUC_UNIT_TIME));
8095 				values[2] = NULL;
8096 				break;
8097 		}
8098 	}
8099 	else
8100 		values[2] = NULL;
8101 
8102 	/* group */
8103 	values[3] = config_group_names[conf->group];
8104 
8105 	/* short_desc */
8106 	values[4] = conf->short_desc;
8107 
8108 	/* extra_desc */
8109 	values[5] = conf->long_desc;
8110 
8111 	/* context */
8112 	values[6] = GucContext_Names[conf->context];
8113 
8114 	/* vartype */
8115 	values[7] = config_type_names[conf->vartype];
8116 
8117 	/* source */
8118 	values[8] = GucSource_Names[conf->source];
8119 
8120 	/* now get the type specific attributes */
8121 	switch (conf->vartype)
8122 	{
8123 		case PGC_BOOL:
8124 			{
8125 				struct config_bool *lconf = (struct config_bool *) conf;
8126 
8127 				/* min_val */
8128 				values[9] = NULL;
8129 
8130 				/* max_val */
8131 				values[10] = NULL;
8132 
8133 				/* enumvals */
8134 				values[11] = NULL;
8135 
8136 				/* boot_val */
8137 				values[12] = pstrdup(lconf->boot_val ? "on" : "off");
8138 
8139 				/* reset_val */
8140 				values[13] = pstrdup(lconf->reset_val ? "on" : "off");
8141 			}
8142 			break;
8143 
8144 		case PGC_INT:
8145 			{
8146 				struct config_int *lconf = (struct config_int *) conf;
8147 
8148 				/* min_val */
8149 				snprintf(buffer, sizeof(buffer), "%d", lconf->min);
8150 				values[9] = pstrdup(buffer);
8151 
8152 				/* max_val */
8153 				snprintf(buffer, sizeof(buffer), "%d", lconf->max);
8154 				values[10] = pstrdup(buffer);
8155 
8156 				/* enumvals */
8157 				values[11] = NULL;
8158 
8159 				/* boot_val */
8160 				snprintf(buffer, sizeof(buffer), "%d", lconf->boot_val);
8161 				values[12] = pstrdup(buffer);
8162 
8163 				/* reset_val */
8164 				snprintf(buffer, sizeof(buffer), "%d", lconf->reset_val);
8165 				values[13] = pstrdup(buffer);
8166 			}
8167 			break;
8168 
8169 		case PGC_REAL:
8170 			{
8171 				struct config_real *lconf = (struct config_real *) conf;
8172 
8173 				/* min_val */
8174 				snprintf(buffer, sizeof(buffer), "%g", lconf->min);
8175 				values[9] = pstrdup(buffer);
8176 
8177 				/* max_val */
8178 				snprintf(buffer, sizeof(buffer), "%g", lconf->max);
8179 				values[10] = pstrdup(buffer);
8180 
8181 				/* enumvals */
8182 				values[11] = NULL;
8183 
8184 				/* boot_val */
8185 				snprintf(buffer, sizeof(buffer), "%g", lconf->boot_val);
8186 				values[12] = pstrdup(buffer);
8187 
8188 				/* reset_val */
8189 				snprintf(buffer, sizeof(buffer), "%g", lconf->reset_val);
8190 				values[13] = pstrdup(buffer);
8191 			}
8192 			break;
8193 
8194 		case PGC_STRING:
8195 			{
8196 				struct config_string *lconf = (struct config_string *) conf;
8197 
8198 				/* min_val */
8199 				values[9] = NULL;
8200 
8201 				/* max_val */
8202 				values[10] = NULL;
8203 
8204 				/* enumvals */
8205 				values[11] = NULL;
8206 
8207 				/* boot_val */
8208 				if (lconf->boot_val == NULL)
8209 					values[12] = NULL;
8210 				else
8211 					values[12] = pstrdup(lconf->boot_val);
8212 
8213 				/* reset_val */
8214 				if (lconf->reset_val == NULL)
8215 					values[13] = NULL;
8216 				else
8217 					values[13] = pstrdup(lconf->reset_val);
8218 			}
8219 			break;
8220 
8221 		case PGC_ENUM:
8222 			{
8223 				struct config_enum *lconf = (struct config_enum *) conf;
8224 
8225 				/* min_val */
8226 				values[9] = NULL;
8227 
8228 				/* max_val */
8229 				values[10] = NULL;
8230 
8231 				/* enumvals */
8232 
8233 				/*
8234 				 * NOTE! enumvals with double quotes in them are not
8235 				 * supported!
8236 				 */
8237 				values[11] = config_enum_get_options((struct config_enum *) conf,
8238 													 "{\"", "\"}", "\",\"");
8239 
8240 				/* boot_val */
8241 				values[12] = pstrdup(config_enum_lookup_by_value(lconf,
8242 														   lconf->boot_val));
8243 
8244 				/* reset_val */
8245 				values[13] = pstrdup(config_enum_lookup_by_value(lconf,
8246 														  lconf->reset_val));
8247 			}
8248 			break;
8249 
8250 		default:
8251 			{
8252 				/*
8253 				 * should never get here, but in case we do, set 'em to NULL
8254 				 */
8255 
8256 				/* min_val */
8257 				values[9] = NULL;
8258 
8259 				/* max_val */
8260 				values[10] = NULL;
8261 
8262 				/* enumvals */
8263 				values[11] = NULL;
8264 
8265 				/* boot_val */
8266 				values[12] = NULL;
8267 
8268 				/* reset_val */
8269 				values[13] = NULL;
8270 			}
8271 			break;
8272 	}
8273 
8274 	/*
8275 	 * If the setting came from a config file, set the source location. For
8276 	 * security reasons, we don't show source file/line number for
8277 	 * non-superusers.
8278 	 */
8279 	if (conf->source == PGC_S_FILE && superuser())
8280 	{
8281 		values[14] = conf->sourcefile;
8282 		snprintf(buffer, sizeof(buffer), "%d", conf->sourceline);
8283 		values[15] = pstrdup(buffer);
8284 	}
8285 	else
8286 	{
8287 		values[14] = NULL;
8288 		values[15] = NULL;
8289 	}
8290 
8291 	values[16] = (conf->status & GUC_PENDING_RESTART) ? "t" : "f";
8292 }
8293 
8294 /*
8295  * Return the total number of GUC variables
8296  */
8297 int
GetNumConfigOptions(void)8298 GetNumConfigOptions(void)
8299 {
8300 	return num_guc_variables;
8301 }
8302 
8303 /*
8304  * show_config_by_name - equiv to SHOW X command but implemented as
8305  * a function.
8306  */
8307 Datum
show_config_by_name(PG_FUNCTION_ARGS)8308 show_config_by_name(PG_FUNCTION_ARGS)
8309 {
8310 	char	   *varname = TextDatumGetCString(PG_GETARG_DATUM(0));
8311 	char	   *varval;
8312 
8313 	/* Get the value */
8314 	varval = GetConfigOptionByName(varname, NULL, false);
8315 
8316 	/* Convert to text */
8317 	PG_RETURN_TEXT_P(cstring_to_text(varval));
8318 }
8319 
8320 /*
8321  * show_config_by_name_missing_ok - equiv to SHOW X command but implemented as
8322  * a function.  If X does not exist, suppress the error and just return NULL
8323  * if missing_ok is TRUE.
8324  */
8325 Datum
show_config_by_name_missing_ok(PG_FUNCTION_ARGS)8326 show_config_by_name_missing_ok(PG_FUNCTION_ARGS)
8327 {
8328 	char	   *varname = TextDatumGetCString(PG_GETARG_DATUM(0));
8329 	bool		missing_ok = PG_GETARG_BOOL(1);
8330 	char	   *varval;
8331 
8332 	/* Get the value */
8333 	varval = GetConfigOptionByName(varname, NULL, missing_ok);
8334 
8335 	/* return NULL if no such variable */
8336 	if (varval == NULL)
8337 		PG_RETURN_NULL();
8338 
8339 	/* Convert to text */
8340 	PG_RETURN_TEXT_P(cstring_to_text(varval));
8341 }
8342 
8343 /*
8344  * show_all_settings - equiv to SHOW ALL command but implemented as
8345  * a Table Function.
8346  */
8347 #define NUM_PG_SETTINGS_ATTS	17
8348 
8349 Datum
show_all_settings(PG_FUNCTION_ARGS)8350 show_all_settings(PG_FUNCTION_ARGS)
8351 {
8352 	FuncCallContext *funcctx;
8353 	TupleDesc	tupdesc;
8354 	int			call_cntr;
8355 	int			max_calls;
8356 	AttInMetadata *attinmeta;
8357 	MemoryContext oldcontext;
8358 
8359 	/* stuff done only on the first call of the function */
8360 	if (SRF_IS_FIRSTCALL())
8361 	{
8362 		/* create a function context for cross-call persistence */
8363 		funcctx = SRF_FIRSTCALL_INIT();
8364 
8365 		/*
8366 		 * switch to memory context appropriate for multiple function calls
8367 		 */
8368 		oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
8369 
8370 		/*
8371 		 * need a tuple descriptor representing NUM_PG_SETTINGS_ATTS columns
8372 		 * of the appropriate types
8373 		 */
8374 		tupdesc = CreateTemplateTupleDesc(NUM_PG_SETTINGS_ATTS, false);
8375 		TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
8376 						   TEXTOID, -1, 0);
8377 		TupleDescInitEntry(tupdesc, (AttrNumber) 2, "setting",
8378 						   TEXTOID, -1, 0);
8379 		TupleDescInitEntry(tupdesc, (AttrNumber) 3, "unit",
8380 						   TEXTOID, -1, 0);
8381 		TupleDescInitEntry(tupdesc, (AttrNumber) 4, "category",
8382 						   TEXTOID, -1, 0);
8383 		TupleDescInitEntry(tupdesc, (AttrNumber) 5, "short_desc",
8384 						   TEXTOID, -1, 0);
8385 		TupleDescInitEntry(tupdesc, (AttrNumber) 6, "extra_desc",
8386 						   TEXTOID, -1, 0);
8387 		TupleDescInitEntry(tupdesc, (AttrNumber) 7, "context",
8388 						   TEXTOID, -1, 0);
8389 		TupleDescInitEntry(tupdesc, (AttrNumber) 8, "vartype",
8390 						   TEXTOID, -1, 0);
8391 		TupleDescInitEntry(tupdesc, (AttrNumber) 9, "source",
8392 						   TEXTOID, -1, 0);
8393 		TupleDescInitEntry(tupdesc, (AttrNumber) 10, "min_val",
8394 						   TEXTOID, -1, 0);
8395 		TupleDescInitEntry(tupdesc, (AttrNumber) 11, "max_val",
8396 						   TEXTOID, -1, 0);
8397 		TupleDescInitEntry(tupdesc, (AttrNumber) 12, "enumvals",
8398 						   TEXTARRAYOID, -1, 0);
8399 		TupleDescInitEntry(tupdesc, (AttrNumber) 13, "boot_val",
8400 						   TEXTOID, -1, 0);
8401 		TupleDescInitEntry(tupdesc, (AttrNumber) 14, "reset_val",
8402 						   TEXTOID, -1, 0);
8403 		TupleDescInitEntry(tupdesc, (AttrNumber) 15, "sourcefile",
8404 						   TEXTOID, -1, 0);
8405 		TupleDescInitEntry(tupdesc, (AttrNumber) 16, "sourceline",
8406 						   INT4OID, -1, 0);
8407 		TupleDescInitEntry(tupdesc, (AttrNumber) 17, "pending_restart",
8408 						   BOOLOID, -1, 0);
8409 
8410 		/*
8411 		 * Generate attribute metadata needed later to produce tuples from raw
8412 		 * C strings
8413 		 */
8414 		attinmeta = TupleDescGetAttInMetadata(tupdesc);
8415 		funcctx->attinmeta = attinmeta;
8416 
8417 		/* total number of tuples to be returned */
8418 		funcctx->max_calls = GetNumConfigOptions();
8419 
8420 		MemoryContextSwitchTo(oldcontext);
8421 	}
8422 
8423 	/* stuff done on every call of the function */
8424 	funcctx = SRF_PERCALL_SETUP();
8425 
8426 	call_cntr = funcctx->call_cntr;
8427 	max_calls = funcctx->max_calls;
8428 	attinmeta = funcctx->attinmeta;
8429 
8430 	if (call_cntr < max_calls)	/* do when there is more left to send */
8431 	{
8432 		char	   *values[NUM_PG_SETTINGS_ATTS];
8433 		bool		noshow;
8434 		HeapTuple	tuple;
8435 		Datum		result;
8436 
8437 		/*
8438 		 * Get the next visible GUC variable name and value
8439 		 */
8440 		do
8441 		{
8442 			GetConfigOptionByNum(call_cntr, (const char **) values, &noshow);
8443 			if (noshow)
8444 			{
8445 				/* bump the counter and get the next config setting */
8446 				call_cntr = ++funcctx->call_cntr;
8447 
8448 				/* make sure we haven't gone too far now */
8449 				if (call_cntr >= max_calls)
8450 					SRF_RETURN_DONE(funcctx);
8451 			}
8452 		} while (noshow);
8453 
8454 		/* build a tuple */
8455 		tuple = BuildTupleFromCStrings(attinmeta, values);
8456 
8457 		/* make the tuple into a datum */
8458 		result = HeapTupleGetDatum(tuple);
8459 
8460 		SRF_RETURN_NEXT(funcctx, result);
8461 	}
8462 	else
8463 	{
8464 		/* do when there is no more left */
8465 		SRF_RETURN_DONE(funcctx);
8466 	}
8467 }
8468 
8469 /*
8470  * show_all_file_settings
8471  *
8472  * Returns a table of all parameter settings in all configuration files
8473  * which includes the config file pathname, the line number, a sequence number
8474  * indicating the order in which the settings were encountered, the parameter
8475  * name and value, a bool showing if the value could be applied, and possibly
8476  * an associated error message.  (For problems such as syntax errors, the
8477  * parameter name/value might be NULL.)
8478  *
8479  * Note: no filtering is done here, instead we depend on the GRANT system
8480  * to prevent unprivileged users from accessing this function or the view
8481  * built on top of it.
8482  */
8483 Datum
show_all_file_settings(PG_FUNCTION_ARGS)8484 show_all_file_settings(PG_FUNCTION_ARGS)
8485 {
8486 #define NUM_PG_FILE_SETTINGS_ATTS 7
8487 	ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
8488 	TupleDesc	tupdesc;
8489 	Tuplestorestate *tupstore;
8490 	ConfigVariable *conf;
8491 	int			seqno;
8492 	MemoryContext per_query_ctx;
8493 	MemoryContext oldcontext;
8494 
8495 	/* Check to see if caller supports us returning a tuplestore */
8496 	if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
8497 		ereport(ERROR,
8498 				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8499 				 errmsg("set-valued function called in context that cannot accept a set")));
8500 	if (!(rsinfo->allowedModes & SFRM_Materialize))
8501 		ereport(ERROR,
8502 				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8503 				 errmsg("materialize mode required, but it is not " \
8504 						"allowed in this context")));
8505 
8506 	/* Scan the config files using current context as workspace */
8507 	conf = ProcessConfigFileInternal(PGC_SIGHUP, false, DEBUG3);
8508 
8509 	/* Switch into long-lived context to construct returned data structures */
8510 	per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
8511 	oldcontext = MemoryContextSwitchTo(per_query_ctx);
8512 
8513 	/* Build a tuple descriptor for our result type */
8514 	tupdesc = CreateTemplateTupleDesc(NUM_PG_FILE_SETTINGS_ATTS, false);
8515 	TupleDescInitEntry(tupdesc, (AttrNumber) 1, "sourcefile",
8516 					   TEXTOID, -1, 0);
8517 	TupleDescInitEntry(tupdesc, (AttrNumber) 2, "sourceline",
8518 					   INT4OID, -1, 0);
8519 	TupleDescInitEntry(tupdesc, (AttrNumber) 3, "seqno",
8520 					   INT4OID, -1, 0);
8521 	TupleDescInitEntry(tupdesc, (AttrNumber) 4, "name",
8522 					   TEXTOID, -1, 0);
8523 	TupleDescInitEntry(tupdesc, (AttrNumber) 5, "setting",
8524 					   TEXTOID, -1, 0);
8525 	TupleDescInitEntry(tupdesc, (AttrNumber) 6, "applied",
8526 					   BOOLOID, -1, 0);
8527 	TupleDescInitEntry(tupdesc, (AttrNumber) 7, "error",
8528 					   TEXTOID, -1, 0);
8529 
8530 	/* Build a tuplestore to return our results in */
8531 	tupstore = tuplestore_begin_heap(true, false, work_mem);
8532 	rsinfo->returnMode = SFRM_Materialize;
8533 	rsinfo->setResult = tupstore;
8534 	rsinfo->setDesc = tupdesc;
8535 
8536 	/* The rest can be done in short-lived context */
8537 	MemoryContextSwitchTo(oldcontext);
8538 
8539 	/* Process the results and create a tuplestore */
8540 	for (seqno = 1; conf != NULL; conf = conf->next, seqno++)
8541 	{
8542 		Datum		values[NUM_PG_FILE_SETTINGS_ATTS];
8543 		bool		nulls[NUM_PG_FILE_SETTINGS_ATTS];
8544 
8545 		memset(values, 0, sizeof(values));
8546 		memset(nulls, 0, sizeof(nulls));
8547 
8548 		/* sourcefile */
8549 		if (conf->filename)
8550 			values[0] = PointerGetDatum(cstring_to_text(conf->filename));
8551 		else
8552 			nulls[0] = true;
8553 
8554 		/* sourceline (not meaningful if no sourcefile) */
8555 		if (conf->filename)
8556 			values[1] = Int32GetDatum(conf->sourceline);
8557 		else
8558 			nulls[1] = true;
8559 
8560 		/* seqno */
8561 		values[2] = Int32GetDatum(seqno);
8562 
8563 		/* name */
8564 		if (conf->name)
8565 			values[3] = PointerGetDatum(cstring_to_text(conf->name));
8566 		else
8567 			nulls[3] = true;
8568 
8569 		/* setting */
8570 		if (conf->value)
8571 			values[4] = PointerGetDatum(cstring_to_text(conf->value));
8572 		else
8573 			nulls[4] = true;
8574 
8575 		/* applied */
8576 		values[5] = BoolGetDatum(conf->applied);
8577 
8578 		/* error */
8579 		if (conf->errmsg)
8580 			values[6] = PointerGetDatum(cstring_to_text(conf->errmsg));
8581 		else
8582 			nulls[6] = true;
8583 
8584 		/* shove row into tuplestore */
8585 		tuplestore_putvalues(tupstore, tupdesc, values, nulls);
8586 	}
8587 
8588 	tuplestore_donestoring(tupstore);
8589 
8590 	return (Datum) 0;
8591 }
8592 
8593 static char *
_ShowOption(struct config_generic * record,bool use_units)8594 _ShowOption(struct config_generic * record, bool use_units)
8595 {
8596 	char		buffer[256];
8597 	const char *val;
8598 
8599 	switch (record->vartype)
8600 	{
8601 		case PGC_BOOL:
8602 			{
8603 				struct config_bool *conf = (struct config_bool *) record;
8604 
8605 				if (conf->show_hook)
8606 					val = (*conf->show_hook) ();
8607 				else
8608 					val = *conf->variable ? "on" : "off";
8609 			}
8610 			break;
8611 
8612 		case PGC_INT:
8613 			{
8614 				struct config_int *conf = (struct config_int *) record;
8615 
8616 				if (conf->show_hook)
8617 					val = (*conf->show_hook) ();
8618 				else
8619 				{
8620 					/*
8621 					 * Use int64 arithmetic to avoid overflows in units
8622 					 * conversion.
8623 					 */
8624 					int64		result = *conf->variable;
8625 					const char *unit;
8626 
8627 					if (use_units && result > 0 && (record->flags & GUC_UNIT))
8628 					{
8629 						convert_from_base_unit(result, record->flags & GUC_UNIT,
8630 											   &result, &unit);
8631 					}
8632 					else
8633 						unit = "";
8634 
8635 					snprintf(buffer, sizeof(buffer), INT64_FORMAT "%s",
8636 							 result, unit);
8637 					val = buffer;
8638 				}
8639 			}
8640 			break;
8641 
8642 		case PGC_REAL:
8643 			{
8644 				struct config_real *conf = (struct config_real *) record;
8645 
8646 				if (conf->show_hook)
8647 					val = (*conf->show_hook) ();
8648 				else
8649 				{
8650 					snprintf(buffer, sizeof(buffer), "%g",
8651 							 *conf->variable);
8652 					val = buffer;
8653 				}
8654 			}
8655 			break;
8656 
8657 		case PGC_STRING:
8658 			{
8659 				struct config_string *conf = (struct config_string *) record;
8660 
8661 				if (conf->show_hook)
8662 					val = (*conf->show_hook) ();
8663 				else if (*conf->variable && **conf->variable)
8664 					val = *conf->variable;
8665 				else
8666 					val = "";
8667 			}
8668 			break;
8669 
8670 		case PGC_ENUM:
8671 			{
8672 				struct config_enum *conf = (struct config_enum *) record;
8673 
8674 				if (conf->show_hook)
8675 					val = (*conf->show_hook) ();
8676 				else
8677 					val = config_enum_lookup_by_value(conf, *conf->variable);
8678 			}
8679 			break;
8680 
8681 		default:
8682 			/* just to keep compiler quiet */
8683 			val = "???";
8684 			break;
8685 	}
8686 
8687 	return pstrdup(val);
8688 }
8689 
8690 
8691 #ifdef EXEC_BACKEND
8692 
8693 /*
8694  *	These routines dump out all non-default GUC options into a binary
8695  *	file that is read by all exec'ed backends.  The format is:
8696  *
8697  *		variable name, string, null terminated
8698  *		variable value, string, null terminated
8699  *		variable sourcefile, string, null terminated (empty if none)
8700  *		variable sourceline, integer
8701  *		variable source, integer
8702  *		variable scontext, integer
8703  */
8704 static void
write_one_nondefault_variable(FILE * fp,struct config_generic * gconf)8705 write_one_nondefault_variable(FILE *fp, struct config_generic * gconf)
8706 {
8707 	if (gconf->source == PGC_S_DEFAULT)
8708 		return;
8709 
8710 	fprintf(fp, "%s", gconf->name);
8711 	fputc(0, fp);
8712 
8713 	switch (gconf->vartype)
8714 	{
8715 		case PGC_BOOL:
8716 			{
8717 				struct config_bool *conf = (struct config_bool *) gconf;
8718 
8719 				if (*conf->variable)
8720 					fprintf(fp, "true");
8721 				else
8722 					fprintf(fp, "false");
8723 			}
8724 			break;
8725 
8726 		case PGC_INT:
8727 			{
8728 				struct config_int *conf = (struct config_int *) gconf;
8729 
8730 				fprintf(fp, "%d", *conf->variable);
8731 			}
8732 			break;
8733 
8734 		case PGC_REAL:
8735 			{
8736 				struct config_real *conf = (struct config_real *) gconf;
8737 
8738 				fprintf(fp, "%.17g", *conf->variable);
8739 			}
8740 			break;
8741 
8742 		case PGC_STRING:
8743 			{
8744 				struct config_string *conf = (struct config_string *) gconf;
8745 
8746 				fprintf(fp, "%s", *conf->variable);
8747 			}
8748 			break;
8749 
8750 		case PGC_ENUM:
8751 			{
8752 				struct config_enum *conf = (struct config_enum *) gconf;
8753 
8754 				fprintf(fp, "%s",
8755 						config_enum_lookup_by_value(conf, *conf->variable));
8756 			}
8757 			break;
8758 	}
8759 
8760 	fputc(0, fp);
8761 
8762 	if (gconf->sourcefile)
8763 		fprintf(fp, "%s", gconf->sourcefile);
8764 	fputc(0, fp);
8765 
8766 	fwrite(&gconf->sourceline, 1, sizeof(gconf->sourceline), fp);
8767 	fwrite(&gconf->source, 1, sizeof(gconf->source), fp);
8768 	fwrite(&gconf->scontext, 1, sizeof(gconf->scontext), fp);
8769 }
8770 
8771 void
write_nondefault_variables(GucContext context)8772 write_nondefault_variables(GucContext context)
8773 {
8774 	int			elevel;
8775 	FILE	   *fp;
8776 	int			i;
8777 
8778 	Assert(context == PGC_POSTMASTER || context == PGC_SIGHUP);
8779 
8780 	elevel = (context == PGC_SIGHUP) ? LOG : ERROR;
8781 
8782 	/*
8783 	 * Open file
8784 	 */
8785 	fp = AllocateFile(CONFIG_EXEC_PARAMS_NEW, "w");
8786 	if (!fp)
8787 	{
8788 		ereport(elevel,
8789 				(errcode_for_file_access(),
8790 				 errmsg("could not write to file \"%s\": %m",
8791 						CONFIG_EXEC_PARAMS_NEW)));
8792 		return;
8793 	}
8794 
8795 	for (i = 0; i < num_guc_variables; i++)
8796 	{
8797 		write_one_nondefault_variable(fp, guc_variables[i]);
8798 	}
8799 
8800 	if (FreeFile(fp))
8801 	{
8802 		ereport(elevel,
8803 				(errcode_for_file_access(),
8804 				 errmsg("could not write to file \"%s\": %m",
8805 						CONFIG_EXEC_PARAMS_NEW)));
8806 		return;
8807 	}
8808 
8809 	/*
8810 	 * Put new file in place.  This could delay on Win32, but we don't hold
8811 	 * any exclusive locks.
8812 	 */
8813 	rename(CONFIG_EXEC_PARAMS_NEW, CONFIG_EXEC_PARAMS);
8814 }
8815 
8816 
8817 /*
8818  *	Read string, including null byte from file
8819  *
8820  *	Return NULL on EOF and nothing read
8821  */
8822 static char *
read_string_with_null(FILE * fp)8823 read_string_with_null(FILE *fp)
8824 {
8825 	int			i = 0,
8826 				ch,
8827 				maxlen = 256;
8828 	char	   *str = NULL;
8829 
8830 	do
8831 	{
8832 		if ((ch = fgetc(fp)) == EOF)
8833 		{
8834 			if (i == 0)
8835 				return NULL;
8836 			else
8837 				elog(FATAL, "invalid format of exec config params file");
8838 		}
8839 		if (i == 0)
8840 			str = guc_malloc(FATAL, maxlen);
8841 		else if (i == maxlen)
8842 			str = guc_realloc(FATAL, str, maxlen *= 2);
8843 		str[i++] = ch;
8844 	} while (ch != 0);
8845 
8846 	return str;
8847 }
8848 
8849 
8850 /*
8851  *	This routine loads a previous postmaster dump of its non-default
8852  *	settings.
8853  */
8854 void
read_nondefault_variables(void)8855 read_nondefault_variables(void)
8856 {
8857 	FILE	   *fp;
8858 	char	   *varname,
8859 			   *varvalue,
8860 			   *varsourcefile;
8861 	int			varsourceline;
8862 	GucSource	varsource;
8863 	GucContext	varscontext;
8864 
8865 	/*
8866 	 * Assert that PGC_BACKEND/PGC_SU_BACKEND case in set_config_option() will
8867 	 * do the right thing.
8868 	 */
8869 	Assert(IsInitProcessingMode());
8870 
8871 	/*
8872 	 * Open file
8873 	 */
8874 	fp = AllocateFile(CONFIG_EXEC_PARAMS, "r");
8875 	if (!fp)
8876 	{
8877 		/* File not found is fine */
8878 		if (errno != ENOENT)
8879 			ereport(FATAL,
8880 					(errcode_for_file_access(),
8881 					 errmsg("could not read from file \"%s\": %m",
8882 							CONFIG_EXEC_PARAMS)));
8883 		return;
8884 	}
8885 
8886 	for (;;)
8887 	{
8888 		struct config_generic *record;
8889 
8890 		if ((varname = read_string_with_null(fp)) == NULL)
8891 			break;
8892 
8893 		if ((record = find_option(varname, true, FATAL)) == NULL)
8894 			elog(FATAL, "failed to locate variable \"%s\" in exec config params file", varname);
8895 
8896 		if ((varvalue = read_string_with_null(fp)) == NULL)
8897 			elog(FATAL, "invalid format of exec config params file");
8898 		if ((varsourcefile = read_string_with_null(fp)) == NULL)
8899 			elog(FATAL, "invalid format of exec config params file");
8900 		if (fread(&varsourceline, 1, sizeof(varsourceline), fp) != sizeof(varsourceline))
8901 			elog(FATAL, "invalid format of exec config params file");
8902 		if (fread(&varsource, 1, sizeof(varsource), fp) != sizeof(varsource))
8903 			elog(FATAL, "invalid format of exec config params file");
8904 		if (fread(&varscontext, 1, sizeof(varscontext), fp) != sizeof(varscontext))
8905 			elog(FATAL, "invalid format of exec config params file");
8906 
8907 		(void) set_config_option(varname, varvalue,
8908 								 varscontext, varsource,
8909 								 GUC_ACTION_SET, true, 0, true);
8910 		if (varsourcefile[0])
8911 			set_config_sourcefile(varname, varsourcefile, varsourceline);
8912 
8913 		free(varname);
8914 		free(varvalue);
8915 		free(varsourcefile);
8916 	}
8917 
8918 	FreeFile(fp);
8919 }
8920 #endif   /* EXEC_BACKEND */
8921 
8922 /*
8923  * can_skip_gucvar:
8924  * When serializing, determine whether to skip this GUC.  When restoring, the
8925  * negation of this test determines whether to restore the compiled-in default
8926  * value before processing serialized values.
8927  *
8928  * A PGC_S_DEFAULT setting on the serialize side will typically match new
8929  * postmaster children, but that can be false when got_SIGHUP == true and the
8930  * pending configuration change modifies this setting.  Nonetheless, we omit
8931  * PGC_S_DEFAULT settings from serialization and make up for that by restoring
8932  * defaults before applying serialized values.
8933  *
8934  * PGC_POSTMASTER variables always have the same value in every child of a
8935  * particular postmaster.  Most PGC_INTERNAL variables are compile-time
8936  * constants; a few, like server_encoding and lc_ctype, are handled specially
8937  * outside the serialize/restore procedure.  Therefore, SerializeGUCState()
8938  * never sends these, and RestoreGUCState() never changes them.
8939  *
8940  * Role is a special variable in the sense that its current value can be an
8941  * invalid value and there are multiple ways by which that can happen (like
8942  * after setting the role, someone drops it).  So we handle it outside of
8943  * serialize/restore machinery.
8944  */
8945 static bool
can_skip_gucvar(struct config_generic * gconf)8946 can_skip_gucvar(struct config_generic * gconf)
8947 {
8948 	return gconf->context == PGC_POSTMASTER ||
8949 		gconf->context == PGC_INTERNAL || gconf->source == PGC_S_DEFAULT ||
8950 		strcmp(gconf->name, "role") == 0;
8951 }
8952 
8953 /*
8954  * estimate_variable_size:
8955  *		Compute space needed for dumping the given GUC variable.
8956  *
8957  * It's OK to overestimate, but not to underestimate.
8958  */
8959 static Size
estimate_variable_size(struct config_generic * gconf)8960 estimate_variable_size(struct config_generic * gconf)
8961 {
8962 	Size		size;
8963 	Size		valsize = 0;
8964 
8965 	if (can_skip_gucvar(gconf))
8966 		return 0;
8967 
8968 	/* Name, plus trailing zero byte. */
8969 	size = strlen(gconf->name) + 1;
8970 
8971 	/* Get the maximum display length of the GUC value. */
8972 	switch (gconf->vartype)
8973 	{
8974 		case PGC_BOOL:
8975 			{
8976 				valsize = 5;	/* max(strlen('true'), strlen('false')) */
8977 			}
8978 			break;
8979 
8980 		case PGC_INT:
8981 			{
8982 				struct config_int *conf = (struct config_int *) gconf;
8983 
8984 				/*
8985 				 * Instead of getting the exact display length, use max
8986 				 * length.  Also reduce the max length for typical ranges of
8987 				 * small values.  Maximum value is 2147483647, i.e. 10 chars.
8988 				 * Include one byte for sign.
8989 				 */
8990 				if (Abs(*conf->variable) < 1000)
8991 					valsize = 3 + 1;
8992 				else
8993 					valsize = 10 + 1;
8994 			}
8995 			break;
8996 
8997 		case PGC_REAL:
8998 			{
8999 				/*
9000 				 * We are going to print it with %e with REALTYPE_PRECISION
9001 				 * fractional digits.  Account for sign, leading digit,
9002 				 * decimal point, and exponent with up to 3 digits.  E.g.
9003 				 * -3.99329042340000021e+110
9004 				 */
9005 				valsize = 1 + 1 + 1 + REALTYPE_PRECISION + 5;
9006 			}
9007 			break;
9008 
9009 		case PGC_STRING:
9010 			{
9011 				struct config_string *conf = (struct config_string *) gconf;
9012 
9013 				/*
9014 				 * If the value is NULL, we transmit it as an empty string.
9015 				 * Although this is not physically the same value, GUC
9016 				 * generally treats a NULL the same as empty string.
9017 				 */
9018 				if (*conf->variable)
9019 					valsize = strlen(*conf->variable);
9020 				else
9021 					valsize = 0;
9022 			}
9023 			break;
9024 
9025 		case PGC_ENUM:
9026 			{
9027 				struct config_enum *conf = (struct config_enum *) gconf;
9028 
9029 				valsize = strlen(config_enum_lookup_by_value(conf, *conf->variable));
9030 			}
9031 			break;
9032 	}
9033 
9034 	/* Allow space for terminating zero-byte for value */
9035 	size = add_size(size, valsize + 1);
9036 
9037 	if (gconf->sourcefile)
9038 		size = add_size(size, strlen(gconf->sourcefile));
9039 
9040 	/* Allow space for terminating zero-byte for sourcefile */
9041 	size = add_size(size, 1);
9042 
9043 	/* Include line whenever file is nonempty. */
9044 	if (gconf->sourcefile && gconf->sourcefile[0])
9045 		size = add_size(size, sizeof(gconf->sourceline));
9046 
9047 	size = add_size(size, sizeof(gconf->source));
9048 	size = add_size(size, sizeof(gconf->scontext));
9049 
9050 	return size;
9051 }
9052 
9053 /*
9054  * EstimateGUCStateSpace:
9055  * Returns the size needed to store the GUC state for the current process
9056  */
9057 Size
EstimateGUCStateSpace(void)9058 EstimateGUCStateSpace(void)
9059 {
9060 	Size		size;
9061 	int			i;
9062 
9063 	/* Add space reqd for saving the data size of the guc state */
9064 	size = sizeof(Size);
9065 
9066 	/* Add up the space needed for each GUC variable */
9067 	for (i = 0; i < num_guc_variables; i++)
9068 		size = add_size(size,
9069 						estimate_variable_size(guc_variables[i]));
9070 
9071 	return size;
9072 }
9073 
9074 /*
9075  * do_serialize:
9076  * Copies the formatted string into the destination.  Moves ahead the
9077  * destination pointer, and decrements the maxbytes by that many bytes. If
9078  * maxbytes is not sufficient to copy the string, error out.
9079  */
9080 static void
do_serialize(char ** destptr,Size * maxbytes,const char * fmt,...)9081 do_serialize(char **destptr, Size *maxbytes, const char *fmt,...)
9082 {
9083 	va_list		vargs;
9084 	int			n;
9085 
9086 	if (*maxbytes <= 0)
9087 		elog(ERROR, "not enough space to serialize GUC state");
9088 
9089 	errno = 0;
9090 
9091 	va_start(vargs, fmt);
9092 	n = vsnprintf(*destptr, *maxbytes, fmt, vargs);
9093 	va_end(vargs);
9094 
9095 	/*
9096 	 * Cater to portability hazards in the vsnprintf() return value just like
9097 	 * appendPQExpBufferVA() does.  Note that this requires an extra byte of
9098 	 * slack at the end of the buffer.  Since serialize_variable() ends with a
9099 	 * do_serialize_binary() rather than a do_serialize(), we'll always have
9100 	 * that slack; estimate_variable_size() need not add a byte for it.
9101 	 */
9102 	if (n < 0 || n >= *maxbytes - 1)
9103 	{
9104 		if (n < 0 && errno != 0 && errno != ENOMEM)
9105 			/* Shouldn't happen. Better show errno description. */
9106 			elog(ERROR, "vsnprintf failed: %m");
9107 		else
9108 			elog(ERROR, "not enough space to serialize GUC state");
9109 	}
9110 
9111 	/* Shift the destptr ahead of the null terminator */
9112 	*destptr += n + 1;
9113 	*maxbytes -= n + 1;
9114 }
9115 
9116 /* Binary copy version of do_serialize() */
9117 static void
do_serialize_binary(char ** destptr,Size * maxbytes,void * val,Size valsize)9118 do_serialize_binary(char **destptr, Size *maxbytes, void *val, Size valsize)
9119 {
9120 	if (valsize > *maxbytes)
9121 		elog(ERROR, "not enough space to serialize GUC state");
9122 
9123 	memcpy(*destptr, val, valsize);
9124 	*destptr += valsize;
9125 	*maxbytes -= valsize;
9126 }
9127 
9128 /*
9129  * serialize_variable:
9130  * Dumps name, value and other information of a GUC variable into destptr.
9131  */
9132 static void
serialize_variable(char ** destptr,Size * maxbytes,struct config_generic * gconf)9133 serialize_variable(char **destptr, Size *maxbytes,
9134 				   struct config_generic * gconf)
9135 {
9136 	if (can_skip_gucvar(gconf))
9137 		return;
9138 
9139 	do_serialize(destptr, maxbytes, "%s", gconf->name);
9140 
9141 	switch (gconf->vartype)
9142 	{
9143 		case PGC_BOOL:
9144 			{
9145 				struct config_bool *conf = (struct config_bool *) gconf;
9146 
9147 				do_serialize(destptr, maxbytes,
9148 							 (*conf->variable ? "true" : "false"));
9149 			}
9150 			break;
9151 
9152 		case PGC_INT:
9153 			{
9154 				struct config_int *conf = (struct config_int *) gconf;
9155 
9156 				do_serialize(destptr, maxbytes, "%d", *conf->variable);
9157 			}
9158 			break;
9159 
9160 		case PGC_REAL:
9161 			{
9162 				struct config_real *conf = (struct config_real *) gconf;
9163 
9164 				do_serialize(destptr, maxbytes, "%.*e",
9165 							 REALTYPE_PRECISION, *conf->variable);
9166 			}
9167 			break;
9168 
9169 		case PGC_STRING:
9170 			{
9171 				struct config_string *conf = (struct config_string *) gconf;
9172 
9173 				/* NULL becomes empty string, see estimate_variable_size() */
9174 				do_serialize(destptr, maxbytes, "%s",
9175 							 *conf->variable ? *conf->variable : "");
9176 			}
9177 			break;
9178 
9179 		case PGC_ENUM:
9180 			{
9181 				struct config_enum *conf = (struct config_enum *) gconf;
9182 
9183 				do_serialize(destptr, maxbytes, "%s",
9184 						 config_enum_lookup_by_value(conf, *conf->variable));
9185 			}
9186 			break;
9187 	}
9188 
9189 	do_serialize(destptr, maxbytes, "%s",
9190 				 (gconf->sourcefile ? gconf->sourcefile : ""));
9191 
9192 	if (gconf->sourcefile && gconf->sourcefile[0])
9193 		do_serialize_binary(destptr, maxbytes, &gconf->sourceline,
9194 							sizeof(gconf->sourceline));
9195 
9196 	do_serialize_binary(destptr, maxbytes, &gconf->source,
9197 						sizeof(gconf->source));
9198 	do_serialize_binary(destptr, maxbytes, &gconf->scontext,
9199 						sizeof(gconf->scontext));
9200 }
9201 
9202 /*
9203  * SerializeGUCState:
9204  * Dumps the complete GUC state onto the memory location at start_address.
9205  */
9206 void
SerializeGUCState(Size maxsize,char * start_address)9207 SerializeGUCState(Size maxsize, char *start_address)
9208 {
9209 	char	   *curptr;
9210 	Size		actual_size;
9211 	Size		bytes_left;
9212 	int			i;
9213 
9214 	/* Reserve space for saving the actual size of the guc state */
9215 	Assert(maxsize > sizeof(actual_size));
9216 	curptr = start_address + sizeof(actual_size);
9217 	bytes_left = maxsize - sizeof(actual_size);
9218 
9219 	for (i = 0; i < num_guc_variables; i++)
9220 		serialize_variable(&curptr, &bytes_left, guc_variables[i]);
9221 
9222 	/* Store actual size without assuming alignment of start_address. */
9223 	actual_size = maxsize - bytes_left - sizeof(actual_size);
9224 	memcpy(start_address, &actual_size, sizeof(actual_size));
9225 }
9226 
9227 /*
9228  * read_gucstate:
9229  * Actually it does not read anything, just returns the srcptr. But it does
9230  * move the srcptr past the terminating zero byte, so that the caller is ready
9231  * to read the next string.
9232  */
9233 static char *
read_gucstate(char ** srcptr,char * srcend)9234 read_gucstate(char **srcptr, char *srcend)
9235 {
9236 	char	   *retptr = *srcptr;
9237 	char	   *ptr;
9238 
9239 	if (*srcptr >= srcend)
9240 		elog(ERROR, "incomplete GUC state");
9241 
9242 	/* The string variables are all null terminated */
9243 	for (ptr = *srcptr; ptr < srcend && *ptr != '\0'; ptr++)
9244 		;
9245 
9246 	if (ptr >= srcend)
9247 		elog(ERROR, "could not find null terminator in GUC state");
9248 
9249 	/* Set the new position to the byte following the terminating NUL */
9250 	*srcptr = ptr + 1;
9251 
9252 	return retptr;
9253 }
9254 
9255 /* Binary read version of read_gucstate(). Copies into dest */
9256 static void
read_gucstate_binary(char ** srcptr,char * srcend,void * dest,Size size)9257 read_gucstate_binary(char **srcptr, char *srcend, void *dest, Size size)
9258 {
9259 	if (*srcptr + size > srcend)
9260 		elog(ERROR, "incomplete GUC state");
9261 
9262 	memcpy(dest, *srcptr, size);
9263 	*srcptr += size;
9264 }
9265 
9266 /*
9267  * Callback used to add a context message when reporting errors that occur
9268  * while trying to restore GUCs in parallel workers.
9269  */
9270 static void
guc_restore_error_context_callback(void * arg)9271 guc_restore_error_context_callback(void *arg)
9272 {
9273 	char	  **error_context_name_and_value = (char **) arg;
9274 
9275 	if (error_context_name_and_value)
9276 		errcontext("while setting parameter \"%s\" to \"%s\"",
9277 				   error_context_name_and_value[0],
9278 				   error_context_name_and_value[1]);
9279 }
9280 
9281 /*
9282  * RestoreGUCState:
9283  * Reads the GUC state at the specified address and updates the GUCs with the
9284  * values read from the GUC state.
9285  */
9286 void
RestoreGUCState(void * gucstate)9287 RestoreGUCState(void *gucstate)
9288 {
9289 	char	   *varname,
9290 			   *varvalue,
9291 			   *varsourcefile;
9292 	int			varsourceline;
9293 	GucSource	varsource;
9294 	GucContext	varscontext;
9295 	char	   *srcptr = (char *) gucstate;
9296 	char	   *srcend;
9297 	Size		len;
9298 	int			i;
9299 	ErrorContextCallback error_context_callback;
9300 
9301 	/* See comment at can_skip_gucvar(). */
9302 	for (i = 0; i < num_guc_variables; i++)
9303 		if (!can_skip_gucvar(guc_variables[i]))
9304 			InitializeOneGUCOption(guc_variables[i]);
9305 
9306 	/* First item is the length of the subsequent data */
9307 	memcpy(&len, gucstate, sizeof(len));
9308 
9309 	srcptr += sizeof(len);
9310 	srcend = srcptr + len;
9311 
9312 	/* If the GUC value check fails, we want errors to show useful context. */
9313 	error_context_callback.callback = guc_restore_error_context_callback;
9314 	error_context_callback.previous = error_context_stack;
9315 	error_context_callback.arg = NULL;
9316 	error_context_stack = &error_context_callback;
9317 
9318 	while (srcptr < srcend)
9319 	{
9320 		int			result;
9321 		char	   *error_context_name_and_value[2];
9322 
9323 		varname = read_gucstate(&srcptr, srcend);
9324 		varvalue = read_gucstate(&srcptr, srcend);
9325 		varsourcefile = read_gucstate(&srcptr, srcend);
9326 		if (varsourcefile[0])
9327 			read_gucstate_binary(&srcptr, srcend,
9328 								 &varsourceline, sizeof(varsourceline));
9329 		else
9330 			varsourceline = 0;
9331 		read_gucstate_binary(&srcptr, srcend,
9332 							 &varsource, sizeof(varsource));
9333 		read_gucstate_binary(&srcptr, srcend,
9334 							 &varscontext, sizeof(varscontext));
9335 
9336 		error_context_name_and_value[0] = varname;
9337 		error_context_name_and_value[1] = varvalue;
9338 		error_context_callback.arg = &error_context_name_and_value[0];
9339 		result = set_config_option(varname, varvalue, varscontext, varsource,
9340 								   GUC_ACTION_SET, true, ERROR, true);
9341 		if (result <= 0)
9342 			ereport(ERROR,
9343 					(errcode(ERRCODE_INTERNAL_ERROR),
9344 					 errmsg("parameter \"%s\" could not be set", varname)));
9345 		if (varsourcefile[0])
9346 			set_config_sourcefile(varname, varsourcefile, varsourceline);
9347 		error_context_callback.arg = NULL;
9348 	}
9349 
9350 	error_context_stack = error_context_callback.previous;
9351 }
9352 
9353 /*
9354  * A little "long argument" simulation, although not quite GNU
9355  * compliant. Takes a string of the form "some-option=some value" and
9356  * returns name = "some_option" and value = "some value" in malloc'ed
9357  * storage. Note that '-' is converted to '_' in the option name. If
9358  * there is no '=' in the input string then value will be NULL.
9359  */
9360 void
ParseLongOption(const char * string,char ** name,char ** value)9361 ParseLongOption(const char *string, char **name, char **value)
9362 {
9363 	size_t		equal_pos;
9364 	char	   *cp;
9365 
9366 	AssertArg(string);
9367 	AssertArg(name);
9368 	AssertArg(value);
9369 
9370 	equal_pos = strcspn(string, "=");
9371 
9372 	if (string[equal_pos] == '=')
9373 	{
9374 		*name = guc_malloc(FATAL, equal_pos + 1);
9375 		strlcpy(*name, string, equal_pos + 1);
9376 
9377 		*value = guc_strdup(FATAL, &string[equal_pos + 1]);
9378 	}
9379 	else
9380 	{
9381 		/* no equal sign in string */
9382 		*name = guc_strdup(FATAL, string);
9383 		*value = NULL;
9384 	}
9385 
9386 	for (cp = *name; *cp; cp++)
9387 		if (*cp == '-')
9388 			*cp = '_';
9389 }
9390 
9391 
9392 /*
9393  * Handle options fetched from pg_db_role_setting.setconfig,
9394  * pg_proc.proconfig, etc.  Caller must specify proper context/source/action.
9395  *
9396  * The array parameter must be an array of TEXT (it must not be NULL).
9397  */
9398 void
ProcessGUCArray(ArrayType * array,GucContext context,GucSource source,GucAction action)9399 ProcessGUCArray(ArrayType *array,
9400 				GucContext context, GucSource source, GucAction action)
9401 {
9402 	int			i;
9403 
9404 	Assert(array != NULL);
9405 	Assert(ARR_ELEMTYPE(array) == TEXTOID);
9406 	Assert(ARR_NDIM(array) == 1);
9407 	Assert(ARR_LBOUND(array)[0] == 1);
9408 
9409 	for (i = 1; i <= ARR_DIMS(array)[0]; i++)
9410 	{
9411 		Datum		d;
9412 		bool		isnull;
9413 		char	   *s;
9414 		char	   *name;
9415 		char	   *value;
9416 		char	   *namecopy;
9417 		char	   *valuecopy;
9418 
9419 		d = array_ref(array, 1, &i,
9420 					  -1 /* varlenarray */ ,
9421 					  -1 /* TEXT's typlen */ ,
9422 					  false /* TEXT's typbyval */ ,
9423 					  'i' /* TEXT's typalign */ ,
9424 					  &isnull);
9425 
9426 		if (isnull)
9427 			continue;
9428 
9429 		s = TextDatumGetCString(d);
9430 
9431 		ParseLongOption(s, &name, &value);
9432 		if (!value)
9433 		{
9434 			ereport(WARNING,
9435 					(errcode(ERRCODE_SYNTAX_ERROR),
9436 					 errmsg("could not parse setting for parameter \"%s\"",
9437 							name)));
9438 			free(name);
9439 			continue;
9440 		}
9441 
9442 		/* free malloc'd strings immediately to avoid leak upon error */
9443 		namecopy = pstrdup(name);
9444 		free(name);
9445 		valuecopy = pstrdup(value);
9446 		free(value);
9447 
9448 		(void) set_config_option(namecopy, valuecopy,
9449 								 context, source,
9450 								 action, true, 0, false);
9451 
9452 		pfree(namecopy);
9453 		pfree(valuecopy);
9454 		pfree(s);
9455 	}
9456 }
9457 
9458 
9459 /*
9460  * Add an entry to an option array.  The array parameter may be NULL
9461  * to indicate the current table entry is NULL.
9462  */
9463 ArrayType *
GUCArrayAdd(ArrayType * array,const char * name,const char * value)9464 GUCArrayAdd(ArrayType *array, const char *name, const char *value)
9465 {
9466 	struct config_generic *record;
9467 	Datum		datum;
9468 	char	   *newval;
9469 	ArrayType  *a;
9470 
9471 	Assert(name);
9472 	Assert(value);
9473 
9474 	/* test if the option is valid and we're allowed to set it */
9475 	(void) validate_option_array_item(name, value, false);
9476 
9477 	/* normalize name (converts obsolete GUC names to modern spellings) */
9478 	record = find_option(name, false, WARNING);
9479 	if (record)
9480 		name = record->name;
9481 
9482 	/* build new item for array */
9483 	newval = psprintf("%s=%s", name, value);
9484 	datum = CStringGetTextDatum(newval);
9485 
9486 	if (array)
9487 	{
9488 		int			index;
9489 		bool		isnull;
9490 		int			i;
9491 
9492 		Assert(ARR_ELEMTYPE(array) == TEXTOID);
9493 		Assert(ARR_NDIM(array) == 1);
9494 		Assert(ARR_LBOUND(array)[0] == 1);
9495 
9496 		index = ARR_DIMS(array)[0] + 1; /* add after end */
9497 
9498 		for (i = 1; i <= ARR_DIMS(array)[0]; i++)
9499 		{
9500 			Datum		d;
9501 			char	   *current;
9502 
9503 			d = array_ref(array, 1, &i,
9504 						  -1 /* varlenarray */ ,
9505 						  -1 /* TEXT's typlen */ ,
9506 						  false /* TEXT's typbyval */ ,
9507 						  'i' /* TEXT's typalign */ ,
9508 						  &isnull);
9509 			if (isnull)
9510 				continue;
9511 			current = TextDatumGetCString(d);
9512 
9513 			/* check for match up through and including '=' */
9514 			if (strncmp(current, newval, strlen(name) + 1) == 0)
9515 			{
9516 				index = i;
9517 				break;
9518 			}
9519 		}
9520 
9521 		a = array_set(array, 1, &index,
9522 					  datum,
9523 					  false,
9524 					  -1 /* varlena array */ ,
9525 					  -1 /* TEXT's typlen */ ,
9526 					  false /* TEXT's typbyval */ ,
9527 					  'i' /* TEXT's typalign */ );
9528 	}
9529 	else
9530 		a = construct_array(&datum, 1,
9531 							TEXTOID,
9532 							-1, false, 'i');
9533 
9534 	return a;
9535 }
9536 
9537 
9538 /*
9539  * Delete an entry from an option array.  The array parameter may be NULL
9540  * to indicate the current table entry is NULL.  Also, if the return value
9541  * is NULL then a null should be stored.
9542  */
9543 ArrayType *
GUCArrayDelete(ArrayType * array,const char * name)9544 GUCArrayDelete(ArrayType *array, const char *name)
9545 {
9546 	struct config_generic *record;
9547 	ArrayType  *newarray;
9548 	int			i;
9549 	int			index;
9550 
9551 	Assert(name);
9552 
9553 	/* test if the option is valid and we're allowed to set it */
9554 	(void) validate_option_array_item(name, NULL, false);
9555 
9556 	/* normalize name (converts obsolete GUC names to modern spellings) */
9557 	record = find_option(name, false, WARNING);
9558 	if (record)
9559 		name = record->name;
9560 
9561 	/* if array is currently null, then surely nothing to delete */
9562 	if (!array)
9563 		return NULL;
9564 
9565 	newarray = NULL;
9566 	index = 1;
9567 
9568 	for (i = 1; i <= ARR_DIMS(array)[0]; i++)
9569 	{
9570 		Datum		d;
9571 		char	   *val;
9572 		bool		isnull;
9573 
9574 		d = array_ref(array, 1, &i,
9575 					  -1 /* varlenarray */ ,
9576 					  -1 /* TEXT's typlen */ ,
9577 					  false /* TEXT's typbyval */ ,
9578 					  'i' /* TEXT's typalign */ ,
9579 					  &isnull);
9580 		if (isnull)
9581 			continue;
9582 		val = TextDatumGetCString(d);
9583 
9584 		/* ignore entry if it's what we want to delete */
9585 		if (strncmp(val, name, strlen(name)) == 0
9586 			&& val[strlen(name)] == '=')
9587 			continue;
9588 
9589 		/* else add it to the output array */
9590 		if (newarray)
9591 			newarray = array_set(newarray, 1, &index,
9592 								 d,
9593 								 false,
9594 								 -1 /* varlenarray */ ,
9595 								 -1 /* TEXT's typlen */ ,
9596 								 false /* TEXT's typbyval */ ,
9597 								 'i' /* TEXT's typalign */ );
9598 		else
9599 			newarray = construct_array(&d, 1,
9600 									   TEXTOID,
9601 									   -1, false, 'i');
9602 
9603 		index++;
9604 	}
9605 
9606 	return newarray;
9607 }
9608 
9609 
9610 /*
9611  * Given a GUC array, delete all settings from it that our permission
9612  * level allows: if superuser, delete them all; if regular user, only
9613  * those that are PGC_USERSET
9614  */
9615 ArrayType *
GUCArrayReset(ArrayType * array)9616 GUCArrayReset(ArrayType *array)
9617 {
9618 	ArrayType  *newarray;
9619 	int			i;
9620 	int			index;
9621 
9622 	/* if array is currently null, nothing to do */
9623 	if (!array)
9624 		return NULL;
9625 
9626 	/* if we're superuser, we can delete everything, so just do it */
9627 	if (superuser())
9628 		return NULL;
9629 
9630 	newarray = NULL;
9631 	index = 1;
9632 
9633 	for (i = 1; i <= ARR_DIMS(array)[0]; i++)
9634 	{
9635 		Datum		d;
9636 		char	   *val;
9637 		char	   *eqsgn;
9638 		bool		isnull;
9639 
9640 		d = array_ref(array, 1, &i,
9641 					  -1 /* varlenarray */ ,
9642 					  -1 /* TEXT's typlen */ ,
9643 					  false /* TEXT's typbyval */ ,
9644 					  'i' /* TEXT's typalign */ ,
9645 					  &isnull);
9646 		if (isnull)
9647 			continue;
9648 		val = TextDatumGetCString(d);
9649 
9650 		eqsgn = strchr(val, '=');
9651 		*eqsgn = '\0';
9652 
9653 		/* skip if we have permission to delete it */
9654 		if (validate_option_array_item(val, NULL, true))
9655 			continue;
9656 
9657 		/* else add it to the output array */
9658 		if (newarray)
9659 			newarray = array_set(newarray, 1, &index,
9660 								 d,
9661 								 false,
9662 								 -1 /* varlenarray */ ,
9663 								 -1 /* TEXT's typlen */ ,
9664 								 false /* TEXT's typbyval */ ,
9665 								 'i' /* TEXT's typalign */ );
9666 		else
9667 			newarray = construct_array(&d, 1,
9668 									   TEXTOID,
9669 									   -1, false, 'i');
9670 
9671 		index++;
9672 		pfree(val);
9673 	}
9674 
9675 	return newarray;
9676 }
9677 
9678 /*
9679  * Validate a proposed option setting for GUCArrayAdd/Delete/Reset.
9680  *
9681  * name is the option name.  value is the proposed value for the Add case,
9682  * or NULL for the Delete/Reset cases.  If skipIfNoPermissions is true, it's
9683  * not an error to have no permissions to set the option.
9684  *
9685  * Returns TRUE if OK, FALSE if skipIfNoPermissions is true and user does not
9686  * have permission to change this option (all other error cases result in an
9687  * error being thrown).
9688  */
9689 static bool
validate_option_array_item(const char * name,const char * value,bool skipIfNoPermissions)9690 validate_option_array_item(const char *name, const char *value,
9691 						   bool skipIfNoPermissions)
9692 
9693 {
9694 	struct config_generic *gconf;
9695 
9696 	/*
9697 	 * There are three cases to consider:
9698 	 *
9699 	 * name is a known GUC variable.  Check the value normally, check
9700 	 * permissions normally (i.e., allow if variable is USERSET, or if it's
9701 	 * SUSET and user is superuser).
9702 	 *
9703 	 * name is not known, but exists or can be created as a placeholder (i.e.,
9704 	 * it has a prefixed name).  We allow this case if you're a superuser,
9705 	 * otherwise not.  Superusers are assumed to know what they're doing. We
9706 	 * can't allow it for other users, because when the placeholder is
9707 	 * resolved it might turn out to be a SUSET variable;
9708 	 * define_custom_variable assumes we checked that.
9709 	 *
9710 	 * name is not known and can't be created as a placeholder.  Throw error,
9711 	 * unless skipIfNoPermissions is true, in which case return FALSE.
9712 	 */
9713 	gconf = find_option(name, true, WARNING);
9714 	if (!gconf)
9715 	{
9716 		/* not known, failed to make a placeholder */
9717 		if (skipIfNoPermissions)
9718 			return false;
9719 		ereport(ERROR,
9720 				(errcode(ERRCODE_UNDEFINED_OBJECT),
9721 				 errmsg("unrecognized configuration parameter \"%s\"",
9722 						name)));
9723 	}
9724 
9725 	if (gconf->flags & GUC_CUSTOM_PLACEHOLDER)
9726 	{
9727 		/*
9728 		 * We cannot do any meaningful check on the value, so only permissions
9729 		 * are useful to check.
9730 		 */
9731 		if (superuser())
9732 			return true;
9733 		if (skipIfNoPermissions)
9734 			return false;
9735 		ereport(ERROR,
9736 				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
9737 				 errmsg("permission denied to set parameter \"%s\"", name)));
9738 	}
9739 
9740 	/* manual permissions check so we can avoid an error being thrown */
9741 	if (gconf->context == PGC_USERSET)
9742 		 /* ok */ ;
9743 	else if (gconf->context == PGC_SUSET && superuser())
9744 		 /* ok */ ;
9745 	else if (skipIfNoPermissions)
9746 		return false;
9747 	/* if a permissions error should be thrown, let set_config_option do it */
9748 
9749 	/* test for permissions and valid option value */
9750 	(void) set_config_option(name, value,
9751 							 superuser() ? PGC_SUSET : PGC_USERSET,
9752 							 PGC_S_TEST, GUC_ACTION_SET, false, 0, false);
9753 
9754 	return true;
9755 }
9756 
9757 
9758 /*
9759  * Called by check_hooks that want to override the normal
9760  * ERRCODE_INVALID_PARAMETER_VALUE SQLSTATE for check hook failures.
9761  *
9762  * Note that GUC_check_errmsg() etc are just macros that result in a direct
9763  * assignment to the associated variables.  That is ugly, but forced by the
9764  * limitations of C's macro mechanisms.
9765  */
9766 void
GUC_check_errcode(int sqlerrcode)9767 GUC_check_errcode(int sqlerrcode)
9768 {
9769 	GUC_check_errcode_value = sqlerrcode;
9770 }
9771 
9772 
9773 /*
9774  * Convenience functions to manage calling a variable's check_hook.
9775  * These mostly take care of the protocol for letting check hooks supply
9776  * portions of the error report on failure.
9777  */
9778 
9779 static bool
call_bool_check_hook(struct config_bool * conf,bool * newval,void ** extra,GucSource source,int elevel)9780 call_bool_check_hook(struct config_bool * conf, bool *newval, void **extra,
9781 					 GucSource source, int elevel)
9782 {
9783 	/* Quick success if no hook */
9784 	if (!conf->check_hook)
9785 		return true;
9786 
9787 	/* Reset variables that might be set by hook */
9788 	GUC_check_errcode_value = ERRCODE_INVALID_PARAMETER_VALUE;
9789 	GUC_check_errmsg_string = NULL;
9790 	GUC_check_errdetail_string = NULL;
9791 	GUC_check_errhint_string = NULL;
9792 
9793 	if (!(*conf->check_hook) (newval, extra, source))
9794 	{
9795 		ereport(elevel,
9796 				(errcode(GUC_check_errcode_value),
9797 				 GUC_check_errmsg_string ?
9798 				 errmsg_internal("%s", GUC_check_errmsg_string) :
9799 				 errmsg("invalid value for parameter \"%s\": %d",
9800 						conf->gen.name, (int) *newval),
9801 				 GUC_check_errdetail_string ?
9802 				 errdetail_internal("%s", GUC_check_errdetail_string) : 0,
9803 				 GUC_check_errhint_string ?
9804 				 errhint("%s", GUC_check_errhint_string) : 0));
9805 		/* Flush any strings created in ErrorContext */
9806 		FlushErrorState();
9807 		return false;
9808 	}
9809 
9810 	return true;
9811 }
9812 
9813 static bool
call_int_check_hook(struct config_int * conf,int * newval,void ** extra,GucSource source,int elevel)9814 call_int_check_hook(struct config_int * conf, int *newval, void **extra,
9815 					GucSource source, int elevel)
9816 {
9817 	/* Quick success if no hook */
9818 	if (!conf->check_hook)
9819 		return true;
9820 
9821 	/* Reset variables that might be set by hook */
9822 	GUC_check_errcode_value = ERRCODE_INVALID_PARAMETER_VALUE;
9823 	GUC_check_errmsg_string = NULL;
9824 	GUC_check_errdetail_string = NULL;
9825 	GUC_check_errhint_string = NULL;
9826 
9827 	if (!(*conf->check_hook) (newval, extra, source))
9828 	{
9829 		ereport(elevel,
9830 				(errcode(GUC_check_errcode_value),
9831 				 GUC_check_errmsg_string ?
9832 				 errmsg_internal("%s", GUC_check_errmsg_string) :
9833 				 errmsg("invalid value for parameter \"%s\": %d",
9834 						conf->gen.name, *newval),
9835 				 GUC_check_errdetail_string ?
9836 				 errdetail_internal("%s", GUC_check_errdetail_string) : 0,
9837 				 GUC_check_errhint_string ?
9838 				 errhint("%s", GUC_check_errhint_string) : 0));
9839 		/* Flush any strings created in ErrorContext */
9840 		FlushErrorState();
9841 		return false;
9842 	}
9843 
9844 	return true;
9845 }
9846 
9847 static bool
call_real_check_hook(struct config_real * conf,double * newval,void ** extra,GucSource source,int elevel)9848 call_real_check_hook(struct config_real * conf, double *newval, void **extra,
9849 					 GucSource source, int elevel)
9850 {
9851 	/* Quick success if no hook */
9852 	if (!conf->check_hook)
9853 		return true;
9854 
9855 	/* Reset variables that might be set by hook */
9856 	GUC_check_errcode_value = ERRCODE_INVALID_PARAMETER_VALUE;
9857 	GUC_check_errmsg_string = NULL;
9858 	GUC_check_errdetail_string = NULL;
9859 	GUC_check_errhint_string = NULL;
9860 
9861 	if (!(*conf->check_hook) (newval, extra, source))
9862 	{
9863 		ereport(elevel,
9864 				(errcode(GUC_check_errcode_value),
9865 				 GUC_check_errmsg_string ?
9866 				 errmsg_internal("%s", GUC_check_errmsg_string) :
9867 				 errmsg("invalid value for parameter \"%s\": %g",
9868 						conf->gen.name, *newval),
9869 				 GUC_check_errdetail_string ?
9870 				 errdetail_internal("%s", GUC_check_errdetail_string) : 0,
9871 				 GUC_check_errhint_string ?
9872 				 errhint("%s", GUC_check_errhint_string) : 0));
9873 		/* Flush any strings created in ErrorContext */
9874 		FlushErrorState();
9875 		return false;
9876 	}
9877 
9878 	return true;
9879 }
9880 
9881 static bool
call_string_check_hook(struct config_string * conf,char ** newval,void ** extra,GucSource source,int elevel)9882 call_string_check_hook(struct config_string * conf, char **newval, void **extra,
9883 					   GucSource source, int elevel)
9884 {
9885 	volatile bool result = true;
9886 
9887 	/* Quick success if no hook */
9888 	if (!conf->check_hook)
9889 		return true;
9890 
9891 	/*
9892 	 * If elevel is ERROR, or if the check_hook itself throws an elog
9893 	 * (undesirable, but not always avoidable), make sure we don't leak the
9894 	 * already-malloc'd newval string.
9895 	 */
9896 	PG_TRY();
9897 	{
9898 		/* Reset variables that might be set by hook */
9899 		GUC_check_errcode_value = ERRCODE_INVALID_PARAMETER_VALUE;
9900 		GUC_check_errmsg_string = NULL;
9901 		GUC_check_errdetail_string = NULL;
9902 		GUC_check_errhint_string = NULL;
9903 
9904 		if (!(*conf->check_hook) (newval, extra, source))
9905 		{
9906 			ereport(elevel,
9907 					(errcode(GUC_check_errcode_value),
9908 					 GUC_check_errmsg_string ?
9909 					 errmsg_internal("%s", GUC_check_errmsg_string) :
9910 					 errmsg("invalid value for parameter \"%s\": \"%s\"",
9911 							conf->gen.name, *newval ? *newval : ""),
9912 					 GUC_check_errdetail_string ?
9913 					 errdetail_internal("%s", GUC_check_errdetail_string) : 0,
9914 					 GUC_check_errhint_string ?
9915 					 errhint("%s", GUC_check_errhint_string) : 0));
9916 			/* Flush any strings created in ErrorContext */
9917 			FlushErrorState();
9918 			result = false;
9919 		}
9920 	}
9921 	PG_CATCH();
9922 	{
9923 		free(*newval);
9924 		PG_RE_THROW();
9925 	}
9926 	PG_END_TRY();
9927 
9928 	return result;
9929 }
9930 
9931 static bool
call_enum_check_hook(struct config_enum * conf,int * newval,void ** extra,GucSource source,int elevel)9932 call_enum_check_hook(struct config_enum * conf, int *newval, void **extra,
9933 					 GucSource source, int elevel)
9934 {
9935 	/* Quick success if no hook */
9936 	if (!conf->check_hook)
9937 		return true;
9938 
9939 	/* Reset variables that might be set by hook */
9940 	GUC_check_errcode_value = ERRCODE_INVALID_PARAMETER_VALUE;
9941 	GUC_check_errmsg_string = NULL;
9942 	GUC_check_errdetail_string = NULL;
9943 	GUC_check_errhint_string = NULL;
9944 
9945 	if (!(*conf->check_hook) (newval, extra, source))
9946 	{
9947 		ereport(elevel,
9948 				(errcode(GUC_check_errcode_value),
9949 				 GUC_check_errmsg_string ?
9950 				 errmsg_internal("%s", GUC_check_errmsg_string) :
9951 				 errmsg("invalid value for parameter \"%s\": \"%s\"",
9952 						conf->gen.name,
9953 						config_enum_lookup_by_value(conf, *newval)),
9954 				 GUC_check_errdetail_string ?
9955 				 errdetail_internal("%s", GUC_check_errdetail_string) : 0,
9956 				 GUC_check_errhint_string ?
9957 				 errhint("%s", GUC_check_errhint_string) : 0));
9958 		/* Flush any strings created in ErrorContext */
9959 		FlushErrorState();
9960 		return false;
9961 	}
9962 
9963 	return true;
9964 }
9965 
9966 
9967 /*
9968  * check_hook, assign_hook and show_hook subroutines
9969  */
9970 
9971 static bool
check_log_destination(char ** newval,void ** extra,GucSource source)9972 check_log_destination(char **newval, void **extra, GucSource source)
9973 {
9974 	char	   *rawstring;
9975 	List	   *elemlist;
9976 	ListCell   *l;
9977 	int			newlogdest = 0;
9978 	int		   *myextra;
9979 
9980 	/* Need a modifiable copy of string */
9981 	rawstring = pstrdup(*newval);
9982 
9983 	/* Parse string into list of identifiers */
9984 	if (!SplitIdentifierString(rawstring, ',', &elemlist))
9985 	{
9986 		/* syntax error in list */
9987 		GUC_check_errdetail("List syntax is invalid.");
9988 		pfree(rawstring);
9989 		list_free(elemlist);
9990 		return false;
9991 	}
9992 
9993 	foreach(l, elemlist)
9994 	{
9995 		char	   *tok = (char *) lfirst(l);
9996 
9997 		if (pg_strcasecmp(tok, "stderr") == 0)
9998 			newlogdest |= LOG_DESTINATION_STDERR;
9999 		else if (pg_strcasecmp(tok, "csvlog") == 0)
10000 			newlogdest |= LOG_DESTINATION_CSVLOG;
10001 #ifdef HAVE_SYSLOG
10002 		else if (pg_strcasecmp(tok, "syslog") == 0)
10003 			newlogdest |= LOG_DESTINATION_SYSLOG;
10004 #endif
10005 #ifdef WIN32
10006 		else if (pg_strcasecmp(tok, "eventlog") == 0)
10007 			newlogdest |= LOG_DESTINATION_EVENTLOG;
10008 #endif
10009 		else
10010 		{
10011 			GUC_check_errdetail("Unrecognized key word: \"%s\".", tok);
10012 			pfree(rawstring);
10013 			list_free(elemlist);
10014 			return false;
10015 		}
10016 	}
10017 
10018 	pfree(rawstring);
10019 	list_free(elemlist);
10020 
10021 	myextra = (int *) guc_malloc(ERROR, sizeof(int));
10022 	*myextra = newlogdest;
10023 	*extra = (void *) myextra;
10024 
10025 	return true;
10026 }
10027 
10028 static void
assign_log_destination(const char * newval,void * extra)10029 assign_log_destination(const char *newval, void *extra)
10030 {
10031 	Log_destination = *((int *) extra);
10032 }
10033 
10034 static void
assign_syslog_facility(int newval,void * extra)10035 assign_syslog_facility(int newval, void *extra)
10036 {
10037 #ifdef HAVE_SYSLOG
10038 	set_syslog_parameters(syslog_ident_str ? syslog_ident_str : "postgres",
10039 						  newval);
10040 #endif
10041 	/* Without syslog support, just ignore it */
10042 }
10043 
10044 static void
assign_syslog_ident(const char * newval,void * extra)10045 assign_syslog_ident(const char *newval, void *extra)
10046 {
10047 #ifdef HAVE_SYSLOG
10048 	set_syslog_parameters(newval, syslog_facility);
10049 #endif
10050 	/* Without syslog support, it will always be set to "none", so ignore */
10051 }
10052 
10053 
10054 static void
assign_session_replication_role(int newval,void * extra)10055 assign_session_replication_role(int newval, void *extra)
10056 {
10057 	/*
10058 	 * Must flush the plan cache when changing replication role; but don't
10059 	 * flush unnecessarily.
10060 	 */
10061 	if (SessionReplicationRole != newval)
10062 		ResetPlanCache();
10063 }
10064 
10065 static bool
check_client_min_messages(int * newval,void ** extra,GucSource source)10066 check_client_min_messages(int *newval, void **extra, GucSource source)
10067 {
10068 	/*
10069 	 * We disallow setting client_min_messages above ERROR, because not
10070 	 * sending an ErrorResponse message for an error breaks the FE/BE
10071 	 * protocol.  However, for backwards compatibility, we still accept FATAL
10072 	 * or PANIC as input values, and then adjust here.
10073 	 */
10074 	if (*newval > ERROR)
10075 		*newval = ERROR;
10076 	return true;
10077 }
10078 
10079 static bool
check_temp_buffers(int * newval,void ** extra,GucSource source)10080 check_temp_buffers(int *newval, void **extra, GucSource source)
10081 {
10082 	/*
10083 	 * Once local buffers have been initialized, it's too late to change this.
10084 	 * However, if this is only a test call, allow it.
10085 	 */
10086 	if (source != PGC_S_TEST && NLocBuffer && NLocBuffer != *newval)
10087 	{
10088 		GUC_check_errdetail("\"temp_buffers\" cannot be changed after any temporary tables have been accessed in the session.");
10089 		return false;
10090 	}
10091 	return true;
10092 }
10093 
10094 static bool
check_bonjour(bool * newval,void ** extra,GucSource source)10095 check_bonjour(bool *newval, void **extra, GucSource source)
10096 {
10097 #ifndef USE_BONJOUR
10098 	if (*newval)
10099 	{
10100 		GUC_check_errmsg("Bonjour is not supported by this build");
10101 		return false;
10102 	}
10103 #endif
10104 	return true;
10105 }
10106 
10107 static bool
check_ssl(bool * newval,void ** extra,GucSource source)10108 check_ssl(bool *newval, void **extra, GucSource source)
10109 {
10110 #ifndef USE_SSL
10111 	if (*newval)
10112 	{
10113 		GUC_check_errmsg("SSL is not supported by this build");
10114 		return false;
10115 	}
10116 #endif
10117 	return true;
10118 }
10119 
10120 static bool
check_stage_log_stats(bool * newval,void ** extra,GucSource source)10121 check_stage_log_stats(bool *newval, void **extra, GucSource source)
10122 {
10123 	if (*newval && log_statement_stats)
10124 	{
10125 		GUC_check_errdetail("Cannot enable parameter when \"log_statement_stats\" is true.");
10126 		return false;
10127 	}
10128 	return true;
10129 }
10130 
10131 static bool
check_log_stats(bool * newval,void ** extra,GucSource source)10132 check_log_stats(bool *newval, void **extra, GucSource source)
10133 {
10134 	if (*newval &&
10135 		(log_parser_stats || log_planner_stats || log_executor_stats))
10136 	{
10137 		GUC_check_errdetail("Cannot enable \"log_statement_stats\" when "
10138 							"\"log_parser_stats\", \"log_planner_stats\", "
10139 							"or \"log_executor_stats\" is true.");
10140 		return false;
10141 	}
10142 	return true;
10143 }
10144 
10145 static bool
check_canonical_path(char ** newval,void ** extra,GucSource source)10146 check_canonical_path(char **newval, void **extra, GucSource source)
10147 {
10148 	/*
10149 	 * Since canonicalize_path never enlarges the string, we can just modify
10150 	 * newval in-place.  But watch out for NULL, which is the default value
10151 	 * for external_pid_file.
10152 	 */
10153 	if (*newval)
10154 		canonicalize_path(*newval);
10155 	return true;
10156 }
10157 
10158 static bool
check_timezone_abbreviations(char ** newval,void ** extra,GucSource source)10159 check_timezone_abbreviations(char **newval, void **extra, GucSource source)
10160 {
10161 	/*
10162 	 * The boot_val given above for timezone_abbreviations is NULL. When we
10163 	 * see this we just do nothing.  If this value isn't overridden from the
10164 	 * config file then pg_timezone_abbrev_initialize() will eventually
10165 	 * replace it with "Default".  This hack has two purposes: to avoid
10166 	 * wasting cycles loading values that might soon be overridden from the
10167 	 * config file, and to avoid trying to read the timezone abbrev files
10168 	 * during InitializeGUCOptions().  The latter doesn't work in an
10169 	 * EXEC_BACKEND subprocess because my_exec_path hasn't been set yet and so
10170 	 * we can't locate PGSHAREDIR.
10171 	 */
10172 	if (*newval == NULL)
10173 	{
10174 		Assert(source == PGC_S_DEFAULT);
10175 		return true;
10176 	}
10177 
10178 	/* OK, load the file and produce a malloc'd TimeZoneAbbrevTable */
10179 	*extra = load_tzoffsets(*newval);
10180 
10181 	/* tzparser.c returns NULL on failure, reporting via GUC_check_errmsg */
10182 	if (!*extra)
10183 		return false;
10184 
10185 	return true;
10186 }
10187 
10188 static void
assign_timezone_abbreviations(const char * newval,void * extra)10189 assign_timezone_abbreviations(const char *newval, void *extra)
10190 {
10191 	/* Do nothing for the boot_val default of NULL */
10192 	if (!extra)
10193 		return;
10194 
10195 	InstallTimeZoneAbbrevs((TimeZoneAbbrevTable *) extra);
10196 }
10197 
10198 /*
10199  * pg_timezone_abbrev_initialize --- set default value if not done already
10200  *
10201  * This is called after initial loading of postgresql.conf.  If no
10202  * timezone_abbreviations setting was found therein, select default.
10203  * If a non-default value is already installed, nothing will happen.
10204  *
10205  * This can also be called from ProcessConfigFile to establish the default
10206  * value after a postgresql.conf entry for it is removed.
10207  */
10208 static void
pg_timezone_abbrev_initialize(void)10209 pg_timezone_abbrev_initialize(void)
10210 {
10211 	SetConfigOption("timezone_abbreviations", "Default",
10212 					PGC_POSTMASTER, PGC_S_DYNAMIC_DEFAULT);
10213 }
10214 
10215 static const char *
show_archive_command(void)10216 show_archive_command(void)
10217 {
10218 	if (XLogArchivingActive())
10219 		return XLogArchiveCommand;
10220 	else
10221 		return "(disabled)";
10222 }
10223 
10224 static void
assign_tcp_keepalives_idle(int newval,void * extra)10225 assign_tcp_keepalives_idle(int newval, void *extra)
10226 {
10227 	/*
10228 	 * The kernel API provides no way to test a value without setting it; and
10229 	 * once we set it we might fail to unset it.  So there seems little point
10230 	 * in fully implementing the check-then-assign GUC API for these
10231 	 * variables.  Instead we just do the assignment on demand.  pqcomm.c
10232 	 * reports any problems via elog(LOG).
10233 	 *
10234 	 * This approach means that the GUC value might have little to do with the
10235 	 * actual kernel value, so we use a show_hook that retrieves the kernel
10236 	 * value rather than trusting GUC's copy.
10237 	 */
10238 	(void) pq_setkeepalivesidle(newval, MyProcPort);
10239 }
10240 
10241 static const char *
show_tcp_keepalives_idle(void)10242 show_tcp_keepalives_idle(void)
10243 {
10244 	/* See comments in assign_tcp_keepalives_idle */
10245 	static char nbuf[16];
10246 
10247 	snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivesidle(MyProcPort));
10248 	return nbuf;
10249 }
10250 
10251 static void
assign_tcp_keepalives_interval(int newval,void * extra)10252 assign_tcp_keepalives_interval(int newval, void *extra)
10253 {
10254 	/* See comments in assign_tcp_keepalives_idle */
10255 	(void) pq_setkeepalivesinterval(newval, MyProcPort);
10256 }
10257 
10258 static const char *
show_tcp_keepalives_interval(void)10259 show_tcp_keepalives_interval(void)
10260 {
10261 	/* See comments in assign_tcp_keepalives_idle */
10262 	static char nbuf[16];
10263 
10264 	snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivesinterval(MyProcPort));
10265 	return nbuf;
10266 }
10267 
10268 static void
assign_tcp_keepalives_count(int newval,void * extra)10269 assign_tcp_keepalives_count(int newval, void *extra)
10270 {
10271 	/* See comments in assign_tcp_keepalives_idle */
10272 	(void) pq_setkeepalivescount(newval, MyProcPort);
10273 }
10274 
10275 static const char *
show_tcp_keepalives_count(void)10276 show_tcp_keepalives_count(void)
10277 {
10278 	/* See comments in assign_tcp_keepalives_idle */
10279 	static char nbuf[16];
10280 
10281 	snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivescount(MyProcPort));
10282 	return nbuf;
10283 }
10284 
10285 static bool
check_maxconnections(int * newval,void ** extra,GucSource source)10286 check_maxconnections(int *newval, void **extra, GucSource source)
10287 {
10288 	if (*newval + autovacuum_max_workers + 1 +
10289 		max_worker_processes > MAX_BACKENDS)
10290 		return false;
10291 	return true;
10292 }
10293 
10294 static bool
check_autovacuum_max_workers(int * newval,void ** extra,GucSource source)10295 check_autovacuum_max_workers(int *newval, void **extra, GucSource source)
10296 {
10297 	if (MaxConnections + *newval + 1 + max_worker_processes > MAX_BACKENDS)
10298 		return false;
10299 	return true;
10300 }
10301 
10302 static bool
check_autovacuum_work_mem(int * newval,void ** extra,GucSource source)10303 check_autovacuum_work_mem(int *newval, void **extra, GucSource source)
10304 {
10305 	/*
10306 	 * -1 indicates fallback.
10307 	 *
10308 	 * If we haven't yet changed the boot_val default of -1, just let it be.
10309 	 * Autovacuum will look to maintenance_work_mem instead.
10310 	 */
10311 	if (*newval == -1)
10312 		return true;
10313 
10314 	/*
10315 	 * We clamp manually-set values to at least 1MB.  Since
10316 	 * maintenance_work_mem is always set to at least this value, do the same
10317 	 * here.
10318 	 */
10319 	if (*newval < 1024)
10320 		*newval = 1024;
10321 
10322 	return true;
10323 }
10324 
10325 static bool
check_max_worker_processes(int * newval,void ** extra,GucSource source)10326 check_max_worker_processes(int *newval, void **extra, GucSource source)
10327 {
10328 	if (MaxConnections + autovacuum_max_workers + 1 + *newval > MAX_BACKENDS)
10329 		return false;
10330 	return true;
10331 }
10332 
10333 static bool
check_effective_io_concurrency(int * newval,void ** extra,GucSource source)10334 check_effective_io_concurrency(int *newval, void **extra, GucSource source)
10335 {
10336 #ifdef USE_PREFETCH
10337 	double		new_prefetch_pages;
10338 
10339 	if (ComputeIoConcurrency(*newval, &new_prefetch_pages))
10340 	{
10341 		int		   *myextra = (int *) guc_malloc(ERROR, sizeof(int));
10342 
10343 		*myextra = (int) rint(new_prefetch_pages);
10344 		*extra = (void *) myextra;
10345 
10346 		return true;
10347 	}
10348 	else
10349 		return false;
10350 #else
10351 	return true;
10352 #endif   /* USE_PREFETCH */
10353 }
10354 
10355 static void
assign_effective_io_concurrency(int newval,void * extra)10356 assign_effective_io_concurrency(int newval, void *extra)
10357 {
10358 #ifdef USE_PREFETCH
10359 	target_prefetch_pages = *((int *) extra);
10360 #endif   /* USE_PREFETCH */
10361 }
10362 
10363 static void
assign_pgstat_temp_directory(const char * newval,void * extra)10364 assign_pgstat_temp_directory(const char *newval, void *extra)
10365 {
10366 	/* check_canonical_path already canonicalized newval for us */
10367 	char	   *dname;
10368 	char	   *tname;
10369 	char	   *fname;
10370 
10371 	/* directory */
10372 	dname = guc_malloc(ERROR, strlen(newval) + 1);		/* runtime dir */
10373 	sprintf(dname, "%s", newval);
10374 
10375 	/* global stats */
10376 	tname = guc_malloc(ERROR, strlen(newval) + 12);		/* /global.tmp */
10377 	sprintf(tname, "%s/global.tmp", newval);
10378 	fname = guc_malloc(ERROR, strlen(newval) + 13);		/* /global.stat */
10379 	sprintf(fname, "%s/global.stat", newval);
10380 
10381 	if (pgstat_stat_directory)
10382 		free(pgstat_stat_directory);
10383 	pgstat_stat_directory = dname;
10384 	if (pgstat_stat_tmpname)
10385 		free(pgstat_stat_tmpname);
10386 	pgstat_stat_tmpname = tname;
10387 	if (pgstat_stat_filename)
10388 		free(pgstat_stat_filename);
10389 	pgstat_stat_filename = fname;
10390 }
10391 
10392 static bool
check_application_name(char ** newval,void ** extra,GucSource source)10393 check_application_name(char **newval, void **extra, GucSource source)
10394 {
10395 	/* Only allow clean ASCII chars in the application name */
10396 	char	   *p;
10397 
10398 	for (p = *newval; *p; p++)
10399 	{
10400 		if (*p < 32 || *p > 126)
10401 			*p = '?';
10402 	}
10403 
10404 	return true;
10405 }
10406 
10407 static void
assign_application_name(const char * newval,void * extra)10408 assign_application_name(const char *newval, void *extra)
10409 {
10410 	/* Update the pg_stat_activity view */
10411 	pgstat_report_appname(newval);
10412 }
10413 
10414 static bool
check_cluster_name(char ** newval,void ** extra,GucSource source)10415 check_cluster_name(char **newval, void **extra, GucSource source)
10416 {
10417 	/* Only allow clean ASCII chars in the cluster name */
10418 	char	   *p;
10419 
10420 	for (p = *newval; *p; p++)
10421 	{
10422 		if (*p < 32 || *p > 126)
10423 			*p = '?';
10424 	}
10425 
10426 	return true;
10427 }
10428 
10429 static const char *
show_unix_socket_permissions(void)10430 show_unix_socket_permissions(void)
10431 {
10432 	static char buf[8];
10433 
10434 	snprintf(buf, sizeof(buf), "%04o", Unix_socket_permissions);
10435 	return buf;
10436 }
10437 
10438 static const char *
show_log_file_mode(void)10439 show_log_file_mode(void)
10440 {
10441 	static char buf[8];
10442 
10443 	snprintf(buf, sizeof(buf), "%04o", Log_file_mode);
10444 	return buf;
10445 }
10446 
10447 #include "guc-file.c"
10448