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