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