]> granicus.if.org Git - postgresql/blob - src/backend/utils/misc/guc.c
pgindent run for 9.4
[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                 -1, -1, INT_MAX,
2516                 check_effective_cache_size, 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          * If timezone_abbreviations wasn't set in the configuration file, install
4368          * the default value.  We do it this way because we can't safely install a
4369          * "real" value until my_exec_path is set, which may not have happened
4370          * when InitializeGUCOptions runs, so the bootstrap default value cannot
4371          * be the real desired default.
4372          */
4373         pg_timezone_abbrev_initialize();
4374
4375         /* Also install the correct value for effective_cache_size */
4376         set_default_effective_cache_size();
4377
4378         /*
4379          * Figure out where pg_hba.conf is, and make sure the path is absolute.
4380          */
4381         if (HbaFileName)
4382                 fname = make_absolute_path(HbaFileName);
4383         else if (configdir)
4384         {
4385                 fname = guc_malloc(FATAL,
4386                                                    strlen(configdir) + strlen(HBA_FILENAME) + 2);
4387                 sprintf(fname, "%s/%s", configdir, HBA_FILENAME);
4388         }
4389         else
4390         {
4391                 write_stderr("%s does not know where to find the \"hba\" configuration file.\n"
4392                                          "This can be specified as \"hba_file\" in \"%s\", "
4393                                          "or by the -D invocation option, or by the "
4394                                          "PGDATA environment variable.\n",
4395                                          progname, ConfigFileName);
4396                 return false;
4397         }
4398         SetConfigOption("hba_file", fname, PGC_POSTMASTER, PGC_S_OVERRIDE);
4399         free(fname);
4400
4401         /*
4402          * Likewise for pg_ident.conf.
4403          */
4404         if (IdentFileName)
4405                 fname = make_absolute_path(IdentFileName);
4406         else if (configdir)
4407         {
4408                 fname = guc_malloc(FATAL,
4409                                                    strlen(configdir) + strlen(IDENT_FILENAME) + 2);
4410                 sprintf(fname, "%s/%s", configdir, IDENT_FILENAME);
4411         }
4412         else
4413         {
4414                 write_stderr("%s does not know where to find the \"ident\" configuration file.\n"
4415                                          "This can be specified as \"ident_file\" in \"%s\", "
4416                                          "or by the -D invocation option, or by the "
4417                                          "PGDATA environment variable.\n",
4418                                          progname, ConfigFileName);
4419                 return false;
4420         }
4421         SetConfigOption("ident_file", fname, PGC_POSTMASTER, PGC_S_OVERRIDE);
4422         free(fname);
4423
4424         free(configdir);
4425
4426         return true;
4427 }
4428
4429
4430 /*
4431  * Reset all options to their saved default values (implements RESET ALL)
4432  */
4433 void
4434 ResetAllOptions(void)
4435 {
4436         int                     i;
4437
4438         for (i = 0; i < num_guc_variables; i++)
4439         {
4440                 struct config_generic *gconf = guc_variables[i];
4441
4442                 /* Don't reset non-SET-able values */
4443                 if (gconf->context != PGC_SUSET &&
4444                         gconf->context != PGC_USERSET)
4445                         continue;
4446                 /* Don't reset if special exclusion from RESET ALL */
4447                 if (gconf->flags & GUC_NO_RESET_ALL)
4448                         continue;
4449                 /* No need to reset if wasn't SET */
4450                 if (gconf->source <= PGC_S_OVERRIDE)
4451                         continue;
4452
4453                 /* Save old value to support transaction abort */
4454                 push_old_value(gconf, GUC_ACTION_SET);
4455
4456                 switch (gconf->vartype)
4457                 {
4458                         case PGC_BOOL:
4459                                 {
4460                                         struct config_bool *conf = (struct config_bool *) gconf;
4461
4462                                         if (conf->assign_hook)
4463                                                 (*conf->assign_hook) (conf->reset_val,
4464                                                                                           conf->reset_extra);
4465                                         *conf->variable = conf->reset_val;
4466                                         set_extra_field(&conf->gen, &conf->gen.extra,
4467                                                                         conf->reset_extra);
4468                                         break;
4469                                 }
4470                         case PGC_INT:
4471                                 {
4472                                         struct config_int *conf = (struct config_int *) gconf;
4473
4474                                         if (conf->assign_hook)
4475                                                 (*conf->assign_hook) (conf->reset_val,
4476                                                                                           conf->reset_extra);
4477                                         *conf->variable = conf->reset_val;
4478                                         set_extra_field(&conf->gen, &conf->gen.extra,
4479                                                                         conf->reset_extra);
4480                                         break;
4481                                 }
4482                         case PGC_REAL:
4483                                 {
4484                                         struct config_real *conf = (struct config_real *) gconf;
4485
4486                                         if (conf->assign_hook)
4487                                                 (*conf->assign_hook) (conf->reset_val,
4488                                                                                           conf->reset_extra);
4489                                         *conf->variable = conf->reset_val;
4490                                         set_extra_field(&conf->gen, &conf->gen.extra,
4491                                                                         conf->reset_extra);
4492                                         break;
4493                                 }
4494                         case PGC_STRING:
4495                                 {
4496                                         struct config_string *conf = (struct config_string *) gconf;
4497
4498                                         if (conf->assign_hook)
4499                                                 (*conf->assign_hook) (conf->reset_val,
4500                                                                                           conf->reset_extra);
4501                                         set_string_field(conf, conf->variable, conf->reset_val);
4502                                         set_extra_field(&conf->gen, &conf->gen.extra,
4503                                                                         conf->reset_extra);
4504                                         break;
4505                                 }
4506                         case PGC_ENUM:
4507                                 {
4508                                         struct config_enum *conf = (struct config_enum *) gconf;
4509
4510                                         if (conf->assign_hook)
4511                                                 (*conf->assign_hook) (conf->reset_val,
4512                                                                                           conf->reset_extra);
4513                                         *conf->variable = conf->reset_val;
4514                                         set_extra_field(&conf->gen, &conf->gen.extra,
4515                                                                         conf->reset_extra);
4516                                         break;
4517                                 }
4518                 }
4519
4520                 gconf->source = gconf->reset_source;
4521                 gconf->scontext = gconf->reset_scontext;
4522
4523                 if (gconf->flags & GUC_REPORT)
4524                         ReportGUCOption(gconf);
4525         }
4526 }
4527
4528
4529 /*
4530  * push_old_value
4531  *              Push previous state during transactional assignment to a GUC variable.
4532  */
4533 static void
4534 push_old_value(struct config_generic * gconf, GucAction action)
4535 {
4536         GucStack   *stack;
4537
4538         /* If we're not inside a nest level, do nothing */
4539         if (GUCNestLevel == 0)
4540                 return;
4541
4542         /* Do we already have a stack entry of the current nest level? */
4543         stack = gconf->stack;
4544         if (stack && stack->nest_level >= GUCNestLevel)
4545         {
4546                 /* Yes, so adjust its state if necessary */
4547                 Assert(stack->nest_level == GUCNestLevel);
4548                 switch (action)
4549                 {
4550                         case GUC_ACTION_SET:
4551                                 /* SET overrides any prior action at same nest level */
4552                                 if (stack->state == GUC_SET_LOCAL)
4553                                 {
4554                                         /* must discard old masked value */
4555                                         discard_stack_value(gconf, &stack->masked);
4556                                 }
4557                                 stack->state = GUC_SET;
4558                                 break;
4559                         case GUC_ACTION_LOCAL:
4560                                 if (stack->state == GUC_SET)
4561                                 {
4562                                         /* SET followed by SET LOCAL, remember SET's value */
4563                                         stack->masked_scontext = gconf->scontext;
4564                                         set_stack_value(gconf, &stack->masked);
4565                                         stack->state = GUC_SET_LOCAL;
4566                                 }
4567                                 /* in all other cases, no change to stack entry */
4568                                 break;
4569                         case GUC_ACTION_SAVE:
4570                                 /* Could only have a prior SAVE of same variable */
4571                                 Assert(stack->state == GUC_SAVE);
4572                                 break;
4573                 }
4574                 Assert(guc_dirty);              /* must be set already */
4575                 return;
4576         }
4577
4578         /*
4579          * Push a new stack entry
4580          *
4581          * We keep all the stack entries in TopTransactionContext for simplicity.
4582          */
4583         stack = (GucStack *) MemoryContextAllocZero(TopTransactionContext,
4584                                                                                                 sizeof(GucStack));
4585
4586         stack->prev = gconf->stack;
4587         stack->nest_level = GUCNestLevel;
4588         switch (action)
4589         {
4590                 case GUC_ACTION_SET:
4591                         stack->state = GUC_SET;
4592                         break;
4593                 case GUC_ACTION_LOCAL:
4594                         stack->state = GUC_LOCAL;
4595                         break;
4596                 case GUC_ACTION_SAVE:
4597                         stack->state = GUC_SAVE;
4598                         break;
4599         }
4600         stack->source = gconf->source;
4601         stack->scontext = gconf->scontext;
4602         set_stack_value(gconf, &stack->prior);
4603
4604         gconf->stack = stack;
4605
4606         /* Ensure we remember to pop at end of xact */
4607         guc_dirty = true;
4608 }
4609
4610
4611 /*
4612  * Do GUC processing at main transaction start.
4613  */
4614 void
4615 AtStart_GUC(void)
4616 {
4617         /*
4618          * The nest level should be 0 between transactions; if it isn't, somebody
4619          * didn't call AtEOXact_GUC, or called it with the wrong nestLevel.  We
4620          * throw a warning but make no other effort to clean up.
4621          */
4622         if (GUCNestLevel != 0)
4623                 elog(WARNING, "GUC nest level = %d at transaction start",
4624                          GUCNestLevel);
4625         GUCNestLevel = 1;
4626 }
4627
4628 /*
4629  * Enter a new nesting level for GUC values.  This is called at subtransaction
4630  * start, and when entering a function that has proconfig settings, and in
4631  * some other places where we want to set GUC variables transiently.
4632  * NOTE we must not risk error here, else subtransaction start will be unhappy.
4633  */
4634 int
4635 NewGUCNestLevel(void)
4636 {
4637         return ++GUCNestLevel;
4638 }
4639
4640 /*
4641  * Do GUC processing at transaction or subtransaction commit or abort, or
4642  * when exiting a function that has proconfig settings, or when undoing a
4643  * transient assignment to some GUC variables.  (The name is thus a bit of
4644  * a misnomer; perhaps it should be ExitGUCNestLevel or some such.)
4645  * During abort, we discard all GUC settings that were applied at nesting
4646  * levels >= nestLevel.  nestLevel == 1 corresponds to the main transaction.
4647  */
4648 void
4649 AtEOXact_GUC(bool isCommit, int nestLevel)
4650 {
4651         bool            still_dirty;
4652         int                     i;
4653
4654         /*
4655          * Note: it's possible to get here with GUCNestLevel == nestLevel-1 during
4656          * abort, if there is a failure during transaction start before
4657          * AtStart_GUC is called.
4658          */
4659         Assert(nestLevel > 0 &&
4660                    (nestLevel <= GUCNestLevel ||
4661                         (nestLevel == GUCNestLevel + 1 && !isCommit)));
4662
4663         /* Quick exit if nothing's changed in this transaction */
4664         if (!guc_dirty)
4665         {
4666                 GUCNestLevel = nestLevel - 1;
4667                 return;
4668         }
4669
4670         still_dirty = false;
4671         for (i = 0; i < num_guc_variables; i++)
4672         {
4673                 struct config_generic *gconf = guc_variables[i];
4674                 GucStack   *stack;
4675
4676                 /*
4677                  * Process and pop each stack entry within the nest level. To simplify
4678                  * fmgr_security_definer() and other places that use GUC_ACTION_SAVE,
4679                  * we allow failure exit from code that uses a local nest level to be
4680                  * recovered at the surrounding transaction or subtransaction abort;
4681                  * so there could be more than one stack entry to pop.
4682                  */
4683                 while ((stack = gconf->stack) != NULL &&
4684                            stack->nest_level >= nestLevel)
4685                 {
4686                         GucStack   *prev = stack->prev;
4687                         bool            restorePrior = false;
4688                         bool            restoreMasked = false;
4689                         bool            changed;
4690
4691                         /*
4692                          * In this next bit, if we don't set either restorePrior or
4693                          * restoreMasked, we must "discard" any unwanted fields of the
4694                          * stack entries to avoid leaking memory.  If we do set one of
4695                          * those flags, unused fields will be cleaned up after restoring.
4696                          */
4697                         if (!isCommit)          /* if abort, always restore prior value */
4698                                 restorePrior = true;
4699                         else if (stack->state == GUC_SAVE)
4700                                 restorePrior = true;
4701                         else if (stack->nest_level == 1)
4702                         {
4703                                 /* transaction commit */
4704                                 if (stack->state == GUC_SET_LOCAL)
4705                                         restoreMasked = true;
4706                                 else if (stack->state == GUC_SET)
4707                                 {
4708                                         /* we keep the current active value */
4709                                         discard_stack_value(gconf, &stack->prior);
4710                                 }
4711                                 else    /* must be GUC_LOCAL */
4712                                         restorePrior = true;
4713                         }
4714                         else if (prev == NULL ||
4715                                          prev->nest_level < stack->nest_level - 1)
4716                         {
4717                                 /* decrement entry's level and do not pop it */
4718                                 stack->nest_level--;
4719                                 continue;
4720                         }
4721                         else
4722                         {
4723                                 /*
4724                                  * We have to merge this stack entry into prev. See README for
4725                                  * discussion of this bit.
4726                                  */
4727                                 switch (stack->state)
4728                                 {
4729                                         case GUC_SAVE:
4730                                                 Assert(false);  /* can't get here */
4731
4732                                         case GUC_SET:
4733                                                 /* next level always becomes SET */
4734                                                 discard_stack_value(gconf, &stack->prior);
4735                                                 if (prev->state == GUC_SET_LOCAL)
4736                                                         discard_stack_value(gconf, &prev->masked);
4737                                                 prev->state = GUC_SET;
4738                                                 break;
4739
4740                                         case GUC_LOCAL:
4741                                                 if (prev->state == GUC_SET)
4742                                                 {
4743                                                         /* LOCAL migrates down */
4744                                                         prev->masked_scontext = stack->scontext;
4745                                                         prev->masked = stack->prior;
4746                                                         prev->state = GUC_SET_LOCAL;
4747                                                 }
4748                                                 else
4749                                                 {
4750                                                         /* else just forget this stack level */
4751                                                         discard_stack_value(gconf, &stack->prior);
4752                                                 }
4753                                                 break;
4754
4755                                         case GUC_SET_LOCAL:
4756                                                 /* prior state at this level no longer wanted */
4757                                                 discard_stack_value(gconf, &stack->prior);
4758                                                 /* copy down the masked state */
4759                                                 prev->masked_scontext = stack->masked_scontext;
4760                                                 if (prev->state == GUC_SET_LOCAL)
4761                                                         discard_stack_value(gconf, &prev->masked);
4762                                                 prev->masked = stack->masked;
4763                                                 prev->state = GUC_SET_LOCAL;
4764                                                 break;
4765                                 }
4766                         }
4767
4768                         changed = false;
4769
4770                         if (restorePrior || restoreMasked)
4771                         {
4772                                 /* Perform appropriate restoration of the stacked value */
4773                                 config_var_value newvalue;
4774                                 GucSource       newsource;
4775                                 GucContext      newscontext;
4776
4777                                 if (restoreMasked)
4778                                 {
4779                                         newvalue = stack->masked;
4780                                         newsource = PGC_S_SESSION;
4781                                         newscontext = stack->masked_scontext;
4782                                 }
4783                                 else
4784                                 {
4785                                         newvalue = stack->prior;
4786                                         newsource = stack->source;
4787                                         newscontext = stack->scontext;
4788                                 }
4789
4790                                 switch (gconf->vartype)
4791                                 {
4792                                         case PGC_BOOL:
4793                                                 {
4794                                                         struct config_bool *conf = (struct config_bool *) gconf;
4795                                                         bool            newval = newvalue.val.boolval;
4796                                                         void       *newextra = newvalue.extra;
4797
4798                                                         if (*conf->variable != newval ||
4799                                                                 conf->gen.extra != newextra)
4800                                                         {
4801                                                                 if (conf->assign_hook)
4802                                                                         (*conf->assign_hook) (newval, newextra);
4803                                                                 *conf->variable = newval;
4804                                                                 set_extra_field(&conf->gen, &conf->gen.extra,
4805                                                                                                 newextra);
4806                                                                 changed = true;
4807                                                         }
4808                                                         break;
4809                                                 }
4810                                         case PGC_INT:
4811                                                 {
4812                                                         struct config_int *conf = (struct config_int *) gconf;
4813                                                         int                     newval = newvalue.val.intval;
4814                                                         void       *newextra = newvalue.extra;
4815
4816                                                         if (*conf->variable != newval ||
4817                                                                 conf->gen.extra != newextra)
4818                                                         {
4819                                                                 if (conf->assign_hook)
4820                                                                         (*conf->assign_hook) (newval, newextra);
4821                                                                 *conf->variable = newval;
4822                                                                 set_extra_field(&conf->gen, &conf->gen.extra,
4823                                                                                                 newextra);
4824                                                                 changed = true;
4825                                                         }
4826                                                         break;
4827                                                 }
4828                                         case PGC_REAL:
4829                                                 {
4830                                                         struct config_real *conf = (struct config_real *) gconf;
4831                                                         double          newval = newvalue.val.realval;
4832                                                         void       *newextra = newvalue.extra;
4833
4834                                                         if (*conf->variable != newval ||
4835                                                                 conf->gen.extra != newextra)
4836                                                         {
4837                                                                 if (conf->assign_hook)
4838                                                                         (*conf->assign_hook) (newval, newextra);
4839                                                                 *conf->variable = newval;
4840                                                                 set_extra_field(&conf->gen, &conf->gen.extra,
4841                                                                                                 newextra);
4842                                                                 changed = true;
4843                                                         }
4844                                                         break;
4845                                                 }
4846                                         case PGC_STRING:
4847                                                 {
4848                                                         struct config_string *conf = (struct config_string *) gconf;
4849                                                         char       *newval = newvalue.val.stringval;
4850                                                         void       *newextra = newvalue.extra;
4851
4852                                                         if (*conf->variable != newval ||
4853                                                                 conf->gen.extra != newextra)
4854                                                         {
4855                                                                 if (conf->assign_hook)
4856                                                                         (*conf->assign_hook) (newval, newextra);
4857                                                                 set_string_field(conf, conf->variable, newval);
4858                                                                 set_extra_field(&conf->gen, &conf->gen.extra,
4859                                                                                                 newextra);
4860                                                                 changed = true;
4861                                                         }
4862
4863                                                         /*
4864                                                          * Release stacked values if not used anymore. We
4865                                                          * could use discard_stack_value() here, but since
4866                                                          * we have type-specific code anyway, might as
4867                                                          * well inline it.
4868                                                          */
4869                                                         set_string_field(conf, &stack->prior.val.stringval, NULL);
4870                                                         set_string_field(conf, &stack->masked.val.stringval, NULL);
4871                                                         break;
4872                                                 }
4873                                         case PGC_ENUM:
4874                                                 {
4875                                                         struct config_enum *conf = (struct config_enum *) gconf;
4876                                                         int                     newval = newvalue.val.enumval;
4877                                                         void       *newextra = newvalue.extra;
4878
4879                                                         if (*conf->variable != newval ||
4880                                                                 conf->gen.extra != newextra)
4881                                                         {
4882                                                                 if (conf->assign_hook)
4883                                                                         (*conf->assign_hook) (newval, newextra);
4884                                                                 *conf->variable = newval;
4885                                                                 set_extra_field(&conf->gen, &conf->gen.extra,
4886                                                                                                 newextra);
4887                                                                 changed = true;
4888                                                         }
4889                                                         break;
4890                                                 }
4891                                 }
4892
4893                                 /*
4894                                  * Release stacked extra values if not used anymore.
4895                                  */
4896                                 set_extra_field(gconf, &(stack->prior.extra), NULL);
4897                                 set_extra_field(gconf, &(stack->masked.extra), NULL);
4898
4899                                 /* And restore source information */
4900                                 gconf->source = newsource;
4901                                 gconf->scontext = newscontext;
4902                         }
4903
4904                         /* Finish popping the state stack */
4905                         gconf->stack = prev;
4906                         pfree(stack);
4907
4908                         /* Report new value if we changed it */
4909                         if (changed && (gconf->flags & GUC_REPORT))
4910                                 ReportGUCOption(gconf);
4911                 }                                               /* end of stack-popping loop */
4912
4913                 if (stack != NULL)
4914                         still_dirty = true;
4915         }
4916
4917         /* If there are no remaining stack entries, we can reset guc_dirty */
4918         guc_dirty = still_dirty;
4919
4920         /* Update nesting level */
4921         GUCNestLevel = nestLevel - 1;
4922 }
4923
4924
4925 /*
4926  * Start up automatic reporting of changes to variables marked GUC_REPORT.
4927  * This is executed at completion of backend startup.
4928  */
4929 void
4930 BeginReportingGUCOptions(void)
4931 {
4932         int                     i;
4933
4934         /*
4935          * Don't do anything unless talking to an interactive frontend of protocol
4936          * 3.0 or later.
4937          */
4938         if (whereToSendOutput != DestRemote ||
4939                 PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
4940                 return;
4941
4942         reporting_enabled = true;
4943
4944         /* Transmit initial values of interesting variables */
4945         for (i = 0; i < num_guc_variables; i++)
4946         {
4947                 struct config_generic *conf = guc_variables[i];
4948
4949                 if (conf->flags & GUC_REPORT)
4950                         ReportGUCOption(conf);
4951         }
4952 }
4953
4954 /*
4955  * ReportGUCOption: if appropriate, transmit option value to frontend
4956  */
4957 static void
4958 ReportGUCOption(struct config_generic * record)
4959 {
4960         if (reporting_enabled && (record->flags & GUC_REPORT))
4961         {
4962                 char       *val = _ShowOption(record, false);
4963                 StringInfoData msgbuf;
4964
4965                 pq_beginmessage(&msgbuf, 'S');
4966                 pq_sendstring(&msgbuf, record->name);
4967                 pq_sendstring(&msgbuf, val);
4968                 pq_endmessage(&msgbuf);
4969
4970                 pfree(val);
4971         }
4972 }
4973
4974 /*
4975  * Try to parse value as an integer.  The accepted formats are the
4976  * usual decimal, octal, or hexadecimal formats, optionally followed by
4977  * a unit name if "flags" indicates a unit is allowed.
4978  *
4979  * If the string parses okay, return true, else false.
4980  * If okay and result is not NULL, return the value in *result.
4981  * If not okay and hintmsg is not NULL, *hintmsg is set to a suitable
4982  *      HINT message, or NULL if no hint provided.
4983  */
4984 bool
4985 parse_int(const char *value, int *result, int flags, const char **hintmsg)
4986 {
4987         int64           val;
4988         char       *endptr;
4989
4990         /* To suppress compiler warnings, always set output params */
4991         if (result)
4992                 *result = 0;
4993         if (hintmsg)
4994                 *hintmsg = NULL;
4995
4996         /* We assume here that int64 is at least as wide as long */
4997         errno = 0;
4998         val = strtol(value, &endptr, 0);
4999
5000         if (endptr == value)
5001                 return false;                   /* no HINT for integer syntax error */
5002
5003         if (errno == ERANGE || val != (int64) ((int32) val))
5004         {
5005                 if (hintmsg)
5006                         *hintmsg = gettext_noop("Value exceeds integer range.");
5007                 return false;
5008         }
5009
5010         /* allow whitespace between integer and unit */
5011         while (isspace((unsigned char) *endptr))
5012                 endptr++;
5013
5014         /* Handle possible unit */
5015         if (*endptr != '\0')
5016         {
5017                 /*
5018                  * Note: the multiple-switch coding technique here is a bit tedious,
5019                  * but seems necessary to avoid intermediate-value overflows.
5020                  */
5021                 if (flags & GUC_UNIT_MEMORY)
5022                 {
5023                         /* Set hint for use if no match or trailing garbage */
5024                         if (hintmsg)
5025                                 *hintmsg = gettext_noop("Valid units for this parameter are \"kB\", \"MB\", \"GB\", and \"TB\".");
5026
5027 #if BLCKSZ < 1024 || BLCKSZ > (1024*1024)
5028 #error BLCKSZ must be between 1KB and 1MB
5029 #endif
5030 #if XLOG_BLCKSZ < 1024 || XLOG_BLCKSZ > (1024*1024)
5031 #error XLOG_BLCKSZ must be between 1KB and 1MB
5032 #endif
5033
5034                         if (strncmp(endptr, "kB", 2) == 0)
5035                         {
5036                                 endptr += 2;
5037                                 switch (flags & GUC_UNIT_MEMORY)
5038                                 {
5039                                         case GUC_UNIT_BLOCKS:
5040                                                 val /= (BLCKSZ / 1024);
5041                                                 break;
5042                                         case GUC_UNIT_XBLOCKS:
5043                                                 val /= (XLOG_BLCKSZ / 1024);
5044                                                 break;
5045                                 }
5046                         }
5047                         else if (strncmp(endptr, "MB", 2) == 0)
5048                         {
5049                                 endptr += 2;
5050                                 switch (flags & GUC_UNIT_MEMORY)
5051                                 {
5052                                         case GUC_UNIT_KB:
5053                                                 val *= KB_PER_MB;
5054                                                 break;
5055                                         case GUC_UNIT_BLOCKS:
5056                                                 val *= KB_PER_MB / (BLCKSZ / 1024);
5057                                                 break;
5058                                         case GUC_UNIT_XBLOCKS:
5059                                                 val *= KB_PER_MB / (XLOG_BLCKSZ / 1024);
5060                                                 break;
5061                                 }
5062                         }
5063                         else if (strncmp(endptr, "GB", 2) == 0)
5064                         {
5065                                 endptr += 2;
5066                                 switch (flags & GUC_UNIT_MEMORY)
5067                                 {
5068                                         case GUC_UNIT_KB:
5069                                                 val *= KB_PER_GB;
5070                                                 break;
5071                                         case GUC_UNIT_BLOCKS:
5072                                                 val *= KB_PER_GB / (BLCKSZ / 1024);
5073                                                 break;
5074                                         case GUC_UNIT_XBLOCKS:
5075                                                 val *= KB_PER_GB / (XLOG_BLCKSZ / 1024);
5076                                                 break;
5077                                 }
5078                         }
5079                         else if (strncmp(endptr, "TB", 2) == 0)
5080                         {
5081                                 endptr += 2;
5082                                 switch (flags & GUC_UNIT_MEMORY)
5083                                 {
5084                                         case GUC_UNIT_KB:
5085                                                 val *= KB_PER_TB;
5086                                                 break;
5087                                         case GUC_UNIT_BLOCKS:
5088                                                 val *= KB_PER_TB / (BLCKSZ / 1024);
5089                                                 break;
5090                                         case GUC_UNIT_XBLOCKS:
5091                                                 val *= KB_PER_TB / (XLOG_BLCKSZ / 1024);
5092                                                 break;
5093                                 }
5094                         }
5095                 }
5096                 else if (flags & GUC_UNIT_TIME)
5097                 {
5098                         /* Set hint for use if no match or trailing garbage */
5099                         if (hintmsg)
5100                                 *hintmsg = gettext_noop("Valid units for this parameter are \"ms\", \"s\", \"min\", \"h\", and \"d\".");
5101
5102                         if (strncmp(endptr, "ms", 2) == 0)
5103                         {
5104                                 endptr += 2;
5105                                 switch (flags & GUC_UNIT_TIME)
5106                                 {
5107                                         case GUC_UNIT_S:
5108                                                 val /= MS_PER_S;
5109                                                 break;
5110                                         case GUC_UNIT_MIN:
5111                                                 val /= MS_PER_MIN;
5112                                                 break;
5113                                 }
5114                         }
5115                         else if (strncmp(endptr, "s", 1) == 0)
5116                         {
5117                                 endptr += 1;
5118                                 switch (flags & GUC_UNIT_TIME)
5119                                 {
5120                                         case GUC_UNIT_MS:
5121                                                 val *= MS_PER_S;
5122                                                 break;
5123                                         case GUC_UNIT_MIN:
5124                                                 val /= S_PER_MIN;
5125                                                 break;
5126                                 }
5127                         }
5128                         else if (strncmp(endptr, "min", 3) == 0)
5129                         {
5130                                 endptr += 3;
5131                                 switch (flags & GUC_UNIT_TIME)
5132                                 {
5133                                         case GUC_UNIT_MS:
5134                                                 val *= MS_PER_MIN;
5135                                                 break;
5136                                         case GUC_UNIT_S:
5137                                                 val *= S_PER_MIN;
5138                                                 break;
5139                                 }
5140                         }
5141                         else if (strncmp(endptr, "h", 1) == 0)
5142                         {
5143                                 endptr += 1;
5144                                 switch (flags & GUC_UNIT_TIME)
5145                                 {
5146                                         case GUC_UNIT_MS:
5147                                                 val *= MS_PER_H;
5148                                                 break;
5149                                         case GUC_UNIT_S:
5150                                                 val *= S_PER_H;
5151                                                 break;
5152                                         case GUC_UNIT_MIN:
5153                                                 val *= MIN_PER_H;
5154                                                 break;
5155                                 }
5156                         }
5157                         else if (strncmp(endptr, "d", 1) == 0)
5158                         {
5159                                 endptr += 1;
5160                                 switch (flags & GUC_UNIT_TIME)
5161                                 {
5162                                         case GUC_UNIT_MS:
5163                                                 val *= MS_PER_D;
5164                                                 break;
5165                                         case GUC_UNIT_S:
5166                                                 val *= S_PER_D;
5167                                                 break;
5168                                         case GUC_UNIT_MIN:
5169                                                 val *= MIN_PER_D;
5170                                                 break;
5171                                 }
5172                         }
5173                 }
5174
5175                 /* allow whitespace after unit */
5176                 while (isspace((unsigned char) *endptr))
5177                         endptr++;
5178
5179                 if (*endptr != '\0')
5180                         return false;           /* appropriate hint, if any, already set */
5181
5182                 /* Check for overflow due to units conversion */
5183                 if (val != (int64) ((int32) val))
5184                 {
5185                         if (hintmsg)
5186                                 *hintmsg = gettext_noop("Value exceeds integer range.");
5187                         return false;
5188                 }
5189         }
5190
5191         if (result)
5192                 *result = (int) val;
5193         return true;
5194 }
5195
5196
5197
5198 /*
5199  * Try to parse value as a floating point number in the usual format.
5200  * If the string parses okay, return true, else false.
5201  * If okay and result is not NULL, return the value in *result.
5202  */
5203 bool
5204 parse_real(const char *value, double *result)
5205 {
5206         double          val;
5207         char       *endptr;
5208
5209         if (result)
5210                 *result = 0;                    /* suppress compiler warning */
5211
5212         errno = 0;
5213         val = strtod(value, &endptr);
5214         if (endptr == value || errno == ERANGE)
5215                 return false;
5216
5217         /* allow whitespace after number */
5218         while (isspace((unsigned char) *endptr))
5219                 endptr++;
5220         if (*endptr != '\0')
5221                 return false;
5222
5223         if (result)
5224                 *result = val;
5225         return true;
5226 }
5227
5228
5229 /*
5230  * Lookup the name for an enum option with the selected value.
5231  * Should only ever be called with known-valid values, so throws
5232  * an elog(ERROR) if the enum option is not found.
5233  *
5234  * The returned string is a pointer to static data and not
5235  * allocated for modification.
5236  */
5237 const char *
5238 config_enum_lookup_by_value(struct config_enum * record, int val)
5239 {
5240         const struct config_enum_entry *entry;
5241
5242         for (entry = record->options; entry && entry->name; entry++)
5243         {
5244                 if (entry->val == val)
5245                         return entry->name;
5246         }
5247
5248         elog(ERROR, "could not find enum option %d for %s",
5249                  val, record->gen.name);
5250         return NULL;                            /* silence compiler */
5251 }
5252
5253
5254 /*
5255  * Lookup the value for an enum option with the selected name
5256  * (case-insensitive).
5257  * If the enum option is found, sets the retval value and returns
5258  * true. If it's not found, return FALSE and retval is set to 0.
5259  */
5260 bool
5261 config_enum_lookup_by_name(struct config_enum * record, const char *value,
5262                                                    int *retval)
5263 {
5264         const struct config_enum_entry *entry;
5265
5266         for (entry = record->options; entry && entry->name; entry++)
5267         {
5268                 if (pg_strcasecmp(value, entry->name) == 0)
5269                 {
5270                         *retval = entry->val;
5271                         return TRUE;
5272                 }
5273         }
5274
5275         *retval = 0;
5276         return FALSE;
5277 }
5278
5279
5280 /*
5281  * Return a list of all available options for an enum, excluding
5282  * hidden ones, separated by the given separator.
5283  * If prefix is non-NULL, it is added before the first enum value.
5284  * If suffix is non-NULL, it is added to the end of the string.
5285  */
5286 static char *
5287 config_enum_get_options(struct config_enum * record, const char *prefix,
5288                                                 const char *suffix, const char *separator)
5289 {
5290         const struct config_enum_entry *entry;
5291         StringInfoData retstr;
5292         int                     seplen;
5293
5294         initStringInfo(&retstr);
5295         appendStringInfoString(&retstr, prefix);
5296
5297         seplen = strlen(separator);
5298         for (entry = record->options; entry && entry->name; entry++)
5299         {
5300                 if (!entry->hidden)
5301                 {
5302                         appendStringInfoString(&retstr, entry->name);
5303                         appendBinaryStringInfo(&retstr, separator, seplen);
5304                 }
5305         }
5306
5307         /*
5308          * All the entries may have been hidden, leaving the string empty if no
5309          * prefix was given. This indicates a broken GUC setup, since there is no
5310          * use for an enum without any values, so we just check to make sure we
5311          * don't write to invalid memory instead of actually trying to do
5312          * something smart with it.
5313          */
5314         if (retstr.len >= seplen)
5315         {
5316                 /* Replace final separator */
5317                 retstr.data[retstr.len - seplen] = '\0';
5318                 retstr.len -= seplen;
5319         }
5320
5321         appendStringInfoString(&retstr, suffix);
5322
5323         return retstr.data;
5324 }
5325
5326 /*
5327  * Validates configuration parameter and value, by calling check hook functions
5328  * depending on record's vartype. It validates if the parameter
5329  * value given is in range of expected predefined value for that parameter.
5330  *
5331  * freemem - true indicates memory for newval and newextra will be
5332  *                       freed in this function, false indicates it will be freed
5333  *                       by caller.
5334  * Return value:
5335  *      1: the value is valid
5336  *      0: the name or value is invalid
5337  */
5338 bool
5339 validate_conf_option(struct config_generic * record, const char *name,
5340                                          const char *value, GucSource source, int elevel,
5341                                          bool freemem, void *newval, void **newextra)
5342 {
5343         /*
5344          * Validate the value for the passed record, to ensure it is in expected
5345          * range.
5346          */
5347         switch (record->vartype)
5348         {
5349
5350                 case PGC_BOOL:
5351                         {
5352                                 struct config_bool *conf = (struct config_bool *) record;
5353                                 bool            tmpnewval;
5354
5355                                 if (newval == NULL)
5356                                         newval = &tmpnewval;
5357
5358                                 if (value != NULL)
5359                                 {
5360                                         if (!parse_bool(value, newval))
5361                                         {
5362                                                 ereport(elevel,
5363                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5364                                                   errmsg("parameter \"%s\" requires a Boolean value",
5365                                                                  name)));
5366                                                 return 0;
5367                                         }
5368
5369                                         if (!call_bool_check_hook(conf, newval, newextra,
5370                                                                                           source, elevel))
5371                                                 return 0;
5372
5373                                         if (*newextra && freemem)
5374                                                 free(*newextra);
5375                                 }
5376                         }
5377                         break;
5378                 case PGC_INT:
5379                         {
5380                                 struct config_int *conf = (struct config_int *) record;
5381                                 int                     tmpnewval;
5382
5383                                 if (newval == NULL)
5384                                         newval = &tmpnewval;
5385
5386                                 if (value != NULL)
5387                                 {
5388                                         const char *hintmsg;
5389
5390                                         if (!parse_int(value, newval, conf->gen.flags, &hintmsg))
5391                                         {
5392                                                 ereport(elevel,
5393                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5394                                                  errmsg("invalid value for parameter \"%s\": \"%s\"",
5395                                                                 name, value),
5396                                                                  hintmsg ? errhint("%s", _(hintmsg)) : 0));
5397                                                 return 0;
5398                                         }
5399
5400                                         if (*((int *) newval) < conf->min || *((int *) newval) > conf->max)
5401                                         {
5402                                                 ereport(elevel,
5403                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5404                                                                  errmsg("%d is outside the valid range for parameter \"%s\" (%d .. %d)",
5405                                                         *((int *) newval), name, conf->min, conf->max)));
5406                                                 return 0;
5407                                         }
5408
5409                                         if (!call_int_check_hook(conf, newval, newextra,
5410                                                                                          source, elevel))
5411                                                 return 0;
5412
5413                                         if (*newextra && freemem)
5414                                                 free(*newextra);
5415                                 }
5416                         }
5417                         break;
5418                 case PGC_REAL:
5419                         {
5420                                 struct config_real *conf = (struct config_real *) record;
5421                                 double          tmpnewval;
5422
5423                                 if (newval == NULL)
5424                                         newval = &tmpnewval;
5425
5426                                 if (value != NULL)
5427                                 {
5428                                         if (!parse_real(value, newval))
5429                                         {
5430                                                 ereport(elevel,
5431                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5432                                                   errmsg("parameter \"%s\" requires a numeric value",
5433                                                                  name)));
5434                                                 return 0;
5435                                         }
5436
5437                                         if (*((double *) newval) < conf->min || *((double *) newval) > conf->max)
5438                                         {
5439                                                 ereport(elevel,
5440                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5441                                                                  errmsg("%g is outside the valid range for parameter \"%s\" (%g .. %g)",
5442                                                  *((double *) newval), name, conf->min, conf->max)));
5443                                                 return 0;
5444                                         }
5445
5446                                         if (!call_real_check_hook(conf, newval, newextra,
5447                                                                                           source, elevel))
5448                                                 return 0;
5449
5450                                         if (*newextra && freemem)
5451                                                 free(*newextra);
5452                                 }
5453                         }
5454                         break;
5455                 case PGC_STRING:
5456                         {
5457                                 struct config_string *conf = (struct config_string *) record;
5458                                 char       *tempPtr;
5459                                 char      **tmpnewval = newval;
5460
5461                                 if (newval == NULL)
5462                                         tmpnewval = &tempPtr;
5463
5464                                 if (value != NULL)
5465                                 {
5466                                         /*
5467                                          * The value passed by the caller could be transient, so
5468                                          * we always strdup it.
5469                                          */
5470                                         *tmpnewval = guc_strdup(elevel, value);
5471                                         if (*tmpnewval == NULL)
5472                                                 return 0;
5473
5474                                         /*
5475                                          * The only built-in "parsing" check we have is to apply
5476                                          * truncation if GUC_IS_NAME.
5477                                          */
5478                                         if (conf->gen.flags & GUC_IS_NAME)
5479                                                 truncate_identifier(*tmpnewval, strlen(*tmpnewval), true);
5480
5481                                         if (!call_string_check_hook(conf, tmpnewval, newextra,
5482                                                                                                 source, elevel))
5483                                         {
5484                                                 free(*tmpnewval);
5485                                                 return 0;
5486                                         }
5487
5488                                         /* Free the malloc'd data if any */
5489                                         if (freemem)
5490                                         {
5491                                                 if (*tmpnewval != NULL)
5492                                                         free(*tmpnewval);
5493                                                 if (*newextra != NULL)
5494                                                         free(*newextra);
5495                                         }
5496                                 }
5497                         }
5498                         break;
5499                 case PGC_ENUM:
5500                         {
5501                                 struct config_enum *conf = (struct config_enum *) record;
5502                                 int                     tmpnewval;
5503
5504                                 if (newval == NULL)
5505                                         newval = &tmpnewval;
5506
5507                                 if (value != NULL)
5508                                 {
5509                                         if (!config_enum_lookup_by_name(conf, value, newval))
5510                                         {
5511                                                 char       *hintmsg;
5512
5513                                                 hintmsg = config_enum_get_options(conf,
5514                                                                                                                 "Available values: ",
5515                                                                                                                   ".", ", ");
5516
5517                                                 ereport(ERROR,
5518                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5519                                                  errmsg("invalid value for parameter \"%s\": \"%s\"",
5520                                                                 name, value),
5521                                                                  hintmsg ? errhint("%s", _(hintmsg)) : 0));
5522
5523                                                 if (hintmsg != NULL)
5524                                                         pfree(hintmsg);
5525                                                 return 0;
5526                                         }
5527                                         if (!call_enum_check_hook(conf, newval, newextra,
5528                                                                                           source, LOG))
5529                                                 return 0;
5530
5531                                         if (*newextra && freemem)
5532                                                 free(*newextra);
5533                                 }
5534                         }
5535                         break;
5536         }
5537         return 1;
5538 }
5539
5540
5541 /*
5542  * Sets option `name' to given value.
5543  *
5544  * The value should be a string, which will be parsed and converted to
5545  * the appropriate data type.  The context and source parameters indicate
5546  * in which context this function is being called, so that it can apply the
5547  * access restrictions properly.
5548  *
5549  * If value is NULL, set the option to its default value (normally the
5550  * reset_val, but if source == PGC_S_DEFAULT we instead use the boot_val).
5551  *
5552  * action indicates whether to set the value globally in the session, locally
5553  * to the current top transaction, or just for the duration of a function call.
5554  *
5555  * If changeVal is false then don't really set the option but do all
5556  * the checks to see if it would work.
5557  *
5558  * elevel should normally be passed as zero, allowing this function to make
5559  * its standard choice of ereport level.  However some callers need to be
5560  * able to override that choice; they should pass the ereport level to use.
5561  *
5562  * Return value:
5563  *      +1: the value is valid and was successfully applied.
5564  *      0:      the name or value is invalid (but see below).
5565  *      -1: the value was not applied because of context, priority, or changeVal.
5566  *
5567  * If there is an error (non-existing option, invalid value) then an
5568  * ereport(ERROR) is thrown *unless* this is called for a source for which
5569  * we don't want an ERROR (currently, those are defaults, the config file,
5570  * and per-database or per-user settings, as well as callers who specify
5571  * a less-than-ERROR elevel).  In those cases we write a suitable error
5572  * message via ereport() and return 0.
5573  *
5574  * See also SetConfigOption for an external interface.
5575  */
5576 int
5577 set_config_option(const char *name, const char *value,
5578                                   GucContext context, GucSource source,
5579                                   GucAction action, bool changeVal, int elevel)
5580 {
5581         struct config_generic *record;
5582         bool            prohibitValueChange = false;
5583         bool            makeDefault;
5584
5585         if (elevel == 0)
5586         {
5587                 if (source == PGC_S_DEFAULT || source == PGC_S_FILE)
5588                 {
5589                         /*
5590                          * To avoid cluttering the log, only the postmaster bleats loudly
5591                          * about problems with the config file.
5592                          */
5593                         elevel = IsUnderPostmaster ? DEBUG3 : LOG;
5594                 }
5595                 else if (source == PGC_S_GLOBAL || source == PGC_S_DATABASE || source == PGC_S_USER ||
5596                                  source == PGC_S_DATABASE_USER)
5597                         elevel = WARNING;
5598                 else
5599                         elevel = ERROR;
5600         }
5601
5602         record = find_option(name, true, elevel);
5603         if (record == NULL)
5604         {
5605                 ereport(elevel,
5606                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
5607                            errmsg("unrecognized configuration parameter \"%s\"", name)));
5608                 return 0;
5609         }
5610
5611         /*
5612          * Check if the option can be set at this time. See guc.h for the precise
5613          * rules.
5614          */
5615         switch (record->context)
5616         {
5617                 case PGC_INTERNAL:
5618                         if (context != PGC_INTERNAL)
5619                         {
5620                                 ereport(elevel,
5621                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5622                                                  errmsg("parameter \"%s\" cannot be changed",
5623                                                                 name)));
5624                                 return 0;
5625                         }
5626                         break;
5627                 case PGC_POSTMASTER:
5628                         if (context == PGC_SIGHUP)
5629                         {
5630                                 /*
5631                                  * We are re-reading a PGC_POSTMASTER variable from
5632                                  * postgresql.conf.  We can't change the setting, so we should
5633                                  * give a warning if the DBA tries to change it.  However,
5634                                  * because of variant formats, canonicalization by check
5635                                  * hooks, etc, we can't just compare the given string directly
5636                                  * to what's stored.  Set a flag to check below after we have
5637                                  * the final storable value.
5638                                  */
5639                                 prohibitValueChange = true;
5640                         }
5641                         else if (context != PGC_POSTMASTER)
5642                         {
5643                                 ereport(elevel,
5644                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5645                                                  errmsg("parameter \"%s\" cannot be changed without restarting the server",
5646                                                                 name)));
5647                                 return 0;
5648                         }
5649                         break;
5650                 case PGC_SIGHUP:
5651                         if (context != PGC_SIGHUP && context != PGC_POSTMASTER)
5652                         {
5653                                 ereport(elevel,
5654                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5655                                                  errmsg("parameter \"%s\" cannot be changed now",
5656                                                                 name)));
5657                                 return 0;
5658                         }
5659
5660                         /*
5661                          * Hmm, the idea of the SIGHUP context is "ought to be global, but
5662                          * can be changed after postmaster start". But there's nothing
5663                          * that prevents a crafty administrator from sending SIGHUP
5664                          * signals to individual backends only.
5665                          */
5666                         break;
5667                 case PGC_BACKEND:
5668                         if (context == PGC_SIGHUP)
5669                         {
5670                                 /*
5671                                  * If a PGC_BACKEND parameter is changed in the config file,
5672                                  * we want to accept the new value in the postmaster (whence
5673                                  * it will propagate to subsequently-started backends), but
5674                                  * ignore it in existing backends.  This is a tad klugy, but
5675                                  * necessary because we don't re-read the config file during
5676                                  * backend start.
5677                                  *
5678                                  * In EXEC_BACKEND builds, this works differently: we load all
5679                                  * nondefault settings from the CONFIG_EXEC_PARAMS file during
5680                                  * backend start.  In that case we must accept PGC_SIGHUP
5681                                  * settings, so as to have the same value as if we'd forked
5682                                  * from the postmaster.  We detect this situation by checking
5683                                  * IsInitProcessingMode, which is a bit ugly, but it doesn't
5684                                  * seem worth passing down an explicit flag saying we're doing
5685                                  * read_nondefault_variables().
5686                                  */
5687 #ifdef EXEC_BACKEND
5688                                 if (IsUnderPostmaster && !IsInitProcessingMode())
5689                                         return -1;
5690 #else
5691                                 if (IsUnderPostmaster)
5692                                         return -1;
5693 #endif
5694                         }
5695                         else if (context != PGC_POSTMASTER && context != PGC_BACKEND &&
5696                                          source != PGC_S_CLIENT)
5697                         {
5698                                 ereport(elevel,
5699                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5700                                                  errmsg("parameter \"%s\" cannot be set after connection start",
5701                                                                 name)));
5702                                 return 0;
5703                         }
5704                         break;
5705                 case PGC_SUSET:
5706                         if (context == PGC_USERSET || context == PGC_BACKEND)
5707                         {
5708                                 ereport(elevel,
5709                                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
5710                                                  errmsg("permission denied to set parameter \"%s\"",
5711                                                                 name)));
5712                                 return 0;
5713                         }
5714                         break;
5715                 case PGC_USERSET:
5716                         /* always okay */
5717                         break;
5718         }
5719
5720         /*
5721          * Disallow changing GUC_NOT_WHILE_SEC_REST values if we are inside a
5722          * security restriction context.  We can reject this regardless of the GUC
5723          * context or source, mainly because sources that it might be reasonable
5724          * to override for won't be seen while inside a function.
5725          *
5726          * Note: variables marked GUC_NOT_WHILE_SEC_REST should usually be marked
5727          * GUC_NO_RESET_ALL as well, because ResetAllOptions() doesn't check this.
5728          * An exception might be made if the reset value is assumed to be "safe".
5729          *
5730          * Note: this flag is currently used for "session_authorization" and
5731          * "role".  We need to prohibit changing these inside a local userid
5732          * context because when we exit it, GUC won't be notified, leaving things
5733          * out of sync.  (This could be fixed by forcing a new GUC nesting level,
5734          * but that would change behavior in possibly-undesirable ways.)  Also, we
5735          * prohibit changing these in a security-restricted operation because
5736          * otherwise RESET could be used to regain the session user's privileges.
5737          */
5738         if (record->flags & GUC_NOT_WHILE_SEC_REST)
5739         {
5740                 if (InLocalUserIdChange())
5741                 {
5742                         /*
5743                          * Phrasing of this error message is historical, but it's the most
5744                          * common case.
5745                          */
5746                         ereport(elevel,
5747                                         (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
5748                                          errmsg("cannot set parameter \"%s\" within security-definer function",
5749                                                         name)));
5750                         return 0;
5751                 }
5752                 if (InSecurityRestrictedOperation())
5753                 {
5754                         ereport(elevel,
5755                                         (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
5756                                          errmsg("cannot set parameter \"%s\" within security-restricted operation",
5757                                                         name)));
5758                         return 0;
5759                 }
5760         }
5761
5762         /*
5763          * Should we set reset/stacked values?  (If so, the behavior is not
5764          * transactional.)      This is done either when we get a default value from
5765          * the database's/user's/client's default settings or when we reset a
5766          * value to its default.
5767          */
5768         makeDefault = changeVal && (source <= PGC_S_OVERRIDE) &&
5769                 ((value != NULL) || source == PGC_S_DEFAULT);
5770
5771         /*
5772          * Ignore attempted set if overridden by previously processed setting.
5773          * However, if changeVal is false then plow ahead anyway since we are
5774          * trying to find out if the value is potentially good, not actually use
5775          * it. Also keep going if makeDefault is true, since we may want to set
5776          * the reset/stacked values even if we can't set the variable itself.
5777          */
5778         if (record->source > source)
5779         {
5780                 if (changeVal && !makeDefault)
5781                 {
5782                         elog(DEBUG3, "\"%s\": setting ignored because previous source is higher priority",
5783                                  name);
5784                         return -1;
5785                 }
5786                 changeVal = false;
5787         }
5788
5789         /*
5790          * Evaluate value and set variable.
5791          */
5792         switch (record->vartype)
5793         {
5794                 case PGC_BOOL:
5795                         {
5796                                 struct config_bool *conf = (struct config_bool *) record;
5797                                 bool            newval;
5798                                 void       *newextra = NULL;
5799
5800                                 if (value)
5801                                 {
5802                                         if (!validate_conf_option(record, name, value, source,
5803                                                                                           elevel, false, &newval,
5804                                                                                           &newextra))
5805                                                 return 0;
5806                                 }
5807                                 else if (source == PGC_S_DEFAULT)
5808                                 {
5809                                         newval = conf->boot_val;
5810                                         if (!call_bool_check_hook(conf, &newval, &newextra,
5811                                                                                           source, elevel))
5812                                                 return 0;
5813                                 }
5814                                 else
5815                                 {
5816                                         newval = conf->reset_val;
5817                                         newextra = conf->reset_extra;
5818                                         source = conf->gen.reset_source;
5819                                         context = conf->gen.reset_scontext;
5820                                 }
5821
5822                                 if (prohibitValueChange)
5823                                 {
5824                                         if (*conf->variable != newval)
5825                                         {
5826                                                 ereport(elevel,
5827                                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5828                                                                  errmsg("parameter \"%s\" cannot be changed without restarting the server",
5829                                                                                 name)));
5830                                                 return 0;
5831                                         }
5832                                         return -1;
5833                                 }
5834
5835                                 if (changeVal)
5836                                 {
5837                                         /* Save old value to support transaction abort */
5838                                         if (!makeDefault)
5839                                                 push_old_value(&conf->gen, action);
5840
5841                                         if (conf->assign_hook)
5842                                                 (*conf->assign_hook) (newval, newextra);
5843                                         *conf->variable = newval;
5844                                         set_extra_field(&conf->gen, &conf->gen.extra,
5845                                                                         newextra);
5846                                         conf->gen.source = source;
5847                                         conf->gen.scontext = context;
5848                                 }
5849                                 if (makeDefault)
5850                                 {
5851                                         GucStack   *stack;
5852
5853                                         if (conf->gen.reset_source <= source)
5854                                         {
5855                                                 conf->reset_val = newval;
5856                                                 set_extra_field(&conf->gen, &conf->reset_extra,
5857                                                                                 newextra);
5858                                                 conf->gen.reset_source = source;
5859                                                 conf->gen.reset_scontext = context;
5860                                         }
5861                                         for (stack = conf->gen.stack; stack; stack = stack->prev)
5862                                         {
5863                                                 if (stack->source <= source)
5864                                                 {
5865                                                         stack->prior.val.boolval = newval;
5866                                                         set_extra_field(&conf->gen, &stack->prior.extra,
5867                                                                                         newextra);
5868                                                         stack->source = source;
5869                                                         stack->scontext = context;
5870                                                 }
5871                                         }
5872                                 }
5873
5874                                 /* Perhaps we didn't install newextra anywhere */
5875                                 if (newextra && !extra_field_used(&conf->gen, newextra))
5876                                         free(newextra);
5877                                 break;
5878                         }
5879
5880                 case PGC_INT:
5881                         {
5882                                 struct config_int *conf = (struct config_int *) record;
5883                                 int                     newval;
5884                                 void       *newextra = NULL;
5885
5886                                 if (value)
5887                                 {
5888                                         if (!validate_conf_option(record, name, value, source,
5889                                                                                           elevel, false, &newval,
5890                                                                                           &newextra))
5891                                                 return 0;
5892                                 }
5893                                 else if (source == PGC_S_DEFAULT)
5894                                 {
5895                                         newval = conf->boot_val;
5896                                         if (!call_int_check_hook(conf, &newval, &newextra,
5897                                                                                          source, elevel))
5898                                                 return 0;
5899                                 }
5900                                 else
5901                                 {
5902                                         newval = conf->reset_val;
5903                                         newextra = conf->reset_extra;
5904                                         source = conf->gen.reset_source;
5905                                         context = conf->gen.reset_scontext;
5906                                 }
5907
5908                                 if (prohibitValueChange)
5909                                 {
5910                                         if (*conf->variable != newval)
5911                                         {
5912                                                 ereport(elevel,
5913                                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5914                                                                  errmsg("parameter \"%s\" cannot be changed without restarting the server",
5915                                                                                 name)));
5916                                                 return 0;
5917                                         }
5918                                         return -1;
5919                                 }
5920
5921                                 if (changeVal)
5922                                 {
5923                                         /* Save old value to support transaction abort */
5924                                         if (!makeDefault)
5925                                                 push_old_value(&conf->gen, action);
5926
5927                                         if (conf->assign_hook)
5928                                                 (*conf->assign_hook) (newval, newextra);
5929                                         *conf->variable = newval;
5930                                         set_extra_field(&conf->gen, &conf->gen.extra,
5931                                                                         newextra);
5932                                         conf->gen.source = source;
5933                                         conf->gen.scontext = context;
5934                                 }
5935                                 if (makeDefault)
5936                                 {
5937                                         GucStack   *stack;
5938
5939                                         if (conf->gen.reset_source <= source)
5940                                         {
5941                                                 conf->reset_val = newval;
5942                                                 set_extra_field(&conf->gen, &conf->reset_extra,
5943                                                                                 newextra);
5944                                                 conf->gen.reset_source = source;
5945                                                 conf->gen.reset_scontext = context;
5946                                         }
5947                                         for (stack = conf->gen.stack; stack; stack = stack->prev)
5948                                         {
5949                                                 if (stack->source <= source)
5950                                                 {
5951                                                         stack->prior.val.intval = newval;
5952                                                         set_extra_field(&conf->gen, &stack->prior.extra,
5953                                                                                         newextra);
5954                                                         stack->source = source;
5955                                                         stack->scontext = context;
5956                                                 }
5957                                         }
5958                                 }
5959
5960                                 /* Perhaps we didn't install newextra anywhere */
5961                                 if (newextra && !extra_field_used(&conf->gen, newextra))
5962                                         free(newextra);
5963                                 break;
5964                         }
5965
5966                 case PGC_REAL:
5967                         {
5968                                 struct config_real *conf = (struct config_real *) record;
5969                                 double          newval;
5970                                 void       *newextra = NULL;
5971
5972                                 if (value)
5973                                 {
5974                                         if (!validate_conf_option(record, name, value, source,
5975                                                                                           elevel, false, &newval,
5976                                                                                           &newextra))
5977                                                 return 0;
5978                                 }
5979                                 else if (source == PGC_S_DEFAULT)
5980                                 {
5981                                         newval = conf->boot_val;
5982                                         if (!call_real_check_hook(conf, &newval, &newextra,
5983                                                                                           source, elevel))
5984                                                 return 0;
5985                                 }
5986                                 else
5987                                 {
5988                                         newval = conf->reset_val;
5989                                         newextra = conf->reset_extra;
5990                                         source = conf->gen.reset_source;
5991                                         context = conf->gen.reset_scontext;
5992                                 }
5993
5994                                 if (prohibitValueChange)
5995                                 {
5996                                         if (*conf->variable != newval)
5997                                         {
5998                                                 ereport(elevel,
5999                                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
6000                                                                  errmsg("parameter \"%s\" cannot be changed without restarting the server",
6001                                                                                 name)));
6002                                                 return 0;
6003                                         }
6004                                         return -1;
6005                                 }
6006
6007                                 if (changeVal)
6008                                 {
6009                                         /* Save old value to support transaction abort */
6010                                         if (!makeDefault)
6011                                                 push_old_value(&conf->gen, action);
6012
6013                                         if (conf->assign_hook)
6014                                                 (*conf->assign_hook) (newval, newextra);
6015                                         *conf->variable = newval;
6016                                         set_extra_field(&conf->gen, &conf->gen.extra,
6017                                                                         newextra);
6018                                         conf->gen.source = source;
6019                                         conf->gen.scontext = context;
6020                                 }
6021                                 if (makeDefault)
6022                                 {
6023                                         GucStack   *stack;
6024
6025                                         if (conf->gen.reset_source <= source)
6026                                         {
6027                                                 conf->reset_val = newval;
6028                                                 set_extra_field(&conf->gen, &conf->reset_extra,
6029                                                                                 newextra);
6030                                                 conf->gen.reset_source = source;
6031                                                 conf->gen.reset_scontext = context;
6032                                         }
6033                                         for (stack = conf->gen.stack; stack; stack = stack->prev)
6034                                         {
6035                                                 if (stack->source <= source)
6036                                                 {
6037                                                         stack->prior.val.realval = newval;
6038                                                         set_extra_field(&conf->gen, &stack->prior.extra,
6039                                                                                         newextra);
6040                                                         stack->source = source;
6041                                                         stack->scontext = context;
6042                                                 }
6043                                         }
6044                                 }
6045
6046                                 /* Perhaps we didn't install newextra anywhere */
6047                                 if (newextra && !extra_field_used(&conf->gen, newextra))
6048                                         free(newextra);
6049                                 break;
6050                         }
6051
6052                 case PGC_STRING:
6053                         {
6054                                 struct config_string *conf = (struct config_string *) record;
6055                                 char       *newval;
6056                                 void       *newextra = NULL;
6057
6058                                 if (value)
6059                                 {
6060                                         if (!validate_conf_option(record, name, value, source,
6061                                                                                           elevel, false, &newval,
6062                                                                                           &newextra))
6063                                                 return 0;
6064                                 }
6065                                 else if (source == PGC_S_DEFAULT)
6066                                 {
6067                                         /* non-NULL boot_val must always get strdup'd */
6068                                         if (conf->boot_val != NULL)
6069                                         {
6070                                                 newval = guc_strdup(elevel, conf->boot_val);
6071                                                 if (newval == NULL)
6072                                                         return 0;
6073                                         }
6074                                         else
6075                                                 newval = NULL;
6076
6077                                         if (!call_string_check_hook(conf, &newval, &newextra,
6078                                                                                                 source, elevel))
6079                                         {
6080                                                 free(newval);
6081                                                 return 0;
6082                                         }
6083                                 }
6084                                 else
6085                                 {
6086                                         /*
6087                                          * strdup not needed, since reset_val is already under
6088                                          * guc.c's control
6089                                          */
6090                                         newval = conf->reset_val;
6091                                         newextra = conf->reset_extra;
6092                                         source = conf->gen.reset_source;
6093                                         context = conf->gen.reset_scontext;
6094                                 }
6095
6096                                 if (prohibitValueChange)
6097                                 {
6098                                         /* newval shouldn't be NULL, so we're a bit sloppy here */
6099                                         if (*conf->variable == NULL || newval == NULL ||
6100                                                 strcmp(*conf->variable, newval) != 0)
6101                                         {
6102                                                 ereport(elevel,
6103                                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
6104                                                                  errmsg("parameter \"%s\" cannot be changed without restarting the server",
6105                                                                                 name)));
6106                                                 return 0;
6107                                         }
6108                                         return -1;
6109                                 }
6110
6111                                 if (changeVal)
6112                                 {
6113                                         /* Save old value to support transaction abort */
6114                                         if (!makeDefault)
6115                                                 push_old_value(&conf->gen, action);
6116
6117                                         if (conf->assign_hook)
6118                                                 (*conf->assign_hook) (newval, newextra);
6119                                         set_string_field(conf, conf->variable, newval);
6120                                         set_extra_field(&conf->gen, &conf->gen.extra,
6121                                                                         newextra);
6122                                         conf->gen.source = source;
6123                                         conf->gen.scontext = context;
6124                                 }
6125
6126                                 if (makeDefault)
6127                                 {
6128                                         GucStack   *stack;
6129
6130                                         if (conf->gen.reset_source <= source)
6131                                         {
6132                                                 set_string_field(conf, &conf->reset_val, newval);
6133                                                 set_extra_field(&conf->gen, &conf->reset_extra,
6134                                                                                 newextra);
6135                                                 conf->gen.reset_source = source;
6136                                                 conf->gen.reset_scontext = context;
6137                                         }
6138                                         for (stack = conf->gen.stack; stack; stack = stack->prev)
6139                                         {
6140                                                 if (stack->source <= source)
6141                                                 {
6142                                                         set_string_field(conf, &stack->prior.val.stringval,
6143                                                                                          newval);
6144                                                         set_extra_field(&conf->gen, &stack->prior.extra,
6145                                                                                         newextra);
6146                                                         stack->source = source;
6147                                                         stack->scontext = context;
6148                                                 }
6149                                         }
6150                                 }
6151
6152                                 /* Perhaps we didn't install newval anywhere */
6153                                 if (newval && !string_field_used(conf, newval))
6154                                         free(newval);
6155                                 /* Perhaps we didn't install newextra anywhere */
6156                                 if (newextra && !extra_field_used(&conf->gen, newextra))
6157                                         free(newextra);
6158                                 break;
6159                         }
6160
6161                 case PGC_ENUM:
6162                         {
6163                                 struct config_enum *conf = (struct config_enum *) record;
6164                                 int                     newval;
6165                                 void       *newextra = NULL;
6166
6167                                 if (value)
6168                                 {
6169                                         if (!validate_conf_option(record, name, value, source,
6170                                                                                           elevel, false, &newval,
6171                                                                                           &newextra))
6172                                                 return 0;
6173                                 }
6174                                 else if (source == PGC_S_DEFAULT)
6175                                 {
6176                                         newval = conf->boot_val;
6177                                         if (!call_enum_check_hook(conf, &newval, &newextra,
6178                                                                                           source, elevel))
6179                                                 return 0;
6180                                 }
6181                                 else
6182                                 {
6183                                         newval = conf->reset_val;
6184                                         newextra = conf->reset_extra;
6185                                         source = conf->gen.reset_source;
6186                                         context = conf->gen.reset_scontext;
6187                                 }
6188
6189                                 if (prohibitValueChange)
6190                                 {
6191                                         if (*conf->variable != newval)
6192                                         {
6193                                                 ereport(elevel,
6194                                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
6195                                                                  errmsg("parameter \"%s\" cannot be changed without restarting the server",
6196                                                                                 name)));
6197                                                 return 0;
6198                                         }
6199                                         return -1;
6200                                 }
6201
6202                                 if (changeVal)
6203                                 {
6204                                         /* Save old value to support transaction abort */
6205                                         if (!makeDefault)
6206                                                 push_old_value(&conf->gen, action);
6207
6208                                         if (conf->assign_hook)
6209                                                 (*conf->assign_hook) (newval, newextra);
6210                                         *conf->variable = newval;
6211                                         set_extra_field(&conf->gen, &conf->gen.extra,
6212                                                                         newextra);
6213                                         conf->gen.source = source;
6214                                         conf->gen.scontext = context;
6215                                 }
6216                                 if (makeDefault)
6217                                 {
6218                                         GucStack   *stack;
6219
6220                                         if (conf->gen.reset_source <= source)
6221                                         {
6222                                                 conf->reset_val = newval;
6223                                                 set_extra_field(&conf->gen, &conf->reset_extra,
6224                                                                                 newextra);
6225                                                 conf->gen.reset_source = source;
6226                                                 conf->gen.reset_scontext = context;
6227                                         }
6228                                         for (stack = conf->gen.stack; stack; stack = stack->prev)
6229                                         {
6230                                                 if (stack->source <= source)
6231                                                 {
6232                                                         stack->prior.val.enumval = newval;
6233                                                         set_extra_field(&conf->gen, &stack->prior.extra,
6234                                                                                         newextra);
6235                                                         stack->source = source;
6236                                                         stack->scontext = context;
6237                                                 }
6238                                         }
6239                                 }
6240
6241                                 /* Perhaps we didn't install newextra anywhere */
6242                                 if (newextra && !extra_field_used(&conf->gen, newextra))
6243                                         free(newextra);
6244                                 break;
6245                         }
6246         }
6247
6248         if (changeVal && (record->flags & GUC_REPORT))
6249                 ReportGUCOption(record);
6250
6251         return changeVal ? 1 : -1;
6252 }
6253
6254
6255 /*
6256  * Set the fields for source file and line number the setting came from.
6257  */
6258 static void
6259 set_config_sourcefile(const char *name, char *sourcefile, int sourceline)
6260 {
6261         struct config_generic *record;
6262         int                     elevel;
6263
6264         /*
6265          * To avoid cluttering the log, only the postmaster bleats loudly about
6266          * problems with the config file.
6267          */
6268         elevel = IsUnderPostmaster ? DEBUG3 : LOG;
6269
6270         record = find_option(name, true, elevel);
6271         /* should not happen */
6272         if (record == NULL)
6273                 elog(ERROR, "unrecognized configuration parameter \"%s\"", name);
6274
6275         sourcefile = guc_strdup(elevel, sourcefile);
6276         if (record->sourcefile)
6277                 free(record->sourcefile);
6278         record->sourcefile = sourcefile;
6279         record->sourceline = sourceline;
6280 }
6281
6282 /*
6283  * Set a config option to the given value.
6284  *
6285  * See also set_config_option; this is just the wrapper to be called from
6286  * outside GUC.  (This function should be used when possible, because its API
6287  * is more stable than set_config_option's.)
6288  *
6289  * Note: there is no support here for setting source file/line, as it
6290  * is currently not needed.
6291  */
6292 void
6293 SetConfigOption(const char *name, const char *value,
6294                                 GucContext context, GucSource source)
6295 {
6296         (void) set_config_option(name, value, context, source,
6297                                                          GUC_ACTION_SET, true, 0);
6298 }
6299
6300
6301
6302 /*
6303  * Fetch the current value of the option `name', as a string.
6304  *
6305  * If the option doesn't exist, return NULL if missing_ok is true (NOTE that
6306  * this cannot be distinguished from a string variable with a NULL value!),
6307  * otherwise throw an ereport and don't return.
6308  *
6309  * If restrict_superuser is true, we also enforce that only superusers can
6310  * see GUC_SUPERUSER_ONLY variables.  This should only be passed as true
6311  * in user-driven calls.
6312  *
6313  * The string is *not* allocated for modification and is really only
6314  * valid until the next call to configuration related functions.
6315  */
6316 const char *
6317 GetConfigOption(const char *name, bool missing_ok, bool restrict_superuser)
6318 {
6319         struct config_generic *record;
6320         static char buffer[256];
6321
6322         record = find_option(name, false, ERROR);
6323         if (record == NULL)
6324         {
6325                 if (missing_ok)
6326                         return NULL;
6327                 ereport(ERROR,
6328                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
6329                                  errmsg("unrecognized configuration parameter \"%s\"",
6330                                                 name)));
6331         }
6332         if (restrict_superuser &&
6333                 (record->flags & GUC_SUPERUSER_ONLY) &&
6334                 !superuser())
6335                 ereport(ERROR,
6336                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6337                                  errmsg("must be superuser to examine \"%s\"", name)));
6338
6339         switch (record->vartype)
6340         {
6341                 case PGC_BOOL:
6342                         return *((struct config_bool *) record)->variable ? "on" : "off";
6343
6344                 case PGC_INT:
6345                         snprintf(buffer, sizeof(buffer), "%d",
6346                                          *((struct config_int *) record)->variable);
6347                         return buffer;
6348
6349                 case PGC_REAL:
6350                         snprintf(buffer, sizeof(buffer), "%g",
6351                                          *((struct config_real *) record)->variable);
6352                         return buffer;
6353
6354                 case PGC_STRING:
6355                         return *((struct config_string *) record)->variable;
6356
6357                 case PGC_ENUM:
6358                         return config_enum_lookup_by_value((struct config_enum *) record,
6359                                                                  *((struct config_enum *) record)->variable);
6360         }
6361         return NULL;
6362 }
6363
6364 /*
6365  * Get the RESET value associated with the given option.
6366  *
6367  * Note: this is not re-entrant, due to use of static result buffer;
6368  * not to mention that a string variable could have its reset_val changed.
6369  * Beware of assuming the result value is good for very long.
6370  */
6371 const char *
6372 GetConfigOptionResetString(const char *name)
6373 {
6374         struct config_generic *record;
6375         static char buffer[256];
6376
6377         record = find_option(name, false, ERROR);
6378         if (record == NULL)
6379                 ereport(ERROR,
6380                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
6381                            errmsg("unrecognized configuration parameter \"%s\"", name)));
6382         if ((record->flags & GUC_SUPERUSER_ONLY) && !superuser())
6383                 ereport(ERROR,
6384                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6385                                  errmsg("must be superuser to examine \"%s\"", name)));
6386
6387         switch (record->vartype)
6388         {
6389                 case PGC_BOOL:
6390                         return ((struct config_bool *) record)->reset_val ? "on" : "off";
6391
6392                 case PGC_INT:
6393                         snprintf(buffer, sizeof(buffer), "%d",
6394                                          ((struct config_int *) record)->reset_val);
6395                         return buffer;
6396
6397                 case PGC_REAL:
6398                         snprintf(buffer, sizeof(buffer), "%g",
6399                                          ((struct config_real *) record)->reset_val);
6400                         return buffer;
6401
6402                 case PGC_STRING:
6403                         return ((struct config_string *) record)->reset_val;
6404
6405                 case PGC_ENUM:
6406                         return config_enum_lookup_by_value((struct config_enum *) record,
6407                                                                  ((struct config_enum *) record)->reset_val);
6408         }
6409         return NULL;
6410 }
6411
6412
6413 /*
6414  * flatten_set_variable_args
6415  *              Given a parsenode List as emitted by the grammar for SET,
6416  *              convert to the flat string representation used by GUC.
6417  *
6418  * We need to be told the name of the variable the args are for, because
6419  * the flattening rules vary (ugh).
6420  *
6421  * The result is NULL if args is NIL (ie, SET ... TO DEFAULT), otherwise
6422  * a palloc'd string.
6423  */
6424 static char *
6425 flatten_set_variable_args(const char *name, List *args)
6426 {
6427         struct config_generic *record;
6428         int                     flags;
6429         StringInfoData buf;
6430         ListCell   *l;
6431
6432         /* Fast path if just DEFAULT */
6433         if (args == NIL)
6434                 return NULL;
6435
6436         /*
6437          * Get flags for the variable; if it's not known, use default flags.
6438          * (Caller might throw error later, but not our business to do so here.)
6439          */
6440         record = find_option(name, false, WARNING);
6441         if (record)
6442                 flags = record->flags;
6443         else
6444                 flags = 0;
6445
6446         /* Complain if list input and non-list variable */
6447         if ((flags & GUC_LIST_INPUT) == 0 &&
6448                 list_length(args) != 1)
6449                 ereport(ERROR,
6450                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6451                                  errmsg("SET %s takes only one argument", name)));
6452
6453         initStringInfo(&buf);
6454
6455         /*
6456          * Each list member may be a plain A_Const node, or an A_Const within a
6457          * TypeCast; the latter case is supported only for ConstInterval arguments
6458          * (for SET TIME ZONE).
6459          */
6460         foreach(l, args)
6461         {
6462                 Node       *arg = (Node *) lfirst(l);
6463                 char       *val;
6464                 TypeName   *typeName = NULL;
6465                 A_Const    *con;
6466
6467                 if (l != list_head(args))
6468                         appendStringInfoString(&buf, ", ");
6469
6470                 if (IsA(arg, TypeCast))
6471                 {
6472                         TypeCast   *tc = (TypeCast *) arg;
6473
6474                         arg = tc->arg;
6475                         typeName = tc->typeName;
6476                 }
6477
6478                 if (!IsA(arg, A_Const))
6479                         elog(ERROR, "unrecognized node type: %d", (int) nodeTag(arg));
6480                 con = (A_Const *) arg;
6481
6482                 switch (nodeTag(&con->val))
6483                 {
6484                         case T_Integer:
6485                                 appendStringInfo(&buf, "%ld", intVal(&con->val));
6486                                 break;
6487                         case T_Float:
6488                                 /* represented as a string, so just copy it */
6489                                 appendStringInfoString(&buf, strVal(&con->val));
6490                                 break;
6491                         case T_String:
6492                                 val = strVal(&con->val);
6493                                 if (typeName != NULL)
6494                                 {
6495                                         /*
6496                                          * Must be a ConstInterval argument for TIME ZONE. Coerce
6497                                          * to interval and back to normalize the value and account
6498                                          * for any typmod.
6499                                          */
6500                                         Oid                     typoid;
6501                                         int32           typmod;
6502                                         Datum           interval;
6503                                         char       *intervalout;
6504
6505                                         typenameTypeIdAndMod(NULL, typeName, &typoid, &typmod);
6506                                         Assert(typoid == INTERVALOID);
6507
6508                                         interval =
6509                                                 DirectFunctionCall3(interval_in,
6510                                                                                         CStringGetDatum(val),
6511                                                                                         ObjectIdGetDatum(InvalidOid),
6512                                                                                         Int32GetDatum(typmod));
6513
6514                                         intervalout =
6515                                                 DatumGetCString(DirectFunctionCall1(interval_out,
6516                                                                                                                         interval));
6517                                         appendStringInfo(&buf, "INTERVAL '%s'", intervalout);
6518                                 }
6519                                 else
6520                                 {
6521                                         /*
6522                                          * Plain string literal or identifier.  For quote mode,
6523                                          * quote it if it's not a vanilla identifier.
6524                                          */
6525                                         if (flags & GUC_LIST_QUOTE)
6526                                                 appendStringInfoString(&buf, quote_identifier(val));
6527                                         else
6528                                                 appendStringInfoString(&buf, val);
6529                                 }
6530                                 break;
6531                         default:
6532                                 elog(ERROR, "unrecognized node type: %d",
6533                                          (int) nodeTag(&con->val));
6534                                 break;
6535                 }
6536         }
6537
6538         return buf.data;
6539 }
6540
6541 /*
6542  * Write updated configuration parameter values into a temporary file.
6543  * This function traverses the list of parameters and quotes the string
6544  * values before writing them.
6545  */
6546 static void
6547 write_auto_conf_file(int fd, const char *filename, ConfigVariable **head_p)
6548 {
6549         ConfigVariable *item;
6550         StringInfoData buf;
6551
6552         initStringInfo(&buf);
6553         appendStringInfoString(&buf, "# Do not edit this file manually!\n");
6554         appendStringInfoString(&buf, "# It will be overwritten by ALTER SYSTEM command.\n");
6555
6556         /*
6557          * write the file header message before contents, so that if there is no
6558          * item it can contain message
6559          */
6560         if (write(fd, buf.data, buf.len) < 0)
6561                 ereport(ERROR,
6562                                 (errmsg("failed to write to \"%s\" file", filename)));
6563         resetStringInfo(&buf);
6564
6565         /*
6566          * traverse the list of parameters, quote the string parameter and write
6567          * it to file. Once all parameters are written fsync the file.
6568          */
6569
6570         for (item = *head_p; item != NULL; item = item->next)
6571         {
6572                 char       *escaped;
6573
6574                 appendStringInfoString(&buf, item->name);
6575                 appendStringInfoString(&buf, " = ");
6576
6577                 appendStringInfoString(&buf, "\'");
6578                 escaped = escape_single_quotes_ascii(item->value);
6579                 appendStringInfoString(&buf, escaped);
6580                 free(escaped);
6581                 appendStringInfoString(&buf, "\'");
6582
6583                 appendStringInfoString(&buf, "\n");
6584
6585                 if (write(fd, buf.data, buf.len) < 0)
6586                         ereport(ERROR,
6587                                         (errmsg("failed to write to \"%s\" file", filename)));
6588                 resetStringInfo(&buf);
6589         }
6590
6591         if (pg_fsync(fd) != 0)
6592                 ereport(ERROR,
6593                                 (errcode_for_file_access(),
6594                                  errmsg("could not fsync file \"%s\": %m", filename)));
6595
6596         pfree(buf.data);
6597 }
6598
6599
6600 /*
6601  * This function takes list of all configuration parameters in
6602  * PG_AUTOCONF_FILENAME and parameter to be updated as input arguments and
6603  * replace the updated configuration parameter value in a list. If the
6604  * parameter to be updated is new then it is appended to the list of
6605  * parameters.
6606  */
6607 static void
6608 replace_auto_config_value(ConfigVariable **head_p, ConfigVariable **tail_p,
6609                                                   char *config_file,
6610                                                   char *name, char *value)
6611 {
6612         ConfigVariable *item,
6613                            *prev = NULL;
6614
6615         if (*head_p != NULL)
6616         {
6617                 for (item = *head_p; item != NULL; item = item->next)
6618                 {
6619                         if (strcmp(item->name, name) == 0)
6620                         {
6621                                 pfree(item->value);
6622                                 if (value != NULL)
6623                                         /* update the parameter value */
6624                                         item->value = pstrdup(value);
6625                                 else
6626                                 {
6627                                         /* delete the configuration parameter from list */
6628                                         if (*head_p == item)
6629                                                 *head_p = item->next;
6630                                         else
6631                                                 prev->next = item->next;
6632
6633                                         if (*tail_p == item)
6634                                                 *tail_p = prev;
6635
6636                                         pfree(item->name);
6637                                         pfree(item->filename);
6638                                         pfree(item);
6639                                 }
6640                                 return;
6641                         }
6642                         prev = item;
6643                 }
6644         }
6645
6646         if (value == NULL)
6647                 return;
6648
6649         item = palloc(sizeof *item);
6650         item->name = pstrdup(name);
6651         item->value = pstrdup(value);
6652         item->filename = pstrdup(config_file);
6653         item->next = NULL;
6654
6655         if (*head_p == NULL)
6656         {
6657                 item->sourceline = 1;
6658                 *head_p = item;
6659         }
6660         else
6661         {
6662                 item->sourceline = (*tail_p)->sourceline + 1;
6663                 (*tail_p)->next = item;
6664         }
6665
6666         *tail_p = item;
6667
6668         return;
6669 }
6670
6671
6672 /*
6673  * Persist the configuration parameter value.
6674  *
6675  * This function takes all previous configuration parameters
6676  * set by ALTER SYSTEM command and the currently set ones
6677  * and write them all to the automatic configuration file.
6678  *
6679  * The configuration parameters are written to a temporary
6680  * file then renamed to the final name.
6681  *
6682  * An LWLock is used to serialize writing to the same file.
6683  *
6684  * In case of an error, we leave the original automatic
6685  * configuration file (PG_AUTOCONF_FILENAME) intact.
6686  */
6687 void
6688 AlterSystemSetConfigFile(AlterSystemStmt *altersysstmt)
6689 {
6690         char       *name;
6691         char       *value;
6692         int                     Tmpfd = -1;
6693         FILE       *infile;
6694         struct config_generic *record;
6695         ConfigVariable *head = NULL;
6696         ConfigVariable *tail = NULL;
6697         char            AutoConfFileName[MAXPGPATH];
6698         char            AutoConfTmpFileName[MAXPGPATH];
6699         struct stat st;
6700         void       *newextra = NULL;
6701
6702         if (!superuser())
6703                 ereport(ERROR,
6704                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6705                          (errmsg("must be superuser to execute ALTER SYSTEM command"))));
6706
6707         /*
6708          * Validate the name and arguments [value1, value2 ... ].
6709          */
6710         name = altersysstmt->setstmt->name;
6711
6712         switch (altersysstmt->setstmt->kind)
6713         {
6714                 case VAR_SET_VALUE:
6715                         value = ExtractSetVariableArgs(altersysstmt->setstmt);
6716                         break;
6717
6718                 case VAR_SET_DEFAULT:
6719                         value = NULL;
6720                         break;
6721                 default:
6722                         elog(ERROR, "unrecognized alter system stmt type: %d",
6723                                  altersysstmt->setstmt->kind);
6724                         break;
6725         }
6726
6727         record = find_option(name, false, LOG);
6728         if (record == NULL)
6729                 ereport(ERROR,
6730                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
6731                            errmsg("unrecognized configuration parameter \"%s\"", name)));
6732
6733         if ((record->context == PGC_INTERNAL) ||
6734                 (record->flags & GUC_DISALLOW_IN_FILE))
6735                 ereport(ERROR,
6736                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
6737                                  errmsg("parameter \"%s\" cannot be changed",
6738                                                 name)));
6739
6740         if (!validate_conf_option(record, name, value, PGC_S_FILE,
6741                                                           ERROR, true, NULL,
6742                                                           &newextra))
6743                 ereport(ERROR,
6744                 (errmsg("invalid value for parameter \"%s\": \"%s\"", name, value)));
6745
6746
6747         /*
6748          * Use data directory as reference path for PG_AUTOCONF_FILENAME and its
6749          * corresponding temporary file.
6750          */
6751         join_path_components(AutoConfFileName, data_directory, PG_AUTOCONF_FILENAME);
6752         canonicalize_path(AutoConfFileName);
6753         snprintf(AutoConfTmpFileName, sizeof(AutoConfTmpFileName), "%s.%s",
6754                          AutoConfFileName,
6755                          "tmp");
6756
6757         /*
6758          * One backend is allowed to operate on file PG_AUTOCONF_FILENAME, to
6759          * ensure that we need to update the contents of the file with
6760          * AutoFileLock. To ensure crash safety, first the contents are written to
6761          * a temporary file which is then renameed to PG_AUTOCONF_FILENAME. In
6762          * case there exists a temp file from previous crash, that can be reused.
6763          */
6764
6765         LWLockAcquire(AutoFileLock, LW_EXCLUSIVE);
6766
6767         Tmpfd = open(AutoConfTmpFileName, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR);
6768         if (Tmpfd < 0)
6769                 ereport(ERROR,
6770                                 (errcode_for_file_access(),
6771                                  errmsg("failed to open auto conf temp file \"%s\": %m ",
6772                                                 AutoConfTmpFileName)));
6773
6774         PG_TRY();
6775         {
6776                 if (stat(AutoConfFileName, &st) == 0)
6777                 {
6778                         /* open file PG_AUTOCONF_FILENAME */
6779                         infile = AllocateFile(AutoConfFileName, "r");
6780                         if (infile == NULL)
6781                                 ereport(ERROR,
6782                                                 (errmsg("failed to open auto conf file \"%s\": %m ",
6783                                                                 AutoConfFileName)));
6784
6785                         /* parse it */
6786                         ParseConfigFp(infile, AutoConfFileName, 0, LOG, &head, &tail);
6787
6788                         FreeFile(infile);
6789                 }
6790
6791                 /*
6792                  * replace with new value if the configuration parameter already
6793                  * exists OR add it as a new cofiguration parameter in the file.
6794                  */
6795                 replace_auto_config_value(&head, &tail, AutoConfFileName, name, value);
6796
6797                 /* Write and sync the new contents to the temporary file */
6798                 write_auto_conf_file(Tmpfd, AutoConfTmpFileName, &head);
6799
6800                 close(Tmpfd);
6801                 Tmpfd = -1;
6802
6803                 /*
6804                  * As the rename is atomic operation, if any problem occurs after this
6805                  * at max it can loose the parameters set by last ALTER SYSTEM
6806                  * command.
6807                  */
6808                 if (rename(AutoConfTmpFileName, AutoConfFileName) < 0)
6809                         ereport(ERROR,
6810                                         (errcode_for_file_access(),
6811                                          errmsg("could not rename file \"%s\" to \"%s\" : %m",
6812                                                         AutoConfTmpFileName, AutoConfFileName)));
6813         }
6814         PG_CATCH();
6815         {
6816                 if (Tmpfd >= 0)
6817                         close(Tmpfd);
6818
6819                 unlink(AutoConfTmpFileName);
6820                 FreeConfigVariables(head);
6821                 PG_RE_THROW();
6822         }
6823         PG_END_TRY();
6824
6825         FreeConfigVariables(head);
6826         LWLockRelease(AutoFileLock);
6827         return;
6828 }
6829
6830 /*
6831  * SET command
6832  */
6833 void
6834 ExecSetVariableStmt(VariableSetStmt *stmt, bool isTopLevel)
6835 {
6836         GucAction       action = stmt->is_local ? GUC_ACTION_LOCAL : GUC_ACTION_SET;
6837
6838         switch (stmt->kind)
6839         {
6840                 case VAR_SET_VALUE:
6841                 case VAR_SET_CURRENT:
6842                         if (stmt->is_local)
6843                                 WarnNoTransactionChain(isTopLevel, "SET LOCAL");
6844                         (void) set_config_option(stmt->name,
6845                                                                          ExtractSetVariableArgs(stmt),
6846                                                                          (superuser() ? PGC_SUSET : PGC_USERSET),
6847                                                                          PGC_S_SESSION,
6848                                                                          action,
6849                                                                          true,
6850                                                                          0);
6851                         break;
6852                 case VAR_SET_MULTI:
6853
6854                         /*
6855                          * Special-case SQL syntaxes.  The TRANSACTION and SESSION
6856                          * CHARACTERISTICS cases effectively set more than one variable
6857                          * per statement.  TRANSACTION SNAPSHOT only takes one argument,
6858                          * but we put it here anyway since it's a special case and not
6859                          * related to any GUC variable.
6860                          */
6861                         if (strcmp(stmt->name, "TRANSACTION") == 0)
6862                         {
6863                                 ListCell   *head;
6864
6865                                 WarnNoTransactionChain(isTopLevel, "SET TRANSACTION");
6866
6867                                 foreach(head, stmt->args)
6868                                 {
6869                                         DefElem    *item = (DefElem *) lfirst(head);
6870
6871                                         if (strcmp(item->defname, "transaction_isolation") == 0)
6872                                                 SetPGVariable("transaction_isolation",
6873                                                                           list_make1(item->arg), stmt->is_local);
6874                                         else if (strcmp(item->defname, "transaction_read_only") == 0)
6875                                                 SetPGVariable("transaction_read_only",
6876                                                                           list_make1(item->arg), stmt->is_local);
6877                                         else if (strcmp(item->defname, "transaction_deferrable") == 0)
6878                                                 SetPGVariable("transaction_deferrable",
6879                                                                           list_make1(item->arg), stmt->is_local);
6880                                         else
6881                                                 elog(ERROR, "unexpected SET TRANSACTION element: %s",
6882                                                          item->defname);
6883                                 }
6884                         }
6885                         else if (strcmp(stmt->name, "SESSION CHARACTERISTICS") == 0)
6886                         {
6887                                 ListCell   *head;
6888
6889                                 foreach(head, stmt->args)
6890                                 {
6891                                         DefElem    *item = (DefElem *) lfirst(head);
6892
6893                                         if (strcmp(item->defname, "transaction_isolation") == 0)
6894                                                 SetPGVariable("default_transaction_isolation",
6895                                                                           list_make1(item->arg), stmt->is_local);
6896                                         else if (strcmp(item->defname, "transaction_read_only") == 0)
6897                                                 SetPGVariable("default_transaction_read_only",
6898                                                                           list_make1(item->arg), stmt->is_local);
6899                                         else if (strcmp(item->defname, "transaction_deferrable") == 0)
6900                                                 SetPGVariable("default_transaction_deferrable",
6901                                                                           list_make1(item->arg), stmt->is_local);
6902                                         else
6903                                                 elog(ERROR, "unexpected SET SESSION element: %s",
6904                                                          item->defname);
6905                                 }
6906                         }
6907                         else if (strcmp(stmt->name, "TRANSACTION SNAPSHOT") == 0)
6908                         {
6909                                 A_Const    *con = (A_Const *) linitial(stmt->args);
6910
6911                                 if (stmt->is_local)
6912                                         ereport(ERROR,
6913                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6914                                                          errmsg("SET LOCAL TRANSACTION SNAPSHOT is not implemented")));
6915
6916                                 WarnNoTransactionChain(isTopLevel, "SET TRANSACTION");
6917                                 Assert(IsA(con, A_Const));
6918                                 Assert(nodeTag(&con->val) == T_String);
6919                                 ImportSnapshot(strVal(&con->val));
6920                         }
6921                         else
6922                                 elog(ERROR, "unexpected SET MULTI element: %s",
6923                                          stmt->name);
6924                         break;
6925                 case VAR_SET_DEFAULT:
6926                         if (stmt->is_local)
6927                                 WarnNoTransactionChain(isTopLevel, "SET LOCAL");
6928                         /* fall through */
6929                 case VAR_RESET:
6930                         if (strcmp(stmt->name, "transaction_isolation") == 0)
6931                                 WarnNoTransactionChain(isTopLevel, "RESET TRANSACTION");
6932
6933                         (void) set_config_option(stmt->name,
6934                                                                          NULL,
6935                                                                          (superuser() ? PGC_SUSET : PGC_USERSET),
6936                                                                          PGC_S_SESSION,
6937                                                                          action,
6938                                                                          true,
6939                                                                          0);
6940                         break;
6941                 case VAR_RESET_ALL:
6942                         ResetAllOptions();
6943                         break;
6944         }
6945 }
6946
6947 /*
6948  * Get the value to assign for a VariableSetStmt, or NULL if it's RESET.
6949  * The result is palloc'd.
6950  *
6951  * This is exported for use by actions such as ALTER ROLE SET.
6952  */
6953 char *
6954 ExtractSetVariableArgs(VariableSetStmt *stmt)
6955 {
6956         switch (stmt->kind)
6957         {
6958                 case VAR_SET_VALUE:
6959                         return flatten_set_variable_args(stmt->name, stmt->args);
6960                 case VAR_SET_CURRENT:
6961                         return GetConfigOptionByName(stmt->name, NULL);
6962                 default:
6963                         return NULL;
6964         }
6965 }
6966
6967 /*
6968  * SetPGVariable - SET command exported as an easily-C-callable function.
6969  *
6970  * This provides access to SET TO value, as well as SET TO DEFAULT (expressed
6971  * by passing args == NIL), but not SET FROM CURRENT functionality.
6972  */
6973 void
6974 SetPGVariable(const char *name, List *args, bool is_local)
6975 {
6976         char       *argstring = flatten_set_variable_args(name, args);
6977
6978         /* Note SET DEFAULT (argstring == NULL) is equivalent to RESET */
6979         (void) set_config_option(name,
6980                                                          argstring,
6981                                                          (superuser() ? PGC_SUSET : PGC_USERSET),
6982                                                          PGC_S_SESSION,
6983                                                          is_local ? GUC_ACTION_LOCAL : GUC_ACTION_SET,
6984                                                          true,
6985                                                          0);
6986 }
6987
6988 /*
6989  * SET command wrapped as a SQL callable function.
6990  */
6991 Datum
6992 set_config_by_name(PG_FUNCTION_ARGS)
6993 {
6994         char       *name;
6995         char       *value;
6996         char       *new_value;
6997         bool            is_local;
6998
6999         if (PG_ARGISNULL(0))
7000                 ereport(ERROR,
7001                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
7002                                  errmsg("SET requires parameter name")));
7003
7004         /* Get the GUC variable name */
7005         name = TextDatumGetCString(PG_GETARG_DATUM(0));
7006
7007         /* Get the desired value or set to NULL for a reset request */
7008         if (PG_ARGISNULL(1))
7009                 value = NULL;
7010         else
7011                 value = TextDatumGetCString(PG_GETARG_DATUM(1));
7012
7013         /*
7014          * Get the desired state of is_local. Default to false if provided value
7015          * is NULL
7016          */
7017         if (PG_ARGISNULL(2))
7018                 is_local = false;
7019         else
7020                 is_local = PG_GETARG_BOOL(2);
7021
7022         /* Note SET DEFAULT (argstring == NULL) is equivalent to RESET */
7023         (void) set_config_option(name,
7024                                                          value,
7025                                                          (superuser() ? PGC_SUSET : PGC_USERSET),
7026                                                          PGC_S_SESSION,
7027                                                          is_local ? GUC_ACTION_LOCAL : GUC_ACTION_SET,
7028                                                          true,
7029                                                          0);
7030
7031         /* get the new current value */
7032         new_value = GetConfigOptionByName(name, NULL);
7033
7034         /* Convert return string to text */
7035         PG_RETURN_TEXT_P(cstring_to_text(new_value));
7036 }
7037
7038
7039 /*
7040  * Common code for DefineCustomXXXVariable subroutines: allocate the
7041  * new variable's config struct and fill in generic fields.
7042  */
7043 static struct config_generic *
7044 init_custom_variable(const char *name,
7045                                          const char *short_desc,
7046                                          const char *long_desc,
7047                                          GucContext context,
7048                                          int flags,
7049                                          enum config_type type,
7050                                          size_t sz)
7051 {
7052         struct config_generic *gen;
7053
7054         /*
7055          * Only allow custom PGC_POSTMASTER variables to be created during shared
7056          * library preload; any later than that, we can't ensure that the value
7057          * doesn't change after startup.  This is a fatal elog if it happens; just
7058          * erroring out isn't safe because we don't know what the calling loadable
7059          * module might already have hooked into.
7060          */
7061         if (context == PGC_POSTMASTER &&
7062                 !process_shared_preload_libraries_in_progress)
7063                 elog(FATAL, "cannot create PGC_POSTMASTER variables after startup");
7064
7065         gen = (struct config_generic *) guc_malloc(ERROR, sz);
7066         memset(gen, 0, sz);
7067
7068         gen->name = guc_strdup(ERROR, name);
7069         gen->context = context;
7070         gen->group = CUSTOM_OPTIONS;
7071         gen->short_desc = short_desc;
7072         gen->long_desc = long_desc;
7073         gen->flags = flags;
7074         gen->vartype = type;
7075
7076         return gen;
7077 }
7078
7079 /*
7080  * Common code for DefineCustomXXXVariable subroutines: insert the new
7081  * variable into the GUC variable array, replacing any placeholder.
7082  */
7083 static void
7084 define_custom_variable(struct config_generic * variable)
7085 {
7086         const char *name = variable->name;
7087         const char **nameAddr = &name;
7088         struct config_string *pHolder;
7089         struct config_generic **res;
7090
7091         /*
7092          * See if there's a placeholder by the same name.
7093          */
7094         res = (struct config_generic **) bsearch((void *) &nameAddr,
7095                                                                                          (void *) guc_variables,
7096                                                                                          num_guc_variables,
7097                                                                                          sizeof(struct config_generic *),
7098                                                                                          guc_var_compare);
7099         if (res == NULL)
7100         {
7101                 /*
7102                  * No placeholder to replace, so we can just add it ... but first,
7103                  * make sure it's initialized to its default value.
7104                  */
7105                 InitializeOneGUCOption(variable);
7106                 add_guc_variable(variable, ERROR);
7107                 return;
7108         }
7109
7110         /*
7111          * This better be a placeholder
7112          */
7113         if (((*res)->flags & GUC_CUSTOM_PLACEHOLDER) == 0)
7114                 ereport(ERROR,
7115                                 (errcode(ERRCODE_INTERNAL_ERROR),
7116                                  errmsg("attempt to redefine parameter \"%s\"", name)));
7117
7118         Assert((*res)->vartype == PGC_STRING);
7119         pHolder = (struct config_string *) (*res);
7120
7121         /*
7122          * First, set the variable to its default value.  We must do this even
7123          * though we intend to immediately apply a new value, since it's possible
7124          * that the new value is invalid.
7125          */
7126         InitializeOneGUCOption(variable);
7127
7128         /*
7129          * Replace the placeholder. We aren't changing the name, so no re-sorting
7130          * is necessary
7131          */
7132         *res = variable;
7133
7134         /*
7135          * Assign the string value(s) stored in the placeholder to the real
7136          * variable.  Essentially, we need to duplicate all the active and stacked
7137          * values, but with appropriate validation and datatype adjustment.
7138          *
7139          * If an assignment fails, we report a WARNING and keep going.  We don't
7140          * want to throw ERROR for bad values, because it'd bollix the add-on
7141          * module that's presumably halfway through getting loaded.  In such cases
7142          * the default or previous state will become active instead.
7143          */
7144
7145         /* First, apply the reset value if any */
7146         if (pHolder->reset_val)
7147                 (void) set_config_option(name, pHolder->reset_val,
7148                                                                  pHolder->gen.reset_scontext,
7149                                                                  pHolder->gen.reset_source,
7150                                                                  GUC_ACTION_SET, true, WARNING);
7151         /* That should not have resulted in stacking anything */
7152         Assert(variable->stack == NULL);
7153
7154         /* Now, apply current and stacked values, in the order they were stacked */
7155         reapply_stacked_values(variable, pHolder, pHolder->gen.stack,
7156                                                    *(pHolder->variable),
7157                                                    pHolder->gen.scontext, pHolder->gen.source);
7158
7159         /* Also copy over any saved source-location information */
7160         if (pHolder->gen.sourcefile)
7161                 set_config_sourcefile(name, pHolder->gen.sourcefile,
7162                                                           pHolder->gen.sourceline);
7163
7164         /*
7165          * Free up as much as we conveniently can of the placeholder structure.
7166          * (This neglects any stack items, so it's possible for some memory to be
7167          * leaked.  Since this can only happen once per session per variable, it
7168          * doesn't seem worth spending much code on.)
7169          */
7170         set_string_field(pHolder, pHolder->variable, NULL);
7171         set_string_field(pHolder, &pHolder->reset_val, NULL);
7172
7173         free(pHolder);
7174 }
7175
7176 /*
7177  * Recursive subroutine for define_custom_variable: reapply non-reset values
7178  *
7179  * We recurse so that the values are applied in the same order as originally.
7180  * At each recursion level, apply the upper-level value (passed in) in the
7181  * fashion implied by the stack entry.
7182  */
7183 static void
7184 reapply_stacked_values(struct config_generic * variable,
7185                                            struct config_string * pHolder,
7186                                            GucStack *stack,
7187                                            const char *curvalue,
7188                                            GucContext curscontext, GucSource cursource)
7189 {
7190         const char *name = variable->name;
7191         GucStack   *oldvarstack = variable->stack;
7192
7193         if (stack != NULL)
7194         {
7195                 /* First, recurse, so that stack items are processed bottom to top */
7196                 reapply_stacked_values(variable, pHolder, stack->prev,
7197                                                            stack->prior.val.stringval,
7198                                                            stack->scontext, stack->source);
7199
7200                 /* See how to apply the passed-in value */
7201                 switch (stack->state)
7202                 {
7203                         case GUC_SAVE:
7204                                 (void) set_config_option(name, curvalue,
7205                                                                                  curscontext, cursource,
7206                                                                                  GUC_ACTION_SAVE, true, WARNING);
7207                                 break;
7208
7209                         case GUC_SET:
7210                                 (void) set_config_option(name, curvalue,
7211                                                                                  curscontext, cursource,
7212                                                                                  GUC_ACTION_SET, true, WARNING);
7213                                 break;
7214
7215                         case GUC_LOCAL:
7216                                 (void) set_config_option(name, curvalue,
7217                                                                                  curscontext, cursource,
7218                                                                                  GUC_ACTION_LOCAL, true, WARNING);
7219                                 break;
7220
7221                         case GUC_SET_LOCAL:
7222                                 /* first, apply the masked value as SET */
7223                                 (void) set_config_option(name, stack->masked.val.stringval,
7224                                                                            stack->masked_scontext, PGC_S_SESSION,
7225                                                                                  GUC_ACTION_SET, true, WARNING);
7226                                 /* then apply the current value as LOCAL */
7227                                 (void) set_config_option(name, curvalue,
7228                                                                                  curscontext, cursource,
7229                                                                                  GUC_ACTION_LOCAL, true, WARNING);
7230                                 break;
7231                 }
7232
7233                 /* If we successfully made a stack entry, adjust its nest level */
7234                 if (variable->stack != oldvarstack)
7235                         variable->stack->nest_level = stack->nest_level;
7236         }
7237         else
7238         {
7239                 /*
7240                  * We are at the end of the stack.  If the active/previous value is
7241                  * different from the reset value, it must represent a previously
7242                  * committed session value.  Apply it, and then drop the stack entry
7243                  * that set_config_option will have created under the impression that
7244                  * this is to be just a transactional assignment.  (We leak the stack
7245                  * entry.)
7246                  */
7247                 if (curvalue != pHolder->reset_val ||
7248                         curscontext != pHolder->gen.reset_scontext ||
7249                         cursource != pHolder->gen.reset_source)
7250                 {
7251                         (void) set_config_option(name, curvalue,
7252                                                                          curscontext, cursource,
7253                                                                          GUC_ACTION_SET, true, WARNING);
7254                         variable->stack = NULL;
7255                 }
7256         }
7257 }
7258
7259 void
7260 DefineCustomBoolVariable(const char *name,
7261                                                  const char *short_desc,
7262                                                  const char *long_desc,
7263                                                  bool *valueAddr,
7264                                                  bool bootValue,
7265                                                  GucContext context,
7266                                                  int flags,
7267                                                  GucBoolCheckHook check_hook,
7268                                                  GucBoolAssignHook assign_hook,
7269                                                  GucShowHook show_hook)
7270 {
7271         struct config_bool *var;
7272
7273         var = (struct config_bool *)
7274                 init_custom_variable(name, short_desc, long_desc, context, flags,
7275                                                          PGC_BOOL, sizeof(struct config_bool));
7276         var->variable = valueAddr;
7277         var->boot_val = bootValue;
7278         var->reset_val = bootValue;
7279         var->check_hook = check_hook;
7280         var->assign_hook = assign_hook;
7281         var->show_hook = show_hook;
7282         define_custom_variable(&var->gen);
7283 }
7284
7285 void
7286 DefineCustomIntVariable(const char *name,
7287                                                 const char *short_desc,
7288                                                 const char *long_desc,
7289                                                 int *valueAddr,
7290                                                 int bootValue,
7291                                                 int minValue,
7292                                                 int maxValue,
7293                                                 GucContext context,
7294                                                 int flags,
7295                                                 GucIntCheckHook check_hook,
7296                                                 GucIntAssignHook assign_hook,
7297                                                 GucShowHook show_hook)
7298 {
7299         struct config_int *var;
7300
7301         var = (struct config_int *)
7302                 init_custom_variable(name, short_desc, long_desc, context, flags,
7303                                                          PGC_INT, sizeof(struct config_int));
7304         var->variable = valueAddr;
7305         var->boot_val = bootValue;
7306         var->reset_val = bootValue;
7307         var->min = minValue;
7308         var->max = maxValue;
7309         var->check_hook = check_hook;
7310         var->assign_hook = assign_hook;
7311         var->show_hook = show_hook;
7312         define_custom_variable(&var->gen);
7313 }
7314
7315 void
7316 DefineCustomRealVariable(const char *name,
7317                                                  const char *short_desc,
7318                                                  const char *long_desc,
7319                                                  double *valueAddr,
7320                                                  double bootValue,
7321                                                  double minValue,
7322                                                  double maxValue,
7323                                                  GucContext context,
7324                                                  int flags,
7325                                                  GucRealCheckHook check_hook,
7326                                                  GucRealAssignHook assign_hook,
7327                                                  GucShowHook show_hook)
7328 {
7329         struct config_real *var;
7330
7331         var = (struct config_real *)
7332                 init_custom_variable(name, short_desc, long_desc, context, flags,
7333                                                          PGC_REAL, sizeof(struct config_real));
7334         var->variable = valueAddr;
7335         var->boot_val = bootValue;
7336         var->reset_val = bootValue;
7337         var->min = minValue;
7338         var->max = maxValue;
7339         var->check_hook = check_hook;
7340         var->assign_hook = assign_hook;
7341         var->show_hook = show_hook;
7342         define_custom_variable(&var->gen);
7343 }
7344
7345 void
7346 DefineCustomStringVariable(const char *name,
7347                                                    const char *short_desc,
7348                                                    const char *long_desc,
7349                                                    char **valueAddr,
7350                                                    const char *bootValue,
7351                                                    GucContext context,
7352                                                    int flags,
7353                                                    GucStringCheckHook check_hook,
7354                                                    GucStringAssignHook assign_hook,
7355                                                    GucShowHook show_hook)
7356 {
7357         struct config_string *var;
7358
7359         var = (struct config_string *)
7360                 init_custom_variable(name, short_desc, long_desc, context, flags,
7361                                                          PGC_STRING, sizeof(struct config_string));
7362         var->variable = valueAddr;
7363         var->boot_val = bootValue;
7364         var->check_hook = check_hook;
7365         var->assign_hook = assign_hook;
7366         var->show_hook = show_hook;
7367         define_custom_variable(&var->gen);
7368 }
7369
7370 void
7371 DefineCustomEnumVariable(const char *name,
7372                                                  const char *short_desc,
7373                                                  const char *long_desc,
7374                                                  int *valueAddr,
7375                                                  int bootValue,
7376                                                  const struct config_enum_entry * options,
7377                                                  GucContext context,
7378                                                  int flags,
7379                                                  GucEnumCheckHook check_hook,
7380                                                  GucEnumAssignHook assign_hook,
7381                                                  GucShowHook show_hook)
7382 {
7383         struct config_enum *var;
7384
7385         var = (struct config_enum *)
7386                 init_custom_variable(name, short_desc, long_desc, context, flags,
7387                                                          PGC_ENUM, sizeof(struct config_enum));
7388         var->variable = valueAddr;
7389         var->boot_val = bootValue;
7390         var->reset_val = bootValue;
7391         var->options = options;
7392         var->check_hook = check_hook;
7393         var->assign_hook = assign_hook;
7394         var->show_hook = show_hook;
7395         define_custom_variable(&var->gen);
7396 }
7397
7398 void
7399 EmitWarningsOnPlaceholders(const char *className)
7400 {
7401         int                     classLen = strlen(className);
7402         int                     i;
7403
7404         for (i = 0; i < num_guc_variables; i++)
7405         {
7406                 struct config_generic *var = guc_variables[i];
7407
7408                 if ((var->flags & GUC_CUSTOM_PLACEHOLDER) != 0 &&
7409                         strncmp(className, var->name, classLen) == 0 &&
7410                         var->name[classLen] == GUC_QUALIFIER_SEPARATOR)
7411                 {
7412                         ereport(WARNING,
7413                                         (errcode(ERRCODE_UNDEFINED_OBJECT),
7414                                          errmsg("unrecognized configuration parameter \"%s\"",
7415                                                         var->name)));
7416                 }
7417         }
7418 }
7419
7420
7421 /*
7422  * SHOW command
7423  */
7424 void
7425 GetPGVariable(const char *name, DestReceiver *dest)
7426 {
7427         if (guc_name_compare(name, "all") == 0)
7428                 ShowAllGUCConfig(dest);
7429         else
7430                 ShowGUCConfigOption(name, dest);
7431 }
7432
7433 TupleDesc
7434 GetPGVariableResultDesc(const char *name)
7435 {
7436         TupleDesc       tupdesc;
7437
7438         if (guc_name_compare(name, "all") == 0)
7439         {
7440                 /* need a tuple descriptor representing three TEXT columns */
7441                 tupdesc = CreateTemplateTupleDesc(3, false);
7442                 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
7443                                                    TEXTOID, -1, 0);
7444                 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "setting",
7445                                                    TEXTOID, -1, 0);
7446                 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "description",
7447                                                    TEXTOID, -1, 0);
7448         }
7449         else
7450         {
7451                 const char *varname;
7452
7453                 /* Get the canonical spelling of name */
7454                 (void) GetConfigOptionByName(name, &varname);
7455
7456                 /* need a tuple descriptor representing a single TEXT column */
7457                 tupdesc = CreateTemplateTupleDesc(1, false);
7458                 TupleDescInitEntry(tupdesc, (AttrNumber) 1, varname,
7459                                                    TEXTOID, -1, 0);
7460         }
7461         return tupdesc;
7462 }
7463
7464
7465 /*
7466  * SHOW command
7467  */
7468 static void
7469 ShowGUCConfigOption(const char *name, DestReceiver *dest)
7470 {
7471         TupOutputState *tstate;
7472         TupleDesc       tupdesc;
7473         const char *varname;
7474         char       *value;
7475
7476         /* Get the value and canonical spelling of name */
7477         value = GetConfigOptionByName(name, &varname);
7478
7479         /* need a tuple descriptor representing a single TEXT column */
7480         tupdesc = CreateTemplateTupleDesc(1, false);
7481         TupleDescInitEntry(tupdesc, (AttrNumber) 1, varname,
7482                                            TEXTOID, -1, 0);
7483
7484         /* prepare for projection of tuples */
7485         tstate = begin_tup_output_tupdesc(dest, tupdesc);
7486
7487         /* Send it */
7488         do_text_output_oneline(tstate, value);
7489
7490         end_tup_output(tstate);
7491 }
7492
7493 /*
7494  * SHOW ALL command
7495  */
7496 static void
7497 ShowAllGUCConfig(DestReceiver *dest)
7498 {
7499         bool            am_superuser = superuser();
7500         int                     i;
7501         TupOutputState *tstate;
7502         TupleDesc       tupdesc;
7503         Datum           values[3];
7504         bool            isnull[3] = {false, false, false};
7505
7506         /* need a tuple descriptor representing three TEXT columns */
7507         tupdesc = CreateTemplateTupleDesc(3, false);
7508         TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
7509                                            TEXTOID, -1, 0);
7510         TupleDescInitEntry(tupdesc, (AttrNumber) 2, "setting",
7511                                            TEXTOID, -1, 0);
7512         TupleDescInitEntry(tupdesc, (AttrNumber) 3, "description",
7513                                            TEXTOID, -1, 0);
7514
7515         /* prepare for projection of tuples */
7516         tstate = begin_tup_output_tupdesc(dest, tupdesc);
7517
7518         for (i = 0; i < num_guc_variables; i++)
7519         {
7520                 struct config_generic *conf = guc_variables[i];
7521                 char       *setting;
7522
7523                 if ((conf->flags & GUC_NO_SHOW_ALL) ||
7524                         ((conf->flags & GUC_SUPERUSER_ONLY) && !am_superuser))
7525                         continue;
7526
7527                 /* assign to the values array */
7528                 values[0] = PointerGetDatum(cstring_to_text(conf->name));
7529
7530                 setting = _ShowOption(conf, true);
7531                 if (setting)
7532                 {
7533                         values[1] = PointerGetDatum(cstring_to_text(setting));
7534                         isnull[1] = false;
7535                 }
7536                 else
7537                 {
7538                         values[1] = PointerGetDatum(NULL);
7539                         isnull[1] = true;
7540                 }
7541
7542                 values[2] = PointerGetDatum(cstring_to_text(conf->short_desc));
7543
7544                 /* send it to dest */
7545                 do_tup_output(tstate, values, isnull);
7546
7547                 /* clean up */
7548                 pfree(DatumGetPointer(values[0]));
7549                 if (setting)
7550                 {
7551                         pfree(setting);
7552                         pfree(DatumGetPointer(values[1]));
7553                 }
7554                 pfree(DatumGetPointer(values[2]));
7555         }
7556
7557         end_tup_output(tstate);
7558 }
7559
7560 /*
7561  * Return GUC variable value by name; optionally return canonical
7562  * form of name.  Return value is palloc'd.
7563  */
7564 char *
7565 GetConfigOptionByName(const char *name, const char **varname)
7566 {
7567         struct config_generic *record;
7568
7569         record = find_option(name, false, ERROR);
7570         if (record == NULL)
7571                 ereport(ERROR,
7572                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
7573                            errmsg("unrecognized configuration parameter \"%s\"", name)));
7574         if ((record->flags & GUC_SUPERUSER_ONLY) && !superuser())
7575                 ereport(ERROR,
7576                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
7577                                  errmsg("must be superuser to examine \"%s\"", name)));
7578
7579         if (varname)
7580                 *varname = record->name;
7581
7582         return _ShowOption(record, true);
7583 }
7584
7585 /*
7586  * Return GUC variable value by variable number; optionally return canonical
7587  * form of name.  Return value is palloc'd.
7588  */
7589 void
7590 GetConfigOptionByNum(int varnum, const char **values, bool *noshow)
7591 {
7592         char            buffer[256];
7593         struct config_generic *conf;
7594
7595         /* check requested variable number valid */
7596         Assert((varnum >= 0) && (varnum < num_guc_variables));
7597
7598         conf = guc_variables[varnum];
7599
7600         if (noshow)
7601         {
7602                 if ((conf->flags & GUC_NO_SHOW_ALL) ||
7603                         ((conf->flags & GUC_SUPERUSER_ONLY) && !superuser()))
7604                         *noshow = true;
7605                 else
7606                         *noshow = false;
7607         }
7608
7609         /* first get the generic attributes */
7610
7611         /* name */
7612         values[0] = conf->name;
7613
7614         /* setting : use _ShowOption in order to avoid duplicating the logic */
7615         values[1] = _ShowOption(conf, false);
7616
7617         /* unit */
7618         if (conf->vartype == PGC_INT)
7619         {
7620                 static char buf[8];
7621
7622                 switch (conf->flags & (GUC_UNIT_MEMORY | GUC_UNIT_TIME))
7623                 {
7624                         case GUC_UNIT_KB:
7625                                 values[2] = "kB";
7626                                 break;
7627                         case GUC_UNIT_BLOCKS:
7628                                 snprintf(buf, sizeof(buf), "%dkB", BLCKSZ / 1024);
7629                                 values[2] = buf;
7630                                 break;
7631                         case GUC_UNIT_XBLOCKS:
7632                                 snprintf(buf, sizeof(buf), "%dkB", XLOG_BLCKSZ / 1024);
7633                                 values[2] = buf;
7634                                 break;
7635                         case GUC_UNIT_MS:
7636                                 values[2] = "ms";
7637                                 break;
7638                         case GUC_UNIT_S:
7639                                 values[2] = "s";
7640                                 break;
7641                         case GUC_UNIT_MIN:
7642                                 values[2] = "min";
7643                                 break;
7644                         default:
7645                                 values[2] = "";
7646                                 break;
7647                 }
7648         }
7649         else
7650                 values[2] = NULL;
7651
7652         /* group */
7653         values[3] = config_group_names[conf->group];
7654
7655         /* short_desc */
7656         values[4] = conf->short_desc;
7657
7658         /* extra_desc */
7659         values[5] = conf->long_desc;
7660
7661         /* context */
7662         values[6] = GucContext_Names[conf->context];
7663
7664         /* vartype */
7665         values[7] = config_type_names[conf->vartype];
7666
7667         /* source */
7668         values[8] = GucSource_Names[conf->source];
7669
7670         /* now get the type specifc attributes */
7671         switch (conf->vartype)
7672         {
7673                 case PGC_BOOL:
7674                         {
7675                                 struct config_bool *lconf = (struct config_bool *) conf;
7676
7677                                 /* min_val */
7678                                 values[9] = NULL;
7679
7680                                 /* max_val */
7681                                 values[10] = NULL;
7682
7683                                 /* enumvals */
7684                                 values[11] = NULL;
7685
7686                                 /* boot_val */
7687                                 values[12] = pstrdup(lconf->boot_val ? "on" : "off");
7688
7689                                 /* reset_val */
7690                                 values[13] = pstrdup(lconf->reset_val ? "on" : "off");
7691                         }
7692                         break;
7693
7694                 case PGC_INT:
7695                         {
7696                                 struct config_int *lconf = (struct config_int *) conf;
7697
7698                                 /* min_val */
7699                                 snprintf(buffer, sizeof(buffer), "%d", lconf->min);
7700                                 values[9] = pstrdup(buffer);
7701
7702                                 /* max_val */
7703                                 snprintf(buffer, sizeof(buffer), "%d", lconf->max);
7704                                 values[10] = pstrdup(buffer);
7705
7706                                 /* enumvals */
7707                                 values[11] = NULL;
7708
7709                                 /* boot_val */
7710                                 snprintf(buffer, sizeof(buffer), "%d", lconf->boot_val);
7711                                 values[12] = pstrdup(buffer);
7712
7713                                 /* reset_val */
7714                                 snprintf(buffer, sizeof(buffer), "%d", lconf->reset_val);
7715                                 values[13] = pstrdup(buffer);
7716                         }
7717                         break;
7718
7719                 case PGC_REAL:
7720                         {
7721                                 struct config_real *lconf = (struct config_real *) conf;
7722
7723                                 /* min_val */
7724                                 snprintf(buffer, sizeof(buffer), "%g", lconf->min);
7725                                 values[9] = pstrdup(buffer);
7726
7727                                 /* max_val */
7728                                 snprintf(buffer, sizeof(buffer), "%g", lconf->max);
7729                                 values[10] = pstrdup(buffer);
7730
7731                                 /* enumvals */
7732                                 values[11] = NULL;
7733
7734                                 /* boot_val */
7735                                 snprintf(buffer, sizeof(buffer), "%g", lconf->boot_val);
7736                                 values[12] = pstrdup(buffer);
7737
7738                                 /* reset_val */
7739                                 snprintf(buffer, sizeof(buffer), "%g", lconf->reset_val);
7740                                 values[13] = pstrdup(buffer);
7741                         }
7742                         break;
7743
7744                 case PGC_STRING:
7745                         {
7746                                 struct config_string *lconf = (struct config_string *) conf;
7747
7748                                 /* min_val */
7749                                 values[9] = NULL;
7750
7751                                 /* max_val */
7752                                 values[10] = NULL;
7753
7754                                 /* enumvals */
7755                                 values[11] = NULL;
7756
7757                                 /* boot_val */
7758                                 if (lconf->boot_val == NULL)
7759                                         values[12] = NULL;
7760                                 else
7761                                         values[12] = pstrdup(lconf->boot_val);
7762
7763                                 /* reset_val */
7764                                 if (lconf->reset_val == NULL)
7765                                         values[13] = NULL;
7766                                 else
7767                                         values[13] = pstrdup(lconf->reset_val);
7768                         }
7769                         break;
7770
7771                 case PGC_ENUM:
7772                         {
7773                                 struct config_enum *lconf = (struct config_enum *) conf;
7774
7775                                 /* min_val */
7776                                 values[9] = NULL;
7777
7778                                 /* max_val */
7779                                 values[10] = NULL;
7780
7781                                 /* enumvals */
7782
7783                                 /*
7784                                  * NOTE! enumvals with double quotes in them are not
7785                                  * supported!
7786                                  */
7787                                 values[11] = config_enum_get_options((struct config_enum *) conf,
7788                                                                                                          "{\"", "\"}", "\",\"");
7789
7790                                 /* boot_val */
7791                                 values[12] = pstrdup(config_enum_lookup_by_value(lconf,
7792                                                                                                                    lconf->boot_val));
7793
7794                                 /* reset_val */
7795                                 values[13] = pstrdup(config_enum_lookup_by_value(lconf,
7796                                                                                                                   lconf->reset_val));
7797                         }
7798                         break;
7799
7800                 default:
7801                         {
7802                                 /*
7803                                  * should never get here, but in case we do, set 'em to NULL
7804                                  */
7805
7806                                 /* min_val */
7807                                 values[9] = NULL;
7808
7809                                 /* max_val */
7810                                 values[10] = NULL;
7811
7812                                 /* enumvals */
7813                                 values[11] = NULL;
7814
7815                                 /* boot_val */
7816                                 values[12] = NULL;
7817
7818                                 /* reset_val */
7819                                 values[13] = NULL;
7820                         }
7821                         break;
7822         }
7823
7824         /*
7825          * If the setting came from a config file, set the source location. For
7826          * security reasons, we don't show source file/line number for
7827          * non-superusers.
7828          */
7829         if (conf->source == PGC_S_FILE && superuser())
7830         {
7831                 values[14] = conf->sourcefile;
7832                 snprintf(buffer, sizeof(buffer), "%d", conf->sourceline);
7833                 values[15] = pstrdup(buffer);
7834         }
7835         else
7836         {
7837                 values[14] = NULL;
7838                 values[15] = NULL;
7839         }
7840 }
7841
7842 /*
7843  * Return the total number of GUC variables
7844  */
7845 int
7846 GetNumConfigOptions(void)
7847 {
7848         return num_guc_variables;
7849 }
7850
7851 /*
7852  * show_config_by_name - equiv to SHOW X command but implemented as
7853  * a function.
7854  */
7855 Datum
7856 show_config_by_name(PG_FUNCTION_ARGS)
7857 {
7858         char       *varname;
7859         char       *varval;
7860
7861         /* Get the GUC variable name */
7862         varname = TextDatumGetCString(PG_GETARG_DATUM(0));
7863
7864         /* Get the value */
7865         varval = GetConfigOptionByName(varname, NULL);
7866
7867         /* Convert to text */
7868         PG_RETURN_TEXT_P(cstring_to_text(varval));
7869 }
7870
7871 /*
7872  * show_all_settings - equiv to SHOW ALL command but implemented as
7873  * a Table Function.
7874  */
7875 #define NUM_PG_SETTINGS_ATTS    16
7876
7877 Datum
7878 show_all_settings(PG_FUNCTION_ARGS)
7879 {
7880         FuncCallContext *funcctx;
7881         TupleDesc       tupdesc;
7882         int                     call_cntr;
7883         int                     max_calls;
7884         AttInMetadata *attinmeta;
7885         MemoryContext oldcontext;
7886
7887         /* stuff done only on the first call of the function */
7888         if (SRF_IS_FIRSTCALL())
7889         {
7890                 /* create a function context for cross-call persistence */
7891                 funcctx = SRF_FIRSTCALL_INIT();
7892
7893                 /*
7894                  * switch to memory context appropriate for multiple function calls
7895                  */
7896                 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
7897
7898                 /*
7899                  * need a tuple descriptor representing NUM_PG_SETTINGS_ATTS columns
7900                  * of the appropriate types
7901                  */
7902                 tupdesc = CreateTemplateTupleDesc(NUM_PG_SETTINGS_ATTS, false);
7903                 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
7904                                                    TEXTOID, -1, 0);
7905                 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "setting",
7906                                                    TEXTOID, -1, 0);
7907                 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "unit",
7908                                                    TEXTOID, -1, 0);
7909                 TupleDescInitEntry(tupdesc, (AttrNumber) 4, "category",
7910                                                    TEXTOID, -1, 0);
7911                 TupleDescInitEntry(tupdesc, (AttrNumber) 5, "short_desc",
7912                                                    TEXTOID, -1, 0);
7913                 TupleDescInitEntry(tupdesc, (AttrNumber) 6, "extra_desc",
7914                                                    TEXTOID, -1, 0);
7915                 TupleDescInitEntry(tupdesc, (AttrNumber) 7, "context",
7916                                                    TEXTOID, -1, 0);
7917                 TupleDescInitEntry(tupdesc, (AttrNumber) 8, "vartype",
7918                                                    TEXTOID, -1, 0);
7919                 TupleDescInitEntry(tupdesc, (AttrNumber) 9, "source",
7920                                                    TEXTOID, -1, 0);
7921                 TupleDescInitEntry(tupdesc, (AttrNumber) 10, "min_val",
7922                                                    TEXTOID, -1, 0);
7923                 TupleDescInitEntry(tupdesc, (AttrNumber) 11, "max_val",
7924                                                    TEXTOID, -1, 0);
7925                 TupleDescInitEntry(tupdesc, (AttrNumber) 12, "enumvals",
7926                                                    TEXTARRAYOID, -1, 0);
7927                 TupleDescInitEntry(tupdesc, (AttrNumber) 13, "boot_val",
7928                                                    TEXTOID, -1, 0);
7929                 TupleDescInitEntry(tupdesc, (AttrNumber) 14, "reset_val",
7930                                                    TEXTOID, -1, 0);
7931                 TupleDescInitEntry(tupdesc, (AttrNumber) 15, "sourcefile",
7932                                                    TEXTOID, -1, 0);
7933                 TupleDescInitEntry(tupdesc, (AttrNumber) 16, "sourceline",
7934                                                    INT4OID, -1, 0);
7935
7936                 /*
7937                  * Generate attribute metadata needed later to produce tuples from raw
7938                  * C strings
7939                  */
7940                 attinmeta = TupleDescGetAttInMetadata(tupdesc);
7941                 funcctx->attinmeta = attinmeta;
7942
7943                 /* total number of tuples to be returned */
7944                 funcctx->max_calls = GetNumConfigOptions();
7945
7946                 MemoryContextSwitchTo(oldcontext);
7947         }
7948
7949         /* stuff done on every call of the function */
7950         funcctx = SRF_PERCALL_SETUP();
7951
7952         call_cntr = funcctx->call_cntr;
7953         max_calls = funcctx->max_calls;
7954         attinmeta = funcctx->attinmeta;
7955
7956         if (call_cntr < max_calls)      /* do when there is more left to send */
7957         {
7958                 char       *values[NUM_PG_SETTINGS_ATTS];
7959                 bool            noshow;
7960                 HeapTuple       tuple;
7961                 Datum           result;
7962
7963                 /*
7964                  * Get the next visible GUC variable name and value
7965                  */
7966                 do
7967                 {
7968                         GetConfigOptionByNum(call_cntr, (const char **) values, &noshow);
7969                         if (noshow)
7970                         {
7971                                 /* bump the counter and get the next config setting */
7972                                 call_cntr = ++funcctx->call_cntr;
7973
7974                                 /* make sure we haven't gone too far now */
7975                                 if (call_cntr >= max_calls)
7976                                         SRF_RETURN_DONE(funcctx);
7977                         }
7978                 } while (noshow);
7979
7980                 /* build a tuple */
7981                 tuple = BuildTupleFromCStrings(attinmeta, values);
7982
7983                 /* make the tuple into a datum */
7984                 result = HeapTupleGetDatum(tuple);
7985
7986                 SRF_RETURN_NEXT(funcctx, result);
7987         }
7988         else
7989         {
7990                 /* do when there is no more left */
7991                 SRF_RETURN_DONE(funcctx);
7992         }
7993 }
7994
7995 static char *
7996 _ShowOption(struct config_generic * record, bool use_units)
7997 {
7998         char            buffer[256];
7999         const char *val;
8000
8001         switch (record->vartype)
8002         {
8003                 case PGC_BOOL:
8004                         {
8005                                 struct config_bool *conf = (struct config_bool *) record;
8006
8007                                 if (conf->show_hook)
8008                                         val = (*conf->show_hook) ();
8009                                 else
8010                                         val = *conf->variable ? "on" : "off";
8011                         }
8012                         break;
8013
8014                 case PGC_INT:
8015                         {
8016                                 struct config_int *conf = (struct config_int *) record;
8017
8018                                 if (conf->show_hook)
8019                                         val = (*conf->show_hook) ();
8020                                 else
8021                                 {
8022                                         /*
8023                                          * Use int64 arithmetic to avoid overflows in units
8024                                          * conversion.
8025                                          */
8026                                         int64           result = *conf->variable;
8027                                         const char *unit;
8028
8029                                         if (use_units && result > 0 &&
8030                                                 (record->flags & GUC_UNIT_MEMORY))
8031                                         {
8032                                                 switch (record->flags & GUC_UNIT_MEMORY)
8033                                                 {
8034                                                         case GUC_UNIT_BLOCKS:
8035                                                                 result *= BLCKSZ / 1024;
8036                                                                 break;
8037                                                         case GUC_UNIT_XBLOCKS:
8038                                                                 result *= XLOG_BLCKSZ / 1024;
8039                                                                 break;
8040                                                 }
8041
8042                                                 if (result % KB_PER_TB == 0)
8043                                                 {
8044                                                         result /= KB_PER_TB;
8045                                                         unit = "TB";
8046                                                 }
8047                                                 else if (result % KB_PER_GB == 0)
8048                                                 {
8049                                                         result /= KB_PER_GB;
8050                                                         unit = "GB";
8051                                                 }
8052                                                 else if (result % KB_PER_MB == 0)
8053                                                 {
8054                                                         result /= KB_PER_MB;
8055                                                         unit = "MB";
8056                                                 }
8057                                                 else
8058                                                 {
8059                                                         unit = "kB";
8060                                                 }
8061                                         }
8062                                         else if (use_units && result > 0 &&
8063                                                          (record->flags & GUC_UNIT_TIME))
8064                                         {
8065                                                 switch (record->flags & GUC_UNIT_TIME)
8066                                                 {
8067                                                         case GUC_UNIT_S:
8068                                                                 result *= MS_PER_S;
8069                                                                 break;
8070                                                         case GUC_UNIT_MIN:
8071                                                                 result *= MS_PER_MIN;
8072                                                                 break;
8073                                                 }
8074
8075                                                 if (result % MS_PER_D == 0)
8076                                                 {
8077                                                         result /= MS_PER_D;
8078                                                         unit = "d";
8079                                                 }
8080                                                 else if (result % MS_PER_H == 0)
8081                                                 {
8082                                                         result /= MS_PER_H;
8083                                                         unit = "h";
8084                                                 }
8085                                                 else if (result % MS_PER_MIN == 0)
8086                                                 {
8087                                                         result /= MS_PER_MIN;
8088                                                         unit = "min";
8089                                                 }
8090                                                 else if (result % MS_PER_S == 0)
8091                                                 {
8092                                                         result /= MS_PER_S;
8093                                                         unit = "s";
8094                                                 }
8095                                                 else
8096                                                 {
8097                                                         unit = "ms";
8098                                                 }
8099                                         }
8100                                         else
8101                                                 unit = "";
8102
8103                                         snprintf(buffer, sizeof(buffer), INT64_FORMAT "%s",
8104                                                          result, unit);
8105                                         val = buffer;
8106                                 }
8107                         }
8108                         break;
8109
8110                 case PGC_REAL:
8111                         {
8112                                 struct config_real *conf = (struct config_real *) record;
8113
8114                                 if (conf->show_hook)
8115                                         val = (*conf->show_hook) ();
8116                                 else
8117                                 {
8118                                         snprintf(buffer, sizeof(buffer), "%g",
8119                                                          *conf->variable);
8120                                         val = buffer;
8121                                 }
8122                         }
8123                         break;
8124
8125                 case PGC_STRING:
8126                         {
8127                                 struct config_string *conf = (struct config_string *) record;
8128
8129                                 if (conf->show_hook)
8130                                         val = (*conf->show_hook) ();
8131                                 else if (*conf->variable && **conf->variable)
8132                                         val = *conf->variable;
8133                                 else
8134                                         val = "";
8135                         }
8136                         break;
8137
8138                 case PGC_ENUM:
8139                         {
8140                                 struct config_enum *conf = (struct config_enum *) record;
8141
8142                                 if (conf->show_hook)
8143                                         val = (*conf->show_hook) ();
8144                                 else
8145                                         val = config_enum_lookup_by_value(conf, *conf->variable);
8146                         }
8147                         break;
8148
8149                 default:
8150                         /* just to keep compiler quiet */
8151                         val = "???";
8152                         break;
8153         }
8154
8155         return pstrdup(val);
8156 }
8157
8158
8159 #ifdef EXEC_BACKEND
8160
8161 /*
8162  *      These routines dump out all non-default GUC options into a binary
8163  *      file that is read by all exec'ed backends.  The format is:
8164  *
8165  *              variable name, string, null terminated
8166  *              variable value, string, null terminated
8167  *              variable sourcefile, string, null terminated (empty if none)
8168  *              variable sourceline, integer
8169  *              variable source, integer
8170  *              variable scontext, integer
8171  */
8172 static void
8173 write_one_nondefault_variable(FILE *fp, struct config_generic * gconf)
8174 {
8175         if (gconf->source == PGC_S_DEFAULT)
8176                 return;
8177
8178         fprintf(fp, "%s", gconf->name);
8179         fputc(0, fp);
8180
8181         switch (gconf->vartype)
8182         {
8183                 case PGC_BOOL:
8184                         {
8185                                 struct config_bool *conf = (struct config_bool *) gconf;
8186
8187                                 if (*conf->variable)
8188                                         fprintf(fp, "true");
8189                                 else
8190                                         fprintf(fp, "false");
8191                         }
8192                         break;
8193
8194                 case PGC_INT:
8195                         {
8196                                 struct config_int *conf = (struct config_int *) gconf;
8197
8198                                 fprintf(fp, "%d", *conf->variable);
8199                         }
8200                         break;
8201
8202                 case PGC_REAL:
8203                         {
8204                                 struct config_real *conf = (struct config_real *) gconf;
8205
8206                                 fprintf(fp, "%.17g", *conf->variable);
8207                         }
8208                         break;
8209
8210                 case PGC_STRING:
8211                         {
8212                                 struct config_string *conf = (struct config_string *) gconf;
8213
8214                                 fprintf(fp, "%s", *conf->variable);
8215                         }
8216                         break;
8217
8218                 case PGC_ENUM:
8219                         {
8220                                 struct config_enum *conf = (struct config_enum *) gconf;
8221
8222                                 fprintf(fp, "%s",
8223                                                 config_enum_lookup_by_value(conf, *conf->variable));
8224                         }
8225                         break;
8226         }
8227
8228         fputc(0, fp);
8229
8230         if (gconf->sourcefile)
8231                 fprintf(fp, "%s", gconf->sourcefile);
8232         fputc(0, fp);
8233
8234         fwrite(&gconf->sourceline, 1, sizeof(gconf->sourceline), fp);
8235         fwrite(&gconf->source, 1, sizeof(gconf->source), fp);
8236         fwrite(&gconf->scontext, 1, sizeof(gconf->scontext), fp);
8237 }
8238
8239 void
8240 write_nondefault_variables(GucContext context)
8241 {
8242         int                     elevel;
8243         FILE       *fp;
8244         int                     i;
8245
8246         Assert(context == PGC_POSTMASTER || context == PGC_SIGHUP);
8247
8248         elevel = (context == PGC_SIGHUP) ? LOG : ERROR;
8249
8250         /*
8251          * Open file
8252          */
8253         fp = AllocateFile(CONFIG_EXEC_PARAMS_NEW, "w");
8254         if (!fp)
8255         {
8256                 ereport(elevel,
8257                                 (errcode_for_file_access(),
8258                                  errmsg("could not write to file \"%s\": %m",
8259                                                 CONFIG_EXEC_PARAMS_NEW)));
8260                 return;
8261         }
8262
8263         for (i = 0; i < num_guc_variables; i++)
8264         {
8265                 write_one_nondefault_variable(fp, guc_variables[i]);
8266         }
8267
8268         if (FreeFile(fp))
8269         {
8270                 ereport(elevel,
8271                                 (errcode_for_file_access(),
8272                                  errmsg("could not write to file \"%s\": %m",
8273                                                 CONFIG_EXEC_PARAMS_NEW)));
8274                 return;
8275         }
8276
8277         /*
8278          * Put new file in place.  This could delay on Win32, but we don't hold
8279          * any exclusive locks.
8280          */
8281         rename(CONFIG_EXEC_PARAMS_NEW, CONFIG_EXEC_PARAMS);
8282 }
8283
8284
8285 /*
8286  *      Read string, including null byte from file
8287  *
8288  *      Return NULL on EOF and nothing read
8289  */
8290 static char *
8291 read_string_with_null(FILE *fp)
8292 {
8293         int                     i = 0,
8294                                 ch,
8295                                 maxlen = 256;
8296         char       *str = NULL;
8297
8298         do
8299         {
8300                 if ((ch = fgetc(fp)) == EOF)
8301                 {
8302                         if (i == 0)
8303                                 return NULL;
8304                         else
8305                                 elog(FATAL, "invalid format of exec config params file");
8306                 }
8307                 if (i == 0)
8308                         str = guc_malloc(FATAL, maxlen);
8309                 else if (i == maxlen)
8310                         str = guc_realloc(FATAL, str, maxlen *= 2);
8311                 str[i++] = ch;
8312         } while (ch != 0);
8313
8314         return str;
8315 }
8316
8317
8318 /*
8319  *      This routine loads a previous postmaster dump of its non-default
8320  *      settings.
8321  */
8322 void
8323 read_nondefault_variables(void)
8324 {
8325         FILE       *fp;
8326         char       *varname,
8327                            *varvalue,
8328                            *varsourcefile;
8329         int                     varsourceline;
8330         GucSource       varsource;
8331         GucContext      varscontext;
8332
8333         /*
8334          * Assert that PGC_BACKEND case in set_config_option() will do the right
8335          * thing.
8336          */
8337         Assert(IsInitProcessingMode());
8338
8339         /*
8340          * Open file
8341          */
8342         fp = AllocateFile(CONFIG_EXEC_PARAMS, "r");
8343         if (!fp)
8344         {
8345                 /* File not found is fine */
8346                 if (errno != ENOENT)
8347                         ereport(FATAL,
8348                                         (errcode_for_file_access(),
8349                                          errmsg("could not read from file \"%s\": %m",
8350                                                         CONFIG_EXEC_PARAMS)));
8351                 return;
8352         }
8353
8354         for (;;)
8355         {
8356                 struct config_generic *record;
8357
8358                 if ((varname = read_string_with_null(fp)) == NULL)
8359                         break;
8360
8361                 if ((record = find_option(varname, true, FATAL)) == NULL)
8362                         elog(FATAL, "failed to locate variable \"%s\" in exec config params file", varname);
8363
8364                 if ((varvalue = read_string_with_null(fp)) == NULL)
8365                         elog(FATAL, "invalid format of exec config params file");
8366                 if ((varsourcefile = read_string_with_null(fp)) == NULL)
8367                         elog(FATAL, "invalid format of exec config params file");
8368                 if (fread(&varsourceline, 1, sizeof(varsourceline), fp) != sizeof(varsourceline))
8369                         elog(FATAL, "invalid format of exec config params file");
8370                 if (fread(&varsource, 1, sizeof(varsource), fp) != sizeof(varsource))
8371                         elog(FATAL, "invalid format of exec config params file");
8372                 if (fread(&varscontext, 1, sizeof(varscontext), fp) != sizeof(varscontext))
8373                         elog(FATAL, "invalid format of exec config params file");
8374
8375                 (void) set_config_option(varname, varvalue,
8376                                                                  varscontext, varsource,
8377                                                                  GUC_ACTION_SET, true, 0);
8378                 if (varsourcefile[0])
8379                         set_config_sourcefile(varname, varsourcefile, varsourceline);
8380
8381                 free(varname);
8382                 free(varvalue);
8383                 free(varsourcefile);
8384         }
8385
8386         FreeFile(fp);
8387 }
8388 #endif   /* EXEC_BACKEND */
8389
8390
8391 /*
8392  * A little "long argument" simulation, although not quite GNU
8393  * compliant. Takes a string of the form "some-option=some value" and
8394  * returns name = "some_option" and value = "some value" in malloc'ed
8395  * storage. Note that '-' is converted to '_' in the option name. If
8396  * there is no '=' in the input string then value will be NULL.
8397  */
8398 void
8399 ParseLongOption(const char *string, char **name, char **value)
8400 {
8401         size_t          equal_pos;
8402         char       *cp;
8403
8404         AssertArg(string);
8405         AssertArg(name);
8406         AssertArg(value);
8407
8408         equal_pos = strcspn(string, "=");
8409
8410         if (string[equal_pos] == '=')
8411         {
8412                 *name = guc_malloc(FATAL, equal_pos + 1);
8413                 strlcpy(*name, string, equal_pos + 1);
8414
8415                 *value = guc_strdup(FATAL, &string[equal_pos + 1]);
8416         }
8417         else
8418         {
8419                 /* no equal sign in string */
8420                 *name = guc_strdup(FATAL, string);
8421                 *value = NULL;
8422         }
8423
8424         for (cp = *name; *cp; cp++)
8425                 if (*cp == '-')
8426                         *cp = '_';
8427 }
8428
8429
8430 /*
8431  * Handle options fetched from pg_db_role_setting.setconfig,
8432  * pg_proc.proconfig, etc.  Caller must specify proper context/source/action.
8433  *
8434  * The array parameter must be an array of TEXT (it must not be NULL).
8435  */
8436 void
8437 ProcessGUCArray(ArrayType *array,
8438                                 GucContext context, GucSource source, GucAction action)
8439 {
8440         int                     i;
8441
8442         Assert(array != NULL);
8443         Assert(ARR_ELEMTYPE(array) == TEXTOID);
8444         Assert(ARR_NDIM(array) == 1);
8445         Assert(ARR_LBOUND(array)[0] == 1);
8446
8447         for (i = 1; i <= ARR_DIMS(array)[0]; i++)
8448         {
8449                 Datum           d;
8450                 bool            isnull;
8451                 char       *s;
8452                 char       *name;
8453                 char       *value;
8454
8455                 d = array_ref(array, 1, &i,
8456                                           -1 /* varlenarray */ ,
8457                                           -1 /* TEXT's typlen */ ,
8458                                           false /* TEXT's typbyval */ ,
8459                                           'i' /* TEXT's typalign */ ,
8460                                           &isnull);
8461
8462                 if (isnull)
8463                         continue;
8464
8465                 s = TextDatumGetCString(d);
8466
8467                 ParseLongOption(s, &name, &value);
8468                 if (!value)
8469                 {
8470                         ereport(WARNING,
8471                                         (errcode(ERRCODE_SYNTAX_ERROR),
8472                                          errmsg("could not parse setting for parameter \"%s\"",
8473                                                         name)));
8474                         free(name);
8475                         continue;
8476                 }
8477
8478                 (void) set_config_option(name, value,
8479                                                                  context, source,
8480                                                                  action, true, 0);
8481
8482                 free(name);
8483                 if (value)
8484                         free(value);
8485                 pfree(s);
8486         }
8487 }
8488
8489
8490 /*
8491  * Add an entry to an option array.  The array parameter may be NULL
8492  * to indicate the current table entry is NULL.
8493  */
8494 ArrayType *
8495 GUCArrayAdd(ArrayType *array, const char *name, const char *value)
8496 {
8497         struct config_generic *record;
8498         Datum           datum;
8499         char       *newval;
8500         ArrayType  *a;
8501
8502         Assert(name);
8503         Assert(value);
8504
8505         /* test if the option is valid and we're allowed to set it */
8506         (void) validate_option_array_item(name, value, false);
8507
8508         /* normalize name (converts obsolete GUC names to modern spellings) */
8509         record = find_option(name, false, WARNING);
8510         if (record)
8511                 name = record->name;
8512
8513         /* build new item for array */
8514         newval = psprintf("%s=%s", name, value);
8515         datum = CStringGetTextDatum(newval);
8516
8517         if (array)
8518         {
8519                 int                     index;
8520                 bool            isnull;
8521                 int                     i;
8522
8523                 Assert(ARR_ELEMTYPE(array) == TEXTOID);
8524                 Assert(ARR_NDIM(array) == 1);
8525                 Assert(ARR_LBOUND(array)[0] == 1);
8526
8527                 index = ARR_DIMS(array)[0] + 1; /* add after end */
8528
8529                 for (i = 1; i <= ARR_DIMS(array)[0]; i++)
8530                 {
8531                         Datum           d;
8532                         char       *current;
8533
8534                         d = array_ref(array, 1, &i,
8535                                                   -1 /* varlenarray */ ,
8536                                                   -1 /* TEXT's typlen */ ,
8537                                                   false /* TEXT's typbyval */ ,
8538                                                   'i' /* TEXT's typalign */ ,
8539                                                   &isnull);
8540                         if (isnull)
8541                                 continue;
8542                         current = TextDatumGetCString(d);
8543
8544                         /* check for match up through and including '=' */
8545                         if (strncmp(current, newval, strlen(name) + 1) == 0)
8546                         {
8547                                 index = i;
8548                                 break;
8549                         }
8550                 }
8551
8552                 a = array_set(array, 1, &index,
8553                                           datum,
8554                                           false,
8555                                           -1 /* varlena array */ ,
8556                                           -1 /* TEXT's typlen */ ,
8557                                           false /* TEXT's typbyval */ ,
8558                                           'i' /* TEXT's typalign */ );
8559         }
8560         else
8561                 a = construct_array(&datum, 1,
8562                                                         TEXTOID,
8563                                                         -1, false, 'i');
8564
8565         return a;
8566 }
8567
8568
8569 /*
8570  * Delete an entry from an option array.  The array parameter may be NULL
8571  * to indicate the current table entry is NULL.  Also, if the return value
8572  * is NULL then a null should be stored.
8573  */
8574 ArrayType *
8575 GUCArrayDelete(ArrayType *array, const char *name)
8576 {
8577         struct config_generic *record;
8578         ArrayType  *newarray;
8579         int                     i;
8580         int                     index;
8581
8582         Assert(name);
8583
8584         /* test if the option is valid and we're allowed to set it */
8585         (void) validate_option_array_item(name, NULL, false);
8586
8587         /* normalize name (converts obsolete GUC names to modern spellings) */
8588         record = find_option(name, false, WARNING);
8589         if (record)
8590                 name = record->name;
8591
8592         /* if array is currently null, then surely nothing to delete */
8593         if (!array)
8594                 return NULL;
8595
8596         newarray = NULL;
8597         index = 1;
8598
8599         for (i = 1; i <= ARR_DIMS(array)[0]; i++)
8600         {
8601                 Datum           d;
8602                 char       *val;
8603                 bool            isnull;
8604
8605                 d = array_ref(array, 1, &i,
8606                                           -1 /* varlenarray */ ,
8607                                           -1 /* TEXT's typlen */ ,
8608                                           false /* TEXT's typbyval */ ,
8609                                           'i' /* TEXT's typalign */ ,
8610                                           &isnull);
8611                 if (isnull)
8612                         continue;
8613                 val = TextDatumGetCString(d);
8614
8615                 /* ignore entry if it's what we want to delete */
8616                 if (strncmp(val, name, strlen(name)) == 0
8617                         && val[strlen(name)] == '=')
8618                         continue;
8619
8620                 /* else add it to the output array */
8621                 if (newarray)
8622                         newarray = array_set(newarray, 1, &index,
8623                                                                  d,
8624                                                                  false,
8625                                                                  -1 /* varlenarray */ ,
8626                                                                  -1 /* TEXT's typlen */ ,
8627                                                                  false /* TEXT's typbyval */ ,
8628                                                                  'i' /* TEXT's typalign */ );
8629                 else
8630                         newarray = construct_array(&d, 1,
8631                                                                            TEXTOID,
8632                                                                            -1, false, 'i');
8633
8634                 index++;
8635         }
8636
8637         return newarray;
8638 }
8639
8640
8641 /*
8642  * Given a GUC array, delete all settings from it that our permission
8643  * level allows: if superuser, delete them all; if regular user, only
8644  * those that are PGC_USERSET
8645  */
8646 ArrayType *
8647 GUCArrayReset(ArrayType *array)
8648 {
8649         ArrayType  *newarray;
8650         int                     i;
8651         int                     index;
8652
8653         /* if array is currently null, nothing to do */
8654         if (!array)
8655                 return NULL;
8656
8657         /* if we're superuser, we can delete everything, so just do it */
8658         if (superuser())
8659                 return NULL;
8660
8661         newarray = NULL;
8662         index = 1;
8663
8664         for (i = 1; i <= ARR_DIMS(array)[0]; i++)
8665         {
8666                 Datum           d;
8667                 char       *val;
8668                 char       *eqsgn;
8669                 bool            isnull;
8670
8671                 d = array_ref(array, 1, &i,
8672                                           -1 /* varlenarray */ ,
8673                                           -1 /* TEXT's typlen */ ,
8674                                           false /* TEXT's typbyval */ ,
8675                                           'i' /* TEXT's typalign */ ,
8676                                           &isnull);
8677                 if (isnull)
8678                         continue;
8679                 val = TextDatumGetCString(d);
8680
8681                 eqsgn = strchr(val, '=');
8682                 *eqsgn = '\0';
8683
8684                 /* skip if we have permission to delete it */
8685                 if (validate_option_array_item(val, NULL, true))
8686                         continue;
8687
8688                 /* else add it to the output array */
8689                 if (newarray)
8690                         newarray = array_set(newarray, 1, &index,
8691                                                                  d,
8692                                                                  false,
8693                                                                  -1 /* varlenarray */ ,
8694                                                                  -1 /* TEXT's typlen */ ,
8695                                                                  false /* TEXT's typbyval */ ,
8696                                                                  'i' /* TEXT's typalign */ );
8697                 else
8698                         newarray = construct_array(&d, 1,
8699                                                                            TEXTOID,
8700                                                                            -1, false, 'i');
8701
8702                 index++;
8703                 pfree(val);
8704         }
8705
8706         return newarray;
8707 }
8708
8709 /*
8710  * Validate a proposed option setting for GUCArrayAdd/Delete/Reset.
8711  *
8712  * name is the option name.  value is the proposed value for the Add case,
8713  * or NULL for the Delete/Reset cases.  If skipIfNoPermissions is true, it's
8714  * not an error to have no permissions to set the option.
8715  *
8716  * Returns TRUE if OK, FALSE if skipIfNoPermissions is true and user does not
8717  * have permission to change this option (all other error cases result in an
8718  * error being thrown).
8719  */
8720 static bool
8721 validate_option_array_item(const char *name, const char *value,
8722                                                    bool skipIfNoPermissions)
8723
8724 {
8725         struct config_generic *gconf;
8726
8727         /*
8728          * There are three cases to consider:
8729          *
8730          * name is a known GUC variable.  Check the value normally, check
8731          * permissions normally (ie, allow if variable is USERSET, or if it's
8732          * SUSET and user is superuser).
8733          *
8734          * name is not known, but exists or can be created as a placeholder (i.e.,
8735          * it has a prefixed name).  We allow this case if you're a superuser,
8736          * otherwise not.  Superusers are assumed to know what they're doing. We
8737          * can't allow it for other users, because when the placeholder is
8738          * resolved it might turn out to be a SUSET variable;
8739          * define_custom_variable assumes we checked that.
8740          *
8741          * name is not known and can't be created as a placeholder.  Throw error,
8742          * unless skipIfNoPermissions is true, in which case return FALSE.
8743          */
8744         gconf = find_option(name, true, WARNING);
8745         if (!gconf)
8746         {
8747                 /* not known, failed to make a placeholder */
8748                 if (skipIfNoPermissions)
8749                         return false;
8750                 ereport(ERROR,
8751                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
8752                                  errmsg("unrecognized configuration parameter \"%s\"",
8753                                                 name)));
8754         }
8755
8756         if (gconf->flags & GUC_CUSTOM_PLACEHOLDER)
8757         {
8758                 /*
8759                  * We cannot do any meaningful check on the value, so only permissions
8760                  * are useful to check.
8761                  */
8762                 if (superuser())
8763                         return true;
8764                 if (skipIfNoPermissions)
8765                         return false;
8766                 ereport(ERROR,
8767                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
8768                                  errmsg("permission denied to set parameter \"%s\"", name)));
8769         }
8770
8771         /* manual permissions check so we can avoid an error being thrown */
8772         if (gconf->context == PGC_USERSET)
8773                  /* ok */ ;
8774         else if (gconf->context == PGC_SUSET && superuser())
8775                  /* ok */ ;
8776         else if (skipIfNoPermissions)
8777                 return false;
8778         /* if a permissions error should be thrown, let set_config_option do it */
8779
8780         /* test for permissions and valid option value */
8781         (void) set_config_option(name, value,
8782                                                          superuser() ? PGC_SUSET : PGC_USERSET,
8783                                                          PGC_S_TEST, GUC_ACTION_SET, false, 0);
8784
8785         return true;
8786 }
8787
8788
8789 /*
8790  * Called by check_hooks that want to override the normal
8791  * ERRCODE_INVALID_PARAMETER_VALUE SQLSTATE for check hook failures.
8792  *
8793  * Note that GUC_check_errmsg() etc are just macros that result in a direct
8794  * assignment to the associated variables.  That is ugly, but forced by the
8795  * limitations of C's macro mechanisms.
8796  */
8797 void
8798 GUC_check_errcode(int sqlerrcode)
8799 {
8800         GUC_check_errcode_value = sqlerrcode;
8801 }
8802
8803
8804 /*
8805  * Convenience functions to manage calling a variable's check_hook.
8806  * These mostly take care of the protocol for letting check hooks supply
8807  * portions of the error report on failure.
8808  */
8809
8810 static bool
8811 call_bool_check_hook(struct config_bool * conf, bool *newval, void **extra,
8812                                          GucSource source, int elevel)
8813 {
8814         /* Quick success if no hook */
8815         if (!conf->check_hook)
8816                 return true;
8817
8818         /* Reset variables that might be set by hook */
8819         GUC_check_errcode_value = ERRCODE_INVALID_PARAMETER_VALUE;
8820         GUC_check_errmsg_string = NULL;
8821         GUC_check_errdetail_string = NULL;
8822         GUC_check_errhint_string = NULL;
8823
8824         if (!(*conf->check_hook) (newval, extra, source))
8825         {
8826                 ereport(elevel,
8827                                 (errcode(GUC_check_errcode_value),
8828                                  GUC_check_errmsg_string ?
8829                                  errmsg_internal("%s", GUC_check_errmsg_string) :
8830                                  errmsg("invalid value for parameter \"%s\": %d",
8831                                                 conf->gen.name, (int) *newval),
8832                                  GUC_check_errdetail_string ?
8833                                  errdetail_internal("%s", GUC_check_errdetail_string) : 0,
8834                                  GUC_check_errhint_string ?
8835                                  errhint("%s", GUC_check_errhint_string) : 0));
8836                 /* Flush any strings created in ErrorContext */
8837                 FlushErrorState();
8838                 return false;
8839         }
8840
8841         return true;
8842 }
8843
8844 static bool
8845 call_int_check_hook(struct config_int * conf, int *newval, void **extra,
8846                                         GucSource source, int elevel)
8847 {
8848         /* Quick success if no hook */
8849         if (!conf->check_hook)
8850                 return true;
8851
8852         /* Reset variables that might be set by hook */
8853         GUC_check_errcode_value = ERRCODE_INVALID_PARAMETER_VALUE;
8854         GUC_check_errmsg_string = NULL;
8855         GUC_check_errdetail_string = NULL;
8856         GUC_check_errhint_string = NULL;
8857
8858         if (!(*conf->check_hook) (newval, extra, source))
8859         {
8860                 ereport(elevel,
8861                                 (errcode(GUC_check_errcode_value),
8862                                  GUC_check_errmsg_string ?
8863                                  errmsg_internal("%s", GUC_check_errmsg_string) :
8864                                  errmsg("invalid value for parameter \"%s\": %d",
8865                                                 conf->gen.name, *newval),
8866                                  GUC_check_errdetail_string ?
8867                                  errdetail_internal("%s", GUC_check_errdetail_string) : 0,
8868                                  GUC_check_errhint_string ?
8869                                  errhint("%s", GUC_check_errhint_string) : 0));
8870                 /* Flush any strings created in ErrorContext */
8871                 FlushErrorState();
8872                 return false;
8873         }
8874
8875         return true;
8876 }
8877
8878 static bool
8879 call_real_check_hook(struct config_real * conf, double *newval, void **extra,
8880                                          GucSource source, int elevel)
8881 {
8882         /* Quick success if no hook */
8883         if (!conf->check_hook)
8884                 return true;
8885
8886         /* Reset variables that might be set by hook */
8887         GUC_check_errcode_value = ERRCODE_INVALID_PARAMETER_VALUE;
8888         GUC_check_errmsg_string = NULL;
8889         GUC_check_errdetail_string = NULL;
8890         GUC_check_errhint_string = NULL;
8891
8892         if (!(*conf->check_hook) (newval, extra, source))
8893         {
8894                 ereport(elevel,
8895                                 (errcode(GUC_check_errcode_value),
8896                                  GUC_check_errmsg_string ?
8897                                  errmsg_internal("%s", GUC_check_errmsg_string) :
8898                                  errmsg("invalid value for parameter \"%s\": %g",
8899                                                 conf->gen.name, *newval),
8900                                  GUC_check_errdetail_string ?
8901                                  errdetail_internal("%s", GUC_check_errdetail_string) : 0,
8902                                  GUC_check_errhint_string ?
8903                                  errhint("%s", GUC_check_errhint_string) : 0));
8904                 /* Flush any strings created in ErrorContext */
8905                 FlushErrorState();
8906                 return false;
8907         }
8908
8909         return true;
8910 }
8911
8912 static bool
8913 call_string_check_hook(struct config_string * conf, char **newval, void **extra,
8914                                            GucSource source, int elevel)
8915 {
8916         /* Quick success if no hook */
8917         if (!conf->check_hook)
8918                 return true;
8919
8920         /* Reset variables that might be set by hook */
8921         GUC_check_errcode_value = ERRCODE_INVALID_PARAMETER_VALUE;
8922         GUC_check_errmsg_string = NULL;
8923         GUC_check_errdetail_string = NULL;
8924         GUC_check_errhint_string = NULL;
8925
8926         if (!(*conf->check_hook) (newval, extra, source))
8927         {
8928                 ereport(elevel,
8929                                 (errcode(GUC_check_errcode_value),
8930                                  GUC_check_errmsg_string ?
8931                                  errmsg_internal("%s", GUC_check_errmsg_string) :
8932                                  errmsg("invalid value for parameter \"%s\": \"%s\"",
8933                                                 conf->gen.name, *newval ? *newval : ""),
8934                                  GUC_check_errdetail_string ?
8935                                  errdetail_internal("%s", GUC_check_errdetail_string) : 0,
8936                                  GUC_check_errhint_string ?
8937                                  errhint("%s", GUC_check_errhint_string) : 0));
8938                 /* Flush any strings created in ErrorContext */
8939                 FlushErrorState();
8940                 return false;
8941         }
8942
8943         return true;
8944 }
8945
8946 static bool
8947 call_enum_check_hook(struct config_enum * conf, int *newval, void **extra,
8948                                          GucSource source, int elevel)
8949 {
8950         /* Quick success if no hook */
8951         if (!conf->check_hook)
8952                 return true;
8953
8954         /* Reset variables that might be set by hook */
8955         GUC_check_errcode_value = ERRCODE_INVALID_PARAMETER_VALUE;
8956         GUC_check_errmsg_string = NULL;
8957         GUC_check_errdetail_string = NULL;
8958         GUC_check_errhint_string = NULL;
8959
8960         if (!(*conf->check_hook) (newval, extra, source))
8961         {
8962                 ereport(elevel,
8963                                 (errcode(GUC_check_errcode_value),
8964                                  GUC_check_errmsg_string ?
8965                                  errmsg_internal("%s", GUC_check_errmsg_string) :
8966                                  errmsg("invalid value for parameter \"%s\": \"%s\"",
8967                                                 conf->gen.name,
8968                                                 config_enum_lookup_by_value(conf, *newval)),
8969                                  GUC_check_errdetail_string ?
8970                                  errdetail_internal("%s", GUC_check_errdetail_string) : 0,
8971                                  GUC_check_errhint_string ?
8972                                  errhint("%s", GUC_check_errhint_string) : 0));
8973                 /* Flush any strings created in ErrorContext */
8974                 FlushErrorState();
8975                 return false;
8976         }
8977
8978         return true;
8979 }
8980
8981
8982 /*
8983  * check_hook, assign_hook and show_hook subroutines
8984  */
8985
8986 static bool
8987 check_log_destination(char **newval, void **extra, GucSource source)
8988 {
8989         char       *rawstring;
8990         List       *elemlist;
8991         ListCell   *l;
8992         int                     newlogdest = 0;
8993         int                *myextra;
8994
8995         /* Need a modifiable copy of string */
8996         rawstring = pstrdup(*newval);
8997
8998         /* Parse string into list of identifiers */
8999         if (!SplitIdentifierString(rawstring, ',', &elemlist))
9000         {
9001                 /* syntax error in list */
9002                 GUC_check_errdetail("List syntax is invalid.");
9003                 pfree(rawstring);
9004                 list_free(elemlist);
9005                 return false;
9006         }
9007
9008         foreach(l, elemlist)
9009         {
9010                 char       *tok = (char *) lfirst(l);
9011
9012                 if (pg_strcasecmp(tok, "stderr") == 0)
9013                         newlogdest |= LOG_DESTINATION_STDERR;
9014                 else if (pg_strcasecmp(tok, "csvlog") == 0)
9015                         newlogdest |= LOG_DESTINATION_CSVLOG;
9016 #ifdef HAVE_SYSLOG
9017                 else if (pg_strcasecmp(tok, "syslog") == 0)
9018                         newlogdest |= LOG_DESTINATION_SYSLOG;
9019 #endif
9020 #ifdef WIN32
9021                 else if (pg_strcasecmp(tok, "eventlog") == 0)
9022                         newlogdest |= LOG_DESTINATION_EVENTLOG;
9023 #endif
9024                 else
9025                 {
9026                         GUC_check_errdetail("Unrecognized key word: \"%s\".", tok);
9027                         pfree(rawstring);
9028                         list_free(elemlist);
9029                         return false;
9030                 }
9031         }
9032
9033         pfree(rawstring);
9034         list_free(elemlist);
9035
9036         myextra = (int *) guc_malloc(ERROR, sizeof(int));
9037         *myextra = newlogdest;
9038         *extra = (void *) myextra;
9039
9040         return true;
9041 }
9042
9043 static void
9044 assign_log_destination(const char *newval, void *extra)
9045 {
9046         Log_destination = *((int *) extra);
9047 }
9048
9049 static void
9050 assign_syslog_facility(int newval, void *extra)
9051 {
9052 #ifdef HAVE_SYSLOG
9053         set_syslog_parameters(syslog_ident_str ? syslog_ident_str : "postgres",
9054                                                   newval);
9055 #endif
9056         /* Without syslog support, just ignore it */
9057 }
9058
9059 static void
9060 assign_syslog_ident(const char *newval, void *extra)
9061 {
9062 #ifdef HAVE_SYSLOG
9063         set_syslog_parameters(newval, syslog_facility);
9064 #endif
9065         /* Without syslog support, it will always be set to "none", so ignore */
9066 }
9067
9068
9069 static void
9070 assign_session_replication_role(int newval, void *extra)
9071 {
9072         /*
9073          * Must flush the plan cache when changing replication role; but don't
9074          * flush unnecessarily.
9075          */
9076         if (SessionReplicationRole != newval)
9077                 ResetPlanCache();
9078 }
9079
9080 static bool
9081 check_temp_buffers(int *newval, void **extra, GucSource source)
9082 {
9083         /*
9084          * Once local buffers have been initialized, it's too late to change this.
9085          */
9086         if (NLocBuffer && NLocBuffer != *newval)
9087         {
9088                 GUC_check_errdetail("\"temp_buffers\" cannot be changed after any temporary tables have been accessed in the session.");
9089                 return false;
9090         }
9091         return true;
9092 }
9093
9094 static bool
9095 check_phony_autocommit(bool *newval, void **extra, GucSource source)
9096 {
9097         if (!*newval)
9098         {
9099                 GUC_check_errcode(ERRCODE_FEATURE_NOT_SUPPORTED);
9100                 GUC_check_errmsg("SET AUTOCOMMIT TO OFF is no longer supported");
9101                 return false;
9102         }
9103         return true;
9104 }
9105
9106 static bool
9107 check_debug_assertions(bool *newval, void **extra, GucSource source)
9108 {
9109 #ifndef USE_ASSERT_CHECKING
9110         if (*newval)
9111         {
9112                 GUC_check_errmsg("assertion checking is not supported by this build");
9113                 return false;
9114         }
9115 #endif
9116         return true;
9117 }
9118
9119 static bool
9120 check_bonjour(bool *newval, void **extra, GucSource source)
9121 {
9122 #ifndef USE_BONJOUR
9123         if (*newval)
9124         {
9125                 GUC_check_errmsg("Bonjour is not supported by this build");
9126                 return false;
9127         }
9128 #endif
9129         return true;
9130 }
9131
9132 static bool
9133 check_ssl(bool *newval, void **extra, GucSource source)
9134 {
9135 #ifndef USE_SSL
9136         if (*newval)
9137         {
9138                 GUC_check_errmsg("SSL is not supported by this build");
9139                 return false;
9140         }
9141 #endif
9142         return true;
9143 }
9144
9145 static bool
9146 check_stage_log_stats(bool *newval, void **extra, GucSource source)
9147 {
9148         if (*newval && log_statement_stats)
9149         {
9150                 GUC_check_errdetail("Cannot enable parameter when \"log_statement_stats\" is true.");
9151                 return false;
9152         }
9153         return true;
9154 }
9155
9156 static bool
9157 check_log_stats(bool *newval, void **extra, GucSource source)
9158 {
9159         if (*newval &&
9160                 (log_parser_stats || log_planner_stats || log_executor_stats))
9161         {
9162                 GUC_check_errdetail("Cannot enable \"log_statement_stats\" when "
9163                                                         "\"log_parser_stats\", \"log_planner_stats\", "
9164                                                         "or \"log_executor_stats\" is true.");
9165                 return false;
9166         }
9167         return true;
9168 }
9169
9170 static bool
9171 check_canonical_path(char **newval, void **extra, GucSource source)
9172 {
9173         /*
9174          * Since canonicalize_path never enlarges the string, we can just modify
9175          * newval in-place.  But watch out for NULL, which is the default value
9176          * for external_pid_file.
9177          */
9178         if (*newval)
9179                 canonicalize_path(*newval);
9180         return true;
9181 }
9182
9183 static bool
9184 check_timezone_abbreviations(char **newval, void **extra, GucSource source)
9185 {
9186         /*
9187          * The boot_val given above for timezone_abbreviations is NULL. When we
9188          * see this we just do nothing.  If this value isn't overridden from the
9189          * config file then pg_timezone_abbrev_initialize() will eventually
9190          * replace it with "Default".  This hack has two purposes: to avoid
9191          * wasting cycles loading values that might soon be overridden from the
9192          * config file, and to avoid trying to read the timezone abbrev files
9193          * during InitializeGUCOptions().  The latter doesn't work in an
9194          * EXEC_BACKEND subprocess because my_exec_path hasn't been set yet and so
9195          * we can't locate PGSHAREDIR.
9196          */
9197         if (*newval == NULL)
9198         {
9199                 Assert(source == PGC_S_DEFAULT);
9200                 return true;
9201         }
9202
9203         /* OK, load the file and produce a malloc'd TimeZoneAbbrevTable */
9204         *extra = load_tzoffsets(*newval);
9205
9206         /* tzparser.c returns NULL on failure, reporting via GUC_check_errmsg */
9207         if (!*extra)
9208                 return false;
9209
9210         return true;
9211 }
9212
9213 static void
9214 assign_timezone_abbreviations(const char *newval, void *extra)
9215 {
9216         /* Do nothing for the boot_val default of NULL */
9217         if (!extra)
9218                 return;
9219
9220         InstallTimeZoneAbbrevs((TimeZoneAbbrevTable *) extra);
9221 }
9222
9223 /*
9224  * pg_timezone_abbrev_initialize --- set default value if not done already
9225  *
9226  * This is called after initial loading of postgresql.conf.  If no
9227  * timezone_abbreviations setting was found therein, select default.
9228  * If a non-default value is already installed, nothing will happen.
9229  *
9230  * This can also be called from ProcessConfigFile to establish the default
9231  * value after a postgresql.conf entry for it is removed.
9232  */
9233 static void
9234 pg_timezone_abbrev_initialize(void)
9235 {
9236         SetConfigOption("timezone_abbreviations", "Default",
9237                                         PGC_POSTMASTER, PGC_S_DYNAMIC_DEFAULT);
9238 }
9239
9240 static const char *
9241 show_archive_command(void)
9242 {
9243         if (XLogArchivingActive())
9244                 return XLogArchiveCommand;
9245         else
9246                 return "(disabled)";
9247 }
9248
9249 static void
9250 assign_tcp_keepalives_idle(int newval, void *extra)
9251 {
9252         /*
9253          * The kernel API provides no way to test a value without setting it; and
9254          * once we set it we might fail to unset it.  So there seems little point
9255          * in fully implementing the check-then-assign GUC API for these
9256          * variables.  Instead we just do the assignment on demand.  pqcomm.c
9257          * reports any problems via elog(LOG).
9258          *
9259          * This approach means that the GUC value might have little to do with the
9260          * actual kernel value, so we use a show_hook that retrieves the kernel
9261          * value rather than trusting GUC's copy.
9262          */
9263         (void) pq_setkeepalivesidle(newval, MyProcPort);
9264 }
9265
9266 static const char *
9267 show_tcp_keepalives_idle(void)
9268 {
9269         /* See comments in assign_tcp_keepalives_idle */
9270         static char nbuf[16];
9271
9272         snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivesidle(MyProcPort));
9273         return nbuf;
9274 }
9275
9276 static void
9277 assign_tcp_keepalives_interval(int newval, void *extra)
9278 {
9279         /* See comments in assign_tcp_keepalives_idle */
9280         (void) pq_setkeepalivesinterval(newval, MyProcPort);
9281 }
9282
9283 static const char *
9284 show_tcp_keepalives_interval(void)
9285 {
9286         /* See comments in assign_tcp_keepalives_idle */
9287         static char nbuf[16];
9288
9289         snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivesinterval(MyProcPort));
9290         return nbuf;
9291 }
9292
9293 static void
9294 assign_tcp_keepalives_count(int newval, void *extra)
9295 {
9296         /* See comments in assign_tcp_keepalives_idle */
9297         (void) pq_setkeepalivescount(newval, MyProcPort);
9298 }
9299
9300 static const char *
9301 show_tcp_keepalives_count(void)
9302 {
9303         /* See comments in assign_tcp_keepalives_idle */
9304         static char nbuf[16];
9305
9306         snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivescount(MyProcPort));
9307         return nbuf;
9308 }
9309
9310 static bool
9311 check_maxconnections(int *newval, void **extra, GucSource source)
9312 {
9313         if (*newval + autovacuum_max_workers + 1 +
9314                 max_worker_processes > MAX_BACKENDS)
9315                 return false;
9316         return true;
9317 }
9318
9319 static bool
9320 check_autovacuum_max_workers(int *newval, void **extra, GucSource source)
9321 {
9322         if (MaxConnections + *newval + 1 + max_worker_processes > MAX_BACKENDS)
9323                 return false;
9324         return true;
9325 }
9326
9327 static bool
9328 check_autovacuum_work_mem(int *newval, void **extra, GucSource source)
9329 {
9330         /*
9331          * -1 indicates fallback.
9332          *
9333          * If we haven't yet changed the boot_val default of -1, just let it be.
9334          * Autovacuum will look to maintenance_work_mem instead.
9335          */
9336         if (*newval == -1)
9337                 return true;
9338
9339         /*
9340          * We clamp manually-set values to at least 1MB.  Since
9341          * maintenance_work_mem is always set to at least this value, do the same
9342          * here.
9343          */
9344         if (*newval < 1024)
9345                 *newval = 1024;
9346
9347         return true;
9348 }
9349
9350 static bool
9351 check_max_worker_processes(int *newval, void **extra, GucSource source)
9352 {
9353         if (MaxConnections + autovacuum_max_workers + 1 + *newval > MAX_BACKENDS)
9354                 return false;
9355         return true;
9356 }
9357
9358 static bool
9359 check_effective_io_concurrency(int *newval, void **extra, GucSource source)
9360 {
9361 #ifdef USE_PREFETCH
9362         double          new_prefetch_pages = 0.0;
9363         int                     i;
9364
9365         /*----------
9366          * The user-visible GUC parameter is the number of drives (spindles),
9367          * which we need to translate to a number-of-pages-to-prefetch target.
9368          * The target value is stashed in *extra and then assigned to the actual
9369          * variable by assign_effective_io_concurrency.
9370          *
9371          * The expected number of prefetch pages needed to keep N drives busy is:
9372          *
9373          * drives |   I/O requests
9374          * -------+----------------
9375          *              1 |   1
9376          *              2 |   2/1 + 2/2 = 3
9377          *              3 |   3/1 + 3/2 + 3/3 = 5 1/2
9378          *              4 |   4/1 + 4/2 + 4/3 + 4/4 = 8 1/3
9379          *              n |   n * H(n)
9380          *
9381          * This is called the "coupon collector problem" and H(n) is called the
9382          * harmonic series.  This could be approximated by n * ln(n), but for
9383          * reasonable numbers of drives we might as well just compute the series.
9384          *
9385          * Alternatively we could set the target to the number of pages necessary
9386          * so that the expected number of active spindles is some arbitrary
9387          * percentage of the total.  This sounds the same but is actually slightly
9388          * different.  The result ends up being ln(1-P)/ln((n-1)/n) where P is
9389          * that desired fraction.
9390          *
9391          * Experimental results show that both of these formulas aren't aggressive
9392          * enough, but we don't really have any better proposals.
9393          *
9394          * Note that if *newval = 0 (disabled), we must set target = 0.
9395          *----------
9396          */
9397
9398         for (i = 1; i <= *newval; i++)
9399                 new_prefetch_pages += (double) *newval / (double) i;
9400
9401         /* This range check shouldn't fail, but let's be paranoid */
9402         if (new_prefetch_pages >= 0.0 && new_prefetch_pages < (double) INT_MAX)
9403         {
9404                 int                *myextra = (int *) guc_malloc(ERROR, sizeof(int));
9405
9406                 *myextra = (int) rint(new_prefetch_pages);
9407                 *extra = (void *) myextra;
9408
9409                 return true;
9410         }
9411         else
9412                 return false;
9413 #else
9414         return true;
9415 #endif   /* USE_PREFETCH */
9416 }
9417
9418 static void
9419 assign_effective_io_concurrency(int newval, void *extra)
9420 {
9421 #ifdef USE_PREFETCH
9422         target_prefetch_pages = *((int *) extra);
9423 #endif   /* USE_PREFETCH */
9424 }
9425
9426 static void
9427 assign_pgstat_temp_directory(const char *newval, void *extra)
9428 {
9429         /* check_canonical_path already canonicalized newval for us */
9430         char       *dname;
9431         char       *tname;
9432         char       *fname;
9433
9434         /* directory */
9435         dname = guc_malloc(ERROR, strlen(newval) + 1);          /* runtime dir */
9436         sprintf(dname, "%s", newval);
9437
9438         /* global stats */
9439         tname = guc_malloc(ERROR, strlen(newval) + 12);         /* /global.tmp */
9440         sprintf(tname, "%s/global.tmp", newval);
9441         fname = guc_malloc(ERROR, strlen(newval) + 13);         /* /global.stat */
9442         sprintf(fname, "%s/global.stat", newval);
9443
9444         if (pgstat_stat_directory)
9445                 free(pgstat_stat_directory);
9446         pgstat_stat_directory = dname;
9447         if (pgstat_stat_tmpname)
9448                 free(pgstat_stat_tmpname);
9449         pgstat_stat_tmpname = tname;
9450         if (pgstat_stat_filename)
9451                 free(pgstat_stat_filename);
9452         pgstat_stat_filename = fname;
9453 }
9454
9455 static bool
9456 check_application_name(char **newval, void **extra, GucSource source)
9457 {
9458         /* Only allow clean ASCII chars in the application name */
9459         char       *p;
9460
9461         for (p = *newval; *p; p++)
9462         {
9463                 if (*p < 32 || *p > 126)
9464                         *p = '?';
9465         }
9466
9467         return true;
9468 }
9469
9470 static void
9471 assign_application_name(const char *newval, void *extra)
9472 {
9473         /* Update the pg_stat_activity view */
9474         pgstat_report_appname(newval);
9475 }
9476
9477 static const char *
9478 show_unix_socket_permissions(void)
9479 {
9480         static char buf[8];
9481
9482         snprintf(buf, sizeof(buf), "%04o", Unix_socket_permissions);
9483         return buf;
9484 }
9485
9486 static const char *
9487 show_log_file_mode(void)
9488 {
9489         static char buf[8];
9490
9491         snprintf(buf, sizeof(buf), "%04o", Log_file_mode);
9492         return buf;
9493 }
9494
9495 #include "guc-file.c"