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