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