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