]> granicus.if.org Git - postgresql/blob - src/backend/utils/misc/guc.c
Remove postmaster.c's check that NBuffers is at least twice MaxBackends.
[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-2008, PostgreSQL Global Development Group
10  * Written by Peter Eisentraut <peter_e@gmx.net>.
11  *
12  * IDENTIFICATION
13  *        $PostgreSQL: pgsql/src/backend/utils/misc/guc.c,v 1.434 2008/03/09 04:56:28 tgl Exp $
14  *
15  *--------------------------------------------------------------------
16  */
17 #include "postgres.h"
18
19 #include <ctype.h>
20 #include <float.h>
21 #include <limits.h>
22 #include <unistd.h>
23 #include <sys/stat.h>
24 #ifdef HAVE_SYSLOG
25 #include <syslog.h>
26 #endif
27
28 #include "access/gin.h"
29 #include "access/transam.h"
30 #include "access/twophase.h"
31 #include "access/xact.h"
32 #include "catalog/namespace.h"
33 #include "commands/async.h"
34 #include "commands/prepare.h"
35 #include "commands/vacuum.h"
36 #include "commands/variable.h"
37 #include "commands/trigger.h"
38 #include "funcapi.h"
39 #include "libpq/auth.h"
40 #include "libpq/pqformat.h"
41 #include "miscadmin.h"
42 #include "optimizer/cost.h"
43 #include "optimizer/geqo.h"
44 #include "optimizer/paths.h"
45 #include "optimizer/planmain.h"
46 #include "parser/gramparse.h"
47 #include "parser/parse_expr.h"
48 #include "parser/parse_relation.h"
49 #include "parser/parse_type.h"
50 #include "parser/scansup.h"
51 #include "pgstat.h"
52 #include "postmaster/autovacuum.h"
53 #include "postmaster/bgwriter.h"
54 #include "postmaster/postmaster.h"
55 #include "postmaster/syslogger.h"
56 #include "postmaster/walwriter.h"
57 #include "storage/fd.h"
58 #include "storage/freespace.h"
59 #include "tcop/tcopprot.h"
60 #include "tsearch/ts_cache.h"
61 #include "utils/builtins.h"
62 #include "utils/guc_tables.h"
63 #include "utils/memutils.h"
64 #include "utils/pg_locale.h"
65 #include "utils/plancache.h"
66 #include "utils/portal.h"
67 #include "utils/ps_status.h"
68 #include "utils/tzparser.h"
69 #include "utils/xml.h"
70
71 #ifndef PG_KRB_SRVTAB
72 #define PG_KRB_SRVTAB ""
73 #endif
74 #ifndef PG_KRB_SRVNAM
75 #define PG_KRB_SRVNAM ""
76 #endif
77
78 #define CONFIG_FILENAME "postgresql.conf"
79 #define HBA_FILENAME    "pg_hba.conf"
80 #define IDENT_FILENAME  "pg_ident.conf"
81
82 #ifdef EXEC_BACKEND
83 #define CONFIG_EXEC_PARAMS "global/config_exec_params"
84 #define CONFIG_EXEC_PARAMS_NEW "global/config_exec_params.new"
85 #endif
86
87 /* upper limit for GUC variables measured in kilobytes of memory */
88 #if SIZEOF_SIZE_T > 4
89 #define MAX_KILOBYTES   INT_MAX
90 #else
91 #define MAX_KILOBYTES   (INT_MAX / 1024)
92 #endif
93
94 #define KB_PER_MB (1024)
95 #define KB_PER_GB (1024*1024)
96
97 #define MS_PER_S 1000
98 #define S_PER_MIN 60
99 #define MS_PER_MIN (1000 * 60)
100 #define MIN_PER_H 60
101 #define S_PER_H (60 * 60)
102 #define MS_PER_H (1000 * 60 * 60)
103 #define MIN_PER_D (60 * 24)
104 #define S_PER_D (60 * 60 * 24)
105 #define MS_PER_D (1000 * 60 * 60 * 24)
106
107 /* XXX these should appear in other modules' header files */
108 extern bool Log_disconnections;
109 extern int      CommitDelay;
110 extern int      CommitSiblings;
111 extern char *default_tablespace;
112 extern char *temp_tablespaces;
113 extern bool synchronize_seqscans;
114 extern bool fullPageWrites;
115
116 #ifdef TRACE_SORT
117 extern bool trace_sort;
118 #endif
119 #ifdef TRACE_SYNCSCAN
120 extern bool trace_syncscan;
121 #endif
122 #ifdef DEBUG_BOUNDED_SORT
123 extern bool optimize_bounded_sort;
124 #endif
125
126 #ifdef USE_SSL
127 extern char *SSLCipherSuites;
128 #endif
129
130
131 static const char *assign_log_destination(const char *value,
132                                            bool doit, GucSource source);
133
134 #ifdef HAVE_SYSLOG
135 static int      syslog_facility = LOG_LOCAL0;
136
137 static const char *assign_syslog_facility(const char *facility,
138                                            bool doit, GucSource source);
139 static const char *assign_syslog_ident(const char *ident,
140                                         bool doit, GucSource source);
141 #endif
142
143 static const char *assign_defaultxactisolevel(const char *newval, bool doit,
144                                                    GucSource source);
145 static const char *assign_session_replication_role(const char *newval, bool doit,
146                                                                 GucSource source);
147 static const char *assign_log_min_messages(const char *newval, bool doit,
148                                                 GucSource source);
149 static const char *assign_client_min_messages(const char *newval,
150                                                    bool doit, GucSource source);
151 static const char *assign_min_error_statement(const char *newval, bool doit,
152                                                    GucSource source);
153 static const char *assign_msglvl(int *var, const char *newval, bool doit,
154                           GucSource source);
155 static const char *assign_log_error_verbosity(const char *newval, bool doit,
156                                                    GucSource source);
157 static const char *assign_log_statement(const char *newval, bool doit,
158                                          GucSource source);
159 static const char *show_num_temp_buffers(void);
160 static bool assign_phony_autocommit(bool newval, bool doit, GucSource source);
161 static const char *assign_custom_variable_classes(const char *newval, bool doit,
162                                                            GucSource source);
163 static bool assign_debug_assertions(bool newval, bool doit, GucSource source);
164 static bool assign_ssl(bool newval, bool doit, GucSource source);
165 static bool assign_stage_log_stats(bool newval, bool doit, GucSource source);
166 static bool assign_log_stats(bool newval, bool doit, GucSource source);
167 static bool assign_transaction_read_only(bool newval, bool doit, GucSource source);
168 static const char *assign_canonical_path(const char *newval, bool doit, GucSource source);
169 static const char *assign_backslash_quote(const char *newval, bool doit, GucSource source);
170 static const char *assign_timezone_abbreviations(const char *newval, bool doit, GucSource source);
171 static const char *assign_xmlbinary(const char *newval, bool doit, GucSource source);
172 static const char *assign_xmloption(const char *newval, bool doit, GucSource source);
173 static const char *show_archive_command(void);
174 static bool assign_tcp_keepalives_idle(int newval, bool doit, GucSource source);
175 static bool assign_tcp_keepalives_interval(int newval, bool doit, GucSource source);
176 static bool assign_tcp_keepalives_count(int newval, bool doit, GucSource source);
177 static const char *show_tcp_keepalives_idle(void);
178 static const char *show_tcp_keepalives_interval(void);
179 static const char *show_tcp_keepalives_count(void);
180 static bool assign_autovacuum_max_workers(int newval, bool doit, GucSource source);
181 static bool assign_maxconnections(int newval, bool doit, GucSource source);
182
183 /*
184  * GUC option variables that are exported from this module
185  */
186 #ifdef USE_ASSERT_CHECKING
187 bool            assert_enabled = true;
188 #else
189 bool            assert_enabled = false;
190 #endif
191 bool            log_duration = false;
192 bool            Debug_print_plan = false;
193 bool            Debug_print_parse = false;
194 bool            Debug_print_rewritten = false;
195 bool            Debug_pretty_print = false;
196 bool            Explain_pretty_print = true;
197
198 bool            log_parser_stats = false;
199 bool            log_planner_stats = false;
200 bool            log_executor_stats = false;
201 bool            log_statement_stats = false;            /* this is sort of all three
202                                                                                                  * above together */
203 bool            log_btree_build_stats = false;
204
205 bool            check_function_bodies = true;
206 bool            default_with_oids = false;
207 bool            SQL_inheritance = true;
208
209 bool            Password_encryption = true;
210
211 int                     log_min_error_statement = ERROR;
212 int                     log_min_messages = NOTICE;
213 int                     client_min_messages = NOTICE;
214 int                     log_min_duration_statement = -1;
215 int                     log_temp_files = -1;
216
217 int                     num_temp_buffers = 1000;
218
219 char       *ConfigFileName;
220 char       *HbaFileName;
221 char       *IdentFileName;
222 char       *external_pid_file;
223
224 int                     tcp_keepalives_idle;
225 int                     tcp_keepalives_interval;
226 int                     tcp_keepalives_count;
227
228 /*
229  * These variables are all dummies that don't do anything, except in some
230  * cases provide the value for SHOW to display.  The real state is elsewhere
231  * and is kept in sync by assign_hooks.
232  */
233 static char *client_min_messages_str;
234 static char *log_min_messages_str;
235 static char *log_error_verbosity_str;
236 static char *log_statement_str;
237 static char *log_min_error_statement_str;
238 static char *log_destination_string;
239
240 #ifdef HAVE_SYSLOG
241 static char *syslog_facility_str;
242 static char *syslog_ident_str;
243 #endif
244 static bool phony_autocommit;
245 static bool session_auth_is_superuser;
246 static double phony_random_seed;
247 static char *backslash_quote_string;
248 static char *client_encoding_string;
249 static char *datestyle_string;
250 static char *default_iso_level_string;
251 static char *session_replication_role_string;
252 static char *locale_collate;
253 static char *locale_ctype;
254 static char *regex_flavor_string;
255 static char *server_encoding_string;
256 static char *server_version_string;
257 static int      server_version_num;
258 static char *timezone_string;
259 static char *log_timezone_string;
260 static char *timezone_abbreviations_string;
261 static char *XactIsoLevel_string;
262 static char *data_directory;
263 static char *custom_variable_classes;
264 static char *xmlbinary_string;
265 static char *xmloption_string;
266 static int      max_function_args;
267 static int      max_index_keys;
268 static int      max_identifier_length;
269 static int      block_size;
270 static bool integer_datetimes;
271
272 /* should be static, but commands/variable.c needs to get at these */
273 char       *role_string;
274 char       *session_authorization_string;
275
276
277 /*
278  * Displayable names for context types (enum GucContext)
279  *
280  * Note: these strings are deliberately not localized.
281  */
282 const char *const GucContext_Names[] =
283 {
284          /* PGC_INTERNAL */ "internal",
285          /* PGC_POSTMASTER */ "postmaster",
286          /* PGC_SIGHUP */ "sighup",
287          /* PGC_BACKEND */ "backend",
288          /* PGC_SUSET */ "superuser",
289          /* PGC_USERSET */ "user"
290 };
291
292 /*
293  * Displayable names for source types (enum GucSource)
294  *
295  * Note: these strings are deliberately not localized.
296  */
297 const char *const GucSource_Names[] =
298 {
299          /* PGC_S_DEFAULT */ "default",
300          /* PGC_S_ENV_VAR */ "environment variable",
301          /* PGC_S_FILE */ "configuration file",
302          /* PGC_S_ARGV */ "command line",
303          /* PGC_S_DATABASE */ "database",
304          /* PGC_S_USER */ "user",
305          /* PGC_S_CLIENT */ "client",
306          /* PGC_S_OVERRIDE */ "override",
307          /* PGC_S_INTERACTIVE */ "interactive",
308          /* PGC_S_TEST */ "test",
309          /* PGC_S_SESSION */ "session"
310 };
311
312 /*
313  * Displayable names for the groupings defined in enum config_group
314  */
315 const char *const config_group_names[] =
316 {
317         /* UNGROUPED */
318         gettext_noop("Ungrouped"),
319         /* FILE_LOCATIONS */
320         gettext_noop("File Locations"),
321         /* CONN_AUTH */
322         gettext_noop("Connections and Authentication"),
323         /* CONN_AUTH_SETTINGS */
324         gettext_noop("Connections and Authentication / Connection Settings"),
325         /* CONN_AUTH_SECURITY */
326         gettext_noop("Connections and Authentication / Security and Authentication"),
327         /* RESOURCES */
328         gettext_noop("Resource Usage"),
329         /* RESOURCES_MEM */
330         gettext_noop("Resource Usage / Memory"),
331         /* RESOURCES_FSM */
332         gettext_noop("Resource Usage / Free Space Map"),
333         /* RESOURCES_KERNEL */
334         gettext_noop("Resource Usage / Kernel Resources"),
335         /* WAL */
336         gettext_noop("Write-Ahead Log"),
337         /* WAL_SETTINGS */
338         gettext_noop("Write-Ahead Log / Settings"),
339         /* WAL_CHECKPOINTS */
340         gettext_noop("Write-Ahead Log / Checkpoints"),
341         /* QUERY_TUNING */
342         gettext_noop("Query Tuning"),
343         /* QUERY_TUNING_METHOD */
344         gettext_noop("Query Tuning / Planner Method Configuration"),
345         /* QUERY_TUNING_COST */
346         gettext_noop("Query Tuning / Planner Cost Constants"),
347         /* QUERY_TUNING_GEQO */
348         gettext_noop("Query Tuning / Genetic Query Optimizer"),
349         /* QUERY_TUNING_OTHER */
350         gettext_noop("Query Tuning / Other Planner Options"),
351         /* LOGGING */
352         gettext_noop("Reporting and Logging"),
353         /* LOGGING_WHERE */
354         gettext_noop("Reporting and Logging / Where to Log"),
355         /* LOGGING_WHEN */
356         gettext_noop("Reporting and Logging / When to Log"),
357         /* LOGGING_WHAT */
358         gettext_noop("Reporting and Logging / What to Log"),
359         /* STATS */
360         gettext_noop("Statistics"),
361         /* STATS_MONITORING */
362         gettext_noop("Statistics / Monitoring"),
363         /* STATS_COLLECTOR */
364         gettext_noop("Statistics / Query and Index Statistics Collector"),
365         /* AUTOVACUUM */
366         gettext_noop("Autovacuum"),
367         /* CLIENT_CONN */
368         gettext_noop("Client Connection Defaults"),
369         /* CLIENT_CONN_STATEMENT */
370         gettext_noop("Client Connection Defaults / Statement Behavior"),
371         /* CLIENT_CONN_LOCALE */
372         gettext_noop("Client Connection Defaults / Locale and Formatting"),
373         /* CLIENT_CONN_OTHER */
374         gettext_noop("Client Connection Defaults / Other Defaults"),
375         /* LOCK_MANAGEMENT */
376         gettext_noop("Lock Management"),
377         /* COMPAT_OPTIONS */
378         gettext_noop("Version and Platform Compatibility"),
379         /* COMPAT_OPTIONS_PREVIOUS */
380         gettext_noop("Version and Platform Compatibility / Previous PostgreSQL Versions"),
381         /* COMPAT_OPTIONS_CLIENT */
382         gettext_noop("Version and Platform Compatibility / Other Platforms and Clients"),
383         /* PRESET_OPTIONS */
384         gettext_noop("Preset Options"),
385         /* CUSTOM_OPTIONS */
386         gettext_noop("Customized Options"),
387         /* DEVELOPER_OPTIONS */
388         gettext_noop("Developer Options"),
389         /* help_config wants this array to be null-terminated */
390         NULL
391 };
392
393 /*
394  * Displayable names for GUC variable types (enum config_type)
395  *
396  * Note: these strings are deliberately not localized.
397  */
398 const char *const config_type_names[] =
399 {
400          /* PGC_BOOL */ "bool",
401          /* PGC_INT */ "integer",
402          /* PGC_REAL */ "real",
403          /* PGC_STRING */ "string"
404 };
405
406
407 /*
408  * Contents of GUC tables
409  *
410  * See src/backend/utils/misc/README for design notes.
411  *
412  * TO ADD AN OPTION:
413  *
414  * 1. Declare a global variable of type bool, int, double, or char*
415  *        and make use of it.
416  *
417  * 2. Decide at what times it's safe to set the option. See guc.h for
418  *        details.
419  *
420  * 3. Decide on a name, a default value, upper and lower bounds (if
421  *        applicable), etc.
422  *
423  * 4. Add a record below.
424  *
425  * 5. Add it to src/backend/utils/misc/postgresql.conf.sample, if
426  *        appropriate.
427  *
428  * 6. Don't forget to document the option (at least in config.sgml).
429  *
430  * 7. If it's a new GUC_LIST option you must edit pg_dumpall.c to ensure
431  *        it is not single quoted at dump time.
432  */
433
434
435 /******** option records follow ********/
436
437 static struct config_bool ConfigureNamesBool[] =
438 {
439         {
440                 {"enable_seqscan", PGC_USERSET, QUERY_TUNING_METHOD,
441                         gettext_noop("Enables the planner's use of sequential-scan plans."),
442                         NULL
443                 },
444                 &enable_seqscan,
445                 true, NULL, NULL
446         },
447         {
448                 {"enable_indexscan", PGC_USERSET, QUERY_TUNING_METHOD,
449                         gettext_noop("Enables the planner's use of index-scan plans."),
450                         NULL
451                 },
452                 &enable_indexscan,
453                 true, NULL, NULL
454         },
455         {
456                 {"enable_bitmapscan", PGC_USERSET, QUERY_TUNING_METHOD,
457                         gettext_noop("Enables the planner's use of bitmap-scan plans."),
458                         NULL
459                 },
460                 &enable_bitmapscan,
461                 true, NULL, NULL
462         },
463         {
464                 {"enable_tidscan", PGC_USERSET, QUERY_TUNING_METHOD,
465                         gettext_noop("Enables the planner's use of TID scan plans."),
466                         NULL
467                 },
468                 &enable_tidscan,
469                 true, NULL, NULL
470         },
471         {
472                 {"enable_sort", PGC_USERSET, QUERY_TUNING_METHOD,
473                         gettext_noop("Enables the planner's use of explicit sort steps."),
474                         NULL
475                 },
476                 &enable_sort,
477                 true, NULL, NULL
478         },
479         {
480                 {"enable_hashagg", PGC_USERSET, QUERY_TUNING_METHOD,
481                         gettext_noop("Enables the planner's use of hashed aggregation plans."),
482                         NULL
483                 },
484                 &enable_hashagg,
485                 true, NULL, NULL
486         },
487         {
488                 {"enable_nestloop", PGC_USERSET, QUERY_TUNING_METHOD,
489                         gettext_noop("Enables the planner's use of nested-loop join plans."),
490                         NULL
491                 },
492                 &enable_nestloop,
493                 true, NULL, NULL
494         },
495         {
496                 {"enable_mergejoin", PGC_USERSET, QUERY_TUNING_METHOD,
497                         gettext_noop("Enables the planner's use of merge join plans."),
498                         NULL
499                 },
500                 &enable_mergejoin,
501                 true, NULL, NULL
502         },
503         {
504                 {"enable_hashjoin", PGC_USERSET, QUERY_TUNING_METHOD,
505                         gettext_noop("Enables the planner's use of hash join plans."),
506                         NULL
507                 },
508                 &enable_hashjoin,
509                 true, NULL, NULL
510         },
511         {
512                 {"constraint_exclusion", PGC_USERSET, QUERY_TUNING_OTHER,
513                         gettext_noop("Enables the planner to use constraints to optimize queries."),
514                         gettext_noop("Child table scans will be skipped if their "
515                                            "constraints guarantee that no rows match the query.")
516                 },
517                 &constraint_exclusion,
518                 false, NULL, NULL
519         },
520         {
521                 {"geqo", PGC_USERSET, QUERY_TUNING_GEQO,
522                         gettext_noop("Enables genetic query optimization."),
523                         gettext_noop("This algorithm attempts to do planning without "
524                                                  "exhaustive searching.")
525                 },
526                 &enable_geqo,
527                 true, NULL, NULL
528         },
529         {
530                 /* Not for general use --- used by SET SESSION AUTHORIZATION */
531                 {"is_superuser", PGC_INTERNAL, UNGROUPED,
532                         gettext_noop("Shows whether the current user is a superuser."),
533                         NULL,
534                         GUC_REPORT | GUC_NO_SHOW_ALL | GUC_NO_RESET_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
535                 },
536                 &session_auth_is_superuser,
537                 false, NULL, NULL
538         },
539         {
540                 {"ssl", PGC_POSTMASTER, CONN_AUTH_SECURITY,
541                         gettext_noop("Enables SSL connections."),
542                         NULL
543                 },
544                 &EnableSSL,
545                 false, assign_ssl, NULL
546         },
547         {
548                 {"fsync", PGC_SIGHUP, WAL_SETTINGS,
549                         gettext_noop("Forces synchronization of updates to disk."),
550                         gettext_noop("The server will use the fsync() system call in several places to make "
551                         "sure that updates are physically written to disk. This insures "
552                                                  "that a database cluster will recover to a consistent state after "
553                                                  "an operating system or hardware crash.")
554                 },
555                 &enableFsync,
556                 true, NULL, NULL
557         },
558         {
559                 {"synchronous_commit", PGC_USERSET, WAL_SETTINGS,
560                         gettext_noop("Sets immediate fsync at commit."),
561                         NULL
562                 },
563                 &XactSyncCommit,
564                 true, NULL, NULL
565         },
566         {
567                 {"zero_damaged_pages", PGC_SUSET, DEVELOPER_OPTIONS,
568                         gettext_noop("Continues processing past damaged page headers."),
569                         gettext_noop("Detection of a damaged page header normally causes PostgreSQL to "
570                                 "report an error, aborting the current transaction. Setting "
571                                                  "zero_damaged_pages to true causes the system to instead report a "
572                                                  "warning, zero out the damaged page, and continue processing. This "
573                                                  "behavior will destroy data, namely all the rows on the damaged page."),
574                         GUC_NOT_IN_SAMPLE
575                 },
576                 &zero_damaged_pages,
577                 false, NULL, NULL
578         },
579         {
580                 {"full_page_writes", PGC_SIGHUP, WAL_SETTINGS,
581                         gettext_noop("Writes full pages to WAL when first modified after a checkpoint."),
582                         gettext_noop("A page write in process during an operating system crash might be "
583                                                  "only partially written to disk.  During recovery, the row changes "
584                           "stored in WAL are not enough to recover.  This option writes "
585                                                  "pages when first modified after a checkpoint to WAL so full recovery "
586                                                  "is possible.")
587                 },
588                 &fullPageWrites,
589                 true, NULL, NULL
590         },
591         {
592                 {"silent_mode", PGC_POSTMASTER, LOGGING_WHEN,
593                         gettext_noop("Runs the server silently."),
594                         gettext_noop("If this parameter is set, the server will automatically run in the "
595                                  "background and any controlling terminals are dissociated.")
596                 },
597                 &SilentMode,
598                 false, NULL, NULL
599         },
600         {
601                 {"log_checkpoints", PGC_SIGHUP, LOGGING_WHAT,
602                         gettext_noop("Logs each checkpoint."),
603                         NULL
604                 },
605                 &log_checkpoints,
606                 false, NULL, NULL
607         },
608         {
609                 {"log_connections", PGC_BACKEND, LOGGING_WHAT,
610                         gettext_noop("Logs each successful connection."),
611                         NULL
612                 },
613                 &Log_connections,
614                 false, NULL, NULL
615         },
616         {
617                 {"log_disconnections", PGC_BACKEND, LOGGING_WHAT,
618                         gettext_noop("Logs end of a session, including duration."),
619                         NULL
620                 },
621                 &Log_disconnections,
622                 false, NULL, NULL
623         },
624         {
625                 {"debug_assertions", PGC_USERSET, DEVELOPER_OPTIONS,
626                         gettext_noop("Turns on various assertion checks."),
627                         gettext_noop("This is a debugging aid."),
628                         GUC_NOT_IN_SAMPLE
629                 },
630                 &assert_enabled,
631 #ifdef USE_ASSERT_CHECKING
632                 true,
633 #else
634                 false,
635 #endif
636                 assign_debug_assertions, NULL
637         },
638         {
639                 /* currently undocumented, so don't show in SHOW ALL */
640                 {"exit_on_error", PGC_USERSET, UNGROUPED,
641                         gettext_noop("No description available."),
642                         NULL,
643                         GUC_NO_SHOW_ALL | GUC_NOT_IN_SAMPLE
644                 },
645                 &ExitOnAnyError,
646                 false, NULL, NULL
647         },
648         {
649                 {"log_duration", PGC_SUSET, LOGGING_WHAT,
650                         gettext_noop("Logs the duration of each completed SQL statement."),
651                         NULL
652                 },
653                 &log_duration,
654                 false, NULL, NULL
655         },
656         {
657                 {"debug_print_parse", PGC_USERSET, LOGGING_WHAT,
658                         gettext_noop("Prints the parse tree to the server log."),
659                         NULL
660                 },
661                 &Debug_print_parse,
662                 false, NULL, NULL
663         },
664         {
665                 {"debug_print_rewritten", PGC_USERSET, LOGGING_WHAT,
666                         gettext_noop("Prints the parse tree after rewriting to server log."),
667                         NULL
668                 },
669                 &Debug_print_rewritten,
670                 false, NULL, NULL
671         },
672         {
673                 {"debug_print_plan", PGC_USERSET, LOGGING_WHAT,
674                         gettext_noop("Prints the execution plan to server log."),
675                         NULL
676                 },
677                 &Debug_print_plan,
678                 false, NULL, NULL
679         },
680         {
681                 {"debug_pretty_print", PGC_USERSET, LOGGING_WHAT,
682                         gettext_noop("Indents parse and plan tree displays."),
683                         NULL
684                 },
685                 &Debug_pretty_print,
686                 false, NULL, NULL
687         },
688         {
689                 {"log_parser_stats", PGC_SUSET, STATS_MONITORING,
690                         gettext_noop("Writes parser performance statistics to the server log."),
691                         NULL
692                 },
693                 &log_parser_stats,
694                 false, assign_stage_log_stats, NULL
695         },
696         {
697                 {"log_planner_stats", PGC_SUSET, STATS_MONITORING,
698                         gettext_noop("Writes planner performance statistics to the server log."),
699                         NULL
700                 },
701                 &log_planner_stats,
702                 false, assign_stage_log_stats, NULL
703         },
704         {
705                 {"log_executor_stats", PGC_SUSET, STATS_MONITORING,
706                         gettext_noop("Writes executor performance statistics to the server log."),
707                         NULL
708                 },
709                 &log_executor_stats,
710                 false, assign_stage_log_stats, NULL
711         },
712         {
713                 {"log_statement_stats", PGC_SUSET, STATS_MONITORING,
714                         gettext_noop("Writes cumulative performance statistics to the server log."),
715                         NULL
716                 },
717                 &log_statement_stats,
718                 false, assign_log_stats, NULL
719         },
720 #ifdef BTREE_BUILD_STATS
721         {
722                 {"log_btree_build_stats", PGC_SUSET, DEVELOPER_OPTIONS,
723                         gettext_noop("No description available."),
724                         NULL,
725                         GUC_NOT_IN_SAMPLE
726                 },
727                 &log_btree_build_stats,
728                 false, NULL, NULL
729         },
730 #endif
731
732         {
733                 {"explain_pretty_print", PGC_USERSET, CLIENT_CONN_OTHER,
734                         gettext_noop("Uses the indented output format for EXPLAIN VERBOSE."),
735                         NULL
736                 },
737                 &Explain_pretty_print,
738                 true, NULL, NULL
739         },
740
741         {
742                 {"track_activities", PGC_SUSET, STATS_COLLECTOR,
743                         gettext_noop("Collects information about executing commands."),
744                         gettext_noop("Enables the collection of information on the currently "
745                                                  "executing command of each session, along with "
746                                                  "the time at which that command began execution.")
747                 },
748                 &pgstat_track_activities,
749                 true, NULL, NULL
750         },
751         {
752                 {"track_counts", PGC_SUSET, STATS_COLLECTOR,
753                         gettext_noop("Collects statistics on database activity."),
754                         NULL
755                 },
756                 &pgstat_track_counts,
757                 true, NULL, NULL
758         },
759
760         {
761                 {"update_process_title", PGC_SUSET, STATS_COLLECTOR,
762                         gettext_noop("Updates the process title to show the active SQL command."),
763                         gettext_noop("Enables updating of the process title every time a new SQL command is received by the server.")
764                 },
765                 &update_process_title,
766                 true, NULL, NULL
767         },
768
769         {
770                 {"autovacuum", PGC_SIGHUP, AUTOVACUUM,
771                         gettext_noop("Starts the autovacuum subprocess."),
772                         NULL
773                 },
774                 &autovacuum_start_daemon,
775                 true, NULL, NULL
776         },
777
778         {
779                 {"trace_notify", PGC_USERSET, DEVELOPER_OPTIONS,
780                         gettext_noop("Generates debugging output for LISTEN and NOTIFY."),
781                         NULL,
782                         GUC_NOT_IN_SAMPLE
783                 },
784                 &Trace_notify,
785                 false, NULL, NULL
786         },
787
788 #ifdef LOCK_DEBUG
789         {
790                 {"trace_locks", PGC_SUSET, DEVELOPER_OPTIONS,
791                         gettext_noop("No description available."),
792                         NULL,
793                         GUC_NOT_IN_SAMPLE
794                 },
795                 &Trace_locks,
796                 false, NULL, NULL
797         },
798         {
799                 {"trace_userlocks", PGC_SUSET, DEVELOPER_OPTIONS,
800                         gettext_noop("No description available."),
801                         NULL,
802                         GUC_NOT_IN_SAMPLE
803                 },
804                 &Trace_userlocks,
805                 false, NULL, NULL
806         },
807         {
808                 {"trace_lwlocks", PGC_SUSET, DEVELOPER_OPTIONS,
809                         gettext_noop("No description available."),
810                         NULL,
811                         GUC_NOT_IN_SAMPLE
812                 },
813                 &Trace_lwlocks,
814                 false, NULL, NULL
815         },
816         {
817                 {"debug_deadlocks", PGC_SUSET, DEVELOPER_OPTIONS,
818                         gettext_noop("No description available."),
819                         NULL,
820                         GUC_NOT_IN_SAMPLE
821                 },
822                 &Debug_deadlocks,
823                 false, NULL, NULL
824         },
825 #endif
826
827         {
828                 {"log_lock_waits", PGC_SUSET, LOGGING_WHAT,
829                         gettext_noop("Logs long lock waits."),
830                         NULL
831                 },
832                 &log_lock_waits,
833                 false, NULL, NULL
834         },
835
836         {
837                 {"log_hostname", PGC_SIGHUP, LOGGING_WHAT,
838                         gettext_noop("Logs the host name in the connection logs."),
839                         gettext_noop("By default, connection logs only show the IP address "
840                                                  "of the connecting host. If you want them to show the host name you "
841                           "can turn this on, but depending on your host name resolution "
842                            "setup it might impose a non-negligible performance penalty.")
843                 },
844                 &log_hostname,
845                 false, NULL, NULL
846         },
847         {
848                 {"sql_inheritance", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
849                         gettext_noop("Causes subtables to be included by default in various commands."),
850                         NULL
851                 },
852                 &SQL_inheritance,
853                 true, NULL, NULL
854         },
855         {
856                 {"password_encryption", PGC_USERSET, CONN_AUTH_SECURITY,
857                         gettext_noop("Encrypt passwords."),
858                         gettext_noop("When a password is specified in CREATE USER or "
859                            "ALTER USER without writing either ENCRYPTED or UNENCRYPTED, "
860                                                  "this parameter determines whether the password is to be encrypted.")
861                 },
862                 &Password_encryption,
863                 true, NULL, NULL
864         },
865         {
866                 {"transform_null_equals", PGC_USERSET, COMPAT_OPTIONS_CLIENT,
867                         gettext_noop("Treats \"expr=NULL\" as \"expr IS NULL\"."),
868                         gettext_noop("When turned on, expressions of the form expr = NULL "
869                            "(or NULL = expr) are treated as expr IS NULL, that is, they "
870                                 "return true if expr evaluates to the null value, and false "
871                            "otherwise. The correct behavior of expr = NULL is to always "
872                                                  "return null (unknown).")
873                 },
874                 &Transform_null_equals,
875                 false, NULL, NULL
876         },
877         {
878                 {"db_user_namespace", PGC_SIGHUP, CONN_AUTH_SECURITY,
879                         gettext_noop("Enables per-database user names."),
880                         NULL
881                 },
882                 &Db_user_namespace,
883                 false, NULL, NULL
884         },
885         {
886                 /* only here for backwards compatibility */
887                 {"autocommit", PGC_USERSET, CLIENT_CONN_STATEMENT,
888                         gettext_noop("This parameter doesn't do anything."),
889                         gettext_noop("It's just here so that we won't choke on SET AUTOCOMMIT TO ON from 7.3-vintage clients."),
890                         GUC_NO_SHOW_ALL | GUC_NOT_IN_SAMPLE
891                 },
892                 &phony_autocommit,
893                 true, assign_phony_autocommit, NULL
894         },
895         {
896                 {"default_transaction_read_only", PGC_USERSET, CLIENT_CONN_STATEMENT,
897                         gettext_noop("Sets the default read-only status of new transactions."),
898                         NULL
899                 },
900                 &DefaultXactReadOnly,
901                 false, NULL, NULL
902         },
903         {
904                 {"transaction_read_only", PGC_USERSET, CLIENT_CONN_STATEMENT,
905                         gettext_noop("Sets the current transaction's read-only status."),
906                         NULL,
907                         GUC_NO_RESET_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
908                 },
909                 &XactReadOnly,
910                 false, assign_transaction_read_only, NULL
911         },
912         {
913                 {"add_missing_from", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
914                         gettext_noop("Automatically adds missing table references to FROM clauses."),
915                         NULL
916                 },
917                 &add_missing_from,
918                 false, NULL, NULL
919         },
920         {
921                 {"check_function_bodies", PGC_USERSET, CLIENT_CONN_STATEMENT,
922                         gettext_noop("Check function bodies during CREATE FUNCTION."),
923                         NULL
924                 },
925                 &check_function_bodies,
926                 true, NULL, NULL
927         },
928         {
929                 {"array_nulls", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
930                         gettext_noop("Enable input of NULL elements in arrays."),
931                         gettext_noop("When turned on, unquoted NULL in an array input "
932                                                  "value means a null value; "
933                                                  "otherwise it is taken literally.")
934                 },
935                 &Array_nulls,
936                 true, NULL, NULL
937         },
938         {
939                 {"default_with_oids", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
940                         gettext_noop("Create new tables with OIDs by default."),
941                         NULL
942                 },
943                 &default_with_oids,
944                 false, NULL, NULL
945         },
946         {
947                 {"logging_collector", PGC_POSTMASTER, LOGGING_WHERE,
948                         gettext_noop("Start a subprocess to capture stderr output and/or csvlogs into log files."),
949                         NULL
950                 },
951                 &Logging_collector,
952                 false, NULL, NULL
953         },
954         {
955                 {"log_truncate_on_rotation", PGC_SIGHUP, LOGGING_WHERE,
956                         gettext_noop("Truncate existing log files of same name during log rotation."),
957                         NULL
958                 },
959                 &Log_truncate_on_rotation,
960                 false, NULL, NULL
961         },
962
963 #ifdef TRACE_SORT
964         {
965                 {"trace_sort", PGC_USERSET, DEVELOPER_OPTIONS,
966                         gettext_noop("Emit information about resource usage in sorting."),
967                         NULL,
968                         GUC_NOT_IN_SAMPLE
969                 },
970                 &trace_sort,
971                 false, NULL, NULL
972         },
973 #endif
974
975 #ifdef TRACE_SYNCSCAN
976         /* this is undocumented because not exposed in a standard build */
977         {
978                 {"trace_syncscan", PGC_USERSET, DEVELOPER_OPTIONS,
979                         gettext_noop("Generate debugging output for synchronized scanning."),
980                         NULL,
981                         GUC_NOT_IN_SAMPLE
982                 },
983                 &trace_syncscan,
984                 false, NULL, NULL
985         },
986 #endif
987
988 #ifdef DEBUG_BOUNDED_SORT
989         /* this is undocumented because not exposed in a standard build */
990         {
991                 {
992                         "optimize_bounded_sort", PGC_USERSET, QUERY_TUNING_METHOD,
993                         gettext_noop("Enable bounded sorting using heap sort."),
994                         NULL,
995                         GUC_NOT_IN_SAMPLE
996                 },
997                 &optimize_bounded_sort,
998                 true, NULL, NULL
999         },
1000 #endif
1001
1002 #ifdef WAL_DEBUG
1003         {
1004                 {"wal_debug", PGC_SUSET, DEVELOPER_OPTIONS,
1005                         gettext_noop("Emit WAL-related debugging output."),
1006                         NULL,
1007                         GUC_NOT_IN_SAMPLE
1008                 },
1009                 &XLOG_DEBUG,
1010                 false, NULL, NULL
1011         },
1012 #endif
1013
1014         {
1015                 {"integer_datetimes", PGC_INTERNAL, PRESET_OPTIONS,
1016                         gettext_noop("Datetimes are integer based."),
1017                         NULL,
1018                         GUC_REPORT | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
1019                 },
1020                 &integer_datetimes,
1021 #ifdef HAVE_INT64_TIMESTAMP
1022                 true, NULL, NULL
1023 #else
1024                 false, NULL, NULL
1025 #endif
1026         },
1027
1028         {
1029                 {"krb_caseins_users", PGC_POSTMASTER, CONN_AUTH_SECURITY,
1030                         gettext_noop("Sets whether Kerberos and GSSAPI user names should be treated as case-insensitive."),
1031                         NULL
1032                 },
1033                 &pg_krb_caseins_users,
1034                 false, NULL, NULL
1035         },
1036
1037         {
1038                 {"escape_string_warning", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
1039                         gettext_noop("Warn about backslash escapes in ordinary string literals."),
1040                         NULL
1041                 },
1042                 &escape_string_warning,
1043                 true, NULL, NULL
1044         },
1045
1046         {
1047                 {"standard_conforming_strings", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
1048                         gettext_noop("Causes '...' strings to treat backslashes literally."),
1049                         NULL,
1050                         GUC_REPORT
1051                 },
1052                 &standard_conforming_strings,
1053                 false, NULL, NULL
1054         },
1055
1056         {
1057                 {"synchronize_seqscans", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
1058                         gettext_noop("Enable synchronized sequential scans."),
1059                         NULL
1060                 },
1061                 &synchronize_seqscans,
1062                 true, NULL, NULL
1063         },
1064
1065         {
1066                 {"archive_mode", PGC_POSTMASTER, WAL_SETTINGS,
1067                         gettext_noop("Allows archiving of WAL files using archive_command."),
1068                         NULL
1069                 },
1070                 &XLogArchiveMode,
1071                 false, NULL, NULL
1072         },
1073
1074         {
1075                 {"allow_system_table_mods", PGC_POSTMASTER, DEVELOPER_OPTIONS,
1076                         gettext_noop("Allows modifications of the structure of system tables."),
1077                         NULL,
1078                         GUC_NOT_IN_SAMPLE
1079                 },
1080                 &allowSystemTableMods,
1081                 false, NULL, NULL
1082         },
1083
1084         {
1085                 {"ignore_system_indexes", PGC_BACKEND, DEVELOPER_OPTIONS,
1086                         gettext_noop("Disables reading from system indexes."),
1087                         gettext_noop("It does not prevent updating the indexes, so it is safe "
1088                                                  "to use.  The worst consequence is slowness."),
1089                         GUC_NOT_IN_SAMPLE
1090                 },
1091                 &IgnoreSystemIndexes,
1092                 false, NULL, NULL
1093         },
1094
1095         /* End-of-list marker */
1096         {
1097                 {NULL, 0, 0, NULL, NULL}, NULL, false, NULL, NULL
1098         }
1099 };
1100
1101
1102 static struct config_int ConfigureNamesInt[] =
1103 {
1104         {
1105                 {"archive_timeout", PGC_SIGHUP, WAL_SETTINGS,
1106                         gettext_noop("Forces a switch to the next xlog file if a "
1107                                                  "new file has not been started within N seconds."),
1108                         NULL,
1109                         GUC_UNIT_S
1110                 },
1111                 &XLogArchiveTimeout,
1112                 0, 0, INT_MAX, NULL, NULL
1113         },
1114         {
1115                 {"post_auth_delay", PGC_BACKEND, DEVELOPER_OPTIONS,
1116                         gettext_noop("Waits N seconds on connection startup after authentication."),
1117                         gettext_noop("This allows attaching a debugger to the process."),
1118                         GUC_NOT_IN_SAMPLE | GUC_UNIT_S
1119                 },
1120                 &PostAuthDelay,
1121                 0, 0, INT_MAX, NULL, NULL
1122         },
1123         {
1124                 {"default_statistics_target", PGC_USERSET, QUERY_TUNING_OTHER,
1125                         gettext_noop("Sets the default statistics target."),
1126                         gettext_noop("This applies to table columns that have not had a "
1127                                 "column-specific target set via ALTER TABLE SET STATISTICS.")
1128                 },
1129                 &default_statistics_target,
1130                 10, 1, 1000, NULL, NULL
1131         },
1132         {
1133                 {"from_collapse_limit", PGC_USERSET, QUERY_TUNING_OTHER,
1134                         gettext_noop("Sets the FROM-list size beyond which subqueries "
1135                                                  "are not collapsed."),
1136                         gettext_noop("The planner will merge subqueries into upper "
1137                                 "queries if the resulting FROM list would have no more than "
1138                                                  "this many items.")
1139                 },
1140                 &from_collapse_limit,
1141                 8, 1, INT_MAX, NULL, NULL
1142         },
1143         {
1144                 {"join_collapse_limit", PGC_USERSET, QUERY_TUNING_OTHER,
1145                         gettext_noop("Sets the FROM-list size beyond which JOIN "
1146                                                  "constructs are not flattened."),
1147                         gettext_noop("The planner will flatten explicit JOIN "
1148                                                  "constructs into lists of FROM items whenever a "
1149                                                  "list of no more than this many items would result.")
1150                 },
1151                 &join_collapse_limit,
1152                 8, 1, INT_MAX, NULL, NULL
1153         },
1154         {
1155                 {"geqo_threshold", PGC_USERSET, QUERY_TUNING_GEQO,
1156                         gettext_noop("Sets the threshold of FROM items beyond which GEQO is used."),
1157                         NULL
1158                 },
1159                 &geqo_threshold,
1160                 12, 2, INT_MAX, NULL, NULL
1161         },
1162         {
1163                 {"geqo_effort", PGC_USERSET, QUERY_TUNING_GEQO,
1164                         gettext_noop("GEQO: effort is used to set the default for other GEQO parameters."),
1165                         NULL
1166                 },
1167                 &Geqo_effort,
1168                 DEFAULT_GEQO_EFFORT, MIN_GEQO_EFFORT, MAX_GEQO_EFFORT, NULL, NULL
1169         },
1170         {
1171                 {"geqo_pool_size", PGC_USERSET, QUERY_TUNING_GEQO,
1172                         gettext_noop("GEQO: number of individuals in the population."),
1173                         gettext_noop("Zero selects a suitable default value.")
1174                 },
1175                 &Geqo_pool_size,
1176                 0, 0, INT_MAX, NULL, NULL
1177         },
1178         {
1179                 {"geqo_generations", PGC_USERSET, QUERY_TUNING_GEQO,
1180                         gettext_noop("GEQO: number of iterations of the algorithm."),
1181                         gettext_noop("Zero selects a suitable default value.")
1182                 },
1183                 &Geqo_generations,
1184                 0, 0, INT_MAX, NULL, NULL
1185         },
1186
1187         {
1188                 {"deadlock_timeout", PGC_SIGHUP, LOCK_MANAGEMENT,
1189                         gettext_noop("Sets the time to wait on a lock before checking for deadlock."),
1190                         NULL,
1191                         GUC_UNIT_MS
1192                 },
1193                 &DeadlockTimeout,
1194                 1000, 1, INT_MAX / 1000, NULL, NULL
1195         },
1196
1197         /*
1198          * Note: MaxBackends is limited to INT_MAX/4 because some places compute
1199          * 4*MaxBackends without any overflow check.  This check is made in
1200          * assign_maxconnections, since MaxBackends is computed as MaxConnections
1201          * plus autovacuum_max_workers.
1202          *
1203          * Likewise we have to limit NBuffers to INT_MAX/2.
1204          */
1205         {
1206                 {"max_connections", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
1207                         gettext_noop("Sets the maximum number of concurrent connections."),
1208                         NULL
1209                 },
1210                 &MaxConnections,
1211                 100, 1, INT_MAX / 4, assign_maxconnections, NULL
1212         },
1213
1214         {
1215                 {"superuser_reserved_connections", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
1216                         gettext_noop("Sets the number of connection slots reserved for superusers."),
1217                         NULL
1218                 },
1219                 &ReservedBackends,
1220                 3, 0, INT_MAX / 4, NULL, NULL
1221         },
1222
1223         {
1224                 {"shared_buffers", PGC_POSTMASTER, RESOURCES_MEM,
1225                         gettext_noop("Sets the number of shared memory buffers used by the server."),
1226                         NULL,
1227                         GUC_UNIT_BLOCKS
1228                 },
1229                 &NBuffers,
1230                 1024, 16, INT_MAX / 2, NULL, NULL
1231         },
1232
1233         {
1234                 {"temp_buffers", PGC_USERSET, RESOURCES_MEM,
1235                         gettext_noop("Sets the maximum number of temporary buffers used by each session."),
1236                         NULL,
1237                         GUC_UNIT_BLOCKS
1238                 },
1239                 &num_temp_buffers,
1240                 1024, 100, INT_MAX / 2, NULL, show_num_temp_buffers
1241         },
1242
1243         {
1244                 {"port", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
1245                         gettext_noop("Sets the TCP port the server listens on."),
1246                         NULL
1247                 },
1248                 &PostPortNumber,
1249                 DEF_PGPORT, 1, 65535, NULL, NULL
1250         },
1251
1252         {
1253                 {"unix_socket_permissions", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
1254                         gettext_noop("Sets the access permissions of the Unix-domain socket."),
1255                         gettext_noop("Unix-domain sockets use the usual Unix file system "
1256                                                  "permission set. The parameter value is expected to be an numeric mode "
1257                                                  "specification in the form accepted by the chmod and umask system "
1258                                                  "calls. (To use the customary octal format the number must start with "
1259                                                  "a 0 (zero).)")
1260                 },
1261                 &Unix_socket_permissions,
1262                 0777, 0000, 0777, NULL, NULL
1263         },
1264
1265         {
1266                 {"work_mem", PGC_USERSET, RESOURCES_MEM,
1267                         gettext_noop("Sets the maximum memory to be used for query workspaces."),
1268                         gettext_noop("This much memory can be used by each internal "
1269                                                  "sort operation and hash table before switching to "
1270                                                  "temporary disk files."),
1271                         GUC_UNIT_KB
1272                 },
1273                 &work_mem,
1274                 1024, 8 * BLCKSZ / 1024, MAX_KILOBYTES, NULL, NULL
1275         },
1276
1277         {
1278                 {"maintenance_work_mem", PGC_USERSET, RESOURCES_MEM,
1279                         gettext_noop("Sets the maximum memory to be used for maintenance operations."),
1280                         gettext_noop("This includes operations such as VACUUM and CREATE INDEX."),
1281                         GUC_UNIT_KB
1282                 },
1283                 &maintenance_work_mem,
1284                 16384, 1024, MAX_KILOBYTES, NULL, NULL
1285         },
1286
1287         {
1288                 {"max_stack_depth", PGC_SUSET, RESOURCES_MEM,
1289                         gettext_noop("Sets the maximum stack depth, in kilobytes."),
1290                         NULL,
1291                         GUC_UNIT_KB
1292                 },
1293                 &max_stack_depth,
1294                 100, 100, MAX_KILOBYTES, assign_max_stack_depth, NULL
1295         },
1296
1297         {
1298                 {"vacuum_cost_page_hit", PGC_USERSET, RESOURCES,
1299                         gettext_noop("Vacuum cost for a page found in the buffer cache."),
1300                         NULL
1301                 },
1302                 &VacuumCostPageHit,
1303                 1, 0, 10000, NULL, NULL
1304         },
1305
1306         {
1307                 {"vacuum_cost_page_miss", PGC_USERSET, RESOURCES,
1308                         gettext_noop("Vacuum cost for a page not found in the buffer cache."),
1309                         NULL
1310                 },
1311                 &VacuumCostPageMiss,
1312                 10, 0, 10000, NULL, NULL
1313         },
1314
1315         {
1316                 {"vacuum_cost_page_dirty", PGC_USERSET, RESOURCES,
1317                         gettext_noop("Vacuum cost for a page dirtied by vacuum."),
1318                         NULL
1319                 },
1320                 &VacuumCostPageDirty,
1321                 20, 0, 10000, NULL, NULL
1322         },
1323
1324         {
1325                 {"vacuum_cost_limit", PGC_USERSET, RESOURCES,
1326                         gettext_noop("Vacuum cost amount available before napping."),
1327                         NULL
1328                 },
1329                 &VacuumCostLimit,
1330                 200, 1, 10000, NULL, NULL
1331         },
1332
1333         {
1334                 {"vacuum_cost_delay", PGC_USERSET, RESOURCES,
1335                         gettext_noop("Vacuum cost delay in milliseconds."),
1336                         NULL,
1337                         GUC_UNIT_MS
1338                 },
1339                 &VacuumCostDelay,
1340                 0, 0, 1000, NULL, NULL
1341         },
1342
1343         {
1344                 {"autovacuum_vacuum_cost_delay", PGC_SIGHUP, AUTOVACUUM,
1345                         gettext_noop("Vacuum cost delay in milliseconds, for autovacuum."),
1346                         NULL,
1347                         GUC_UNIT_MS
1348                 },
1349                 &autovacuum_vac_cost_delay,
1350                 20, -1, 1000, NULL, NULL
1351         },
1352
1353         {
1354                 {"autovacuum_vacuum_cost_limit", PGC_SIGHUP, AUTOVACUUM,
1355                         gettext_noop("Vacuum cost amount available before napping, for autovacuum."),
1356                         NULL
1357                 },
1358                 &autovacuum_vac_cost_limit,
1359                 -1, -1, 10000, NULL, NULL
1360         },
1361
1362         {
1363                 {"max_files_per_process", PGC_POSTMASTER, RESOURCES_KERNEL,
1364                         gettext_noop("Sets the maximum number of simultaneously open files for each server process."),
1365                         NULL
1366                 },
1367                 &max_files_per_process,
1368                 1000, 25, INT_MAX, NULL, NULL
1369         },
1370
1371         {
1372                 {"max_prepared_transactions", PGC_POSTMASTER, RESOURCES,
1373                         gettext_noop("Sets the maximum number of simultaneously prepared transactions."),
1374                         NULL
1375                 },
1376                 &max_prepared_xacts,
1377                 5, 0, INT_MAX, NULL, NULL
1378         },
1379
1380 #ifdef LOCK_DEBUG
1381         {
1382                 {"trace_lock_oidmin", PGC_SUSET, DEVELOPER_OPTIONS,
1383                         gettext_noop("No description available."),
1384                         NULL,
1385                         GUC_NOT_IN_SAMPLE
1386                 },
1387                 &Trace_lock_oidmin,
1388                 FirstNormalObjectId, 0, INT_MAX, NULL, NULL
1389         },
1390         {
1391                 {"trace_lock_table", PGC_SUSET, DEVELOPER_OPTIONS,
1392                         gettext_noop("No description available."),
1393                         NULL,
1394                         GUC_NOT_IN_SAMPLE
1395                 },
1396                 &Trace_lock_table,
1397                 0, 0, INT_MAX, NULL, NULL
1398         },
1399 #endif
1400
1401         {
1402                 {"statement_timeout", PGC_USERSET, CLIENT_CONN_STATEMENT,
1403                         gettext_noop("Sets the maximum allowed duration of any statement."),
1404                         gettext_noop("A value of 0 turns off the timeout."),
1405                         GUC_UNIT_MS
1406                 },
1407                 &StatementTimeout,
1408                 0, 0, INT_MAX, NULL, NULL
1409         },
1410
1411         {
1412                 {"vacuum_freeze_min_age", PGC_USERSET, CLIENT_CONN_STATEMENT,
1413                         gettext_noop("Minimum age at which VACUUM should freeze a table row."),
1414                         NULL
1415                 },
1416                 &vacuum_freeze_min_age,
1417                 100000000, 0, 1000000000, NULL, NULL
1418         },
1419
1420         {
1421                 {"max_fsm_relations", PGC_POSTMASTER, RESOURCES_FSM,
1422                         gettext_noop("Sets the maximum number of tables and indexes for which free space is tracked."),
1423                         NULL
1424                 },
1425                 &MaxFSMRelations,
1426                 1000, 100, INT_MAX, NULL, NULL
1427         },
1428         {
1429                 {"max_fsm_pages", PGC_POSTMASTER, RESOURCES_FSM,
1430                         gettext_noop("Sets the maximum number of disk pages for which free space is tracked."),
1431                         NULL
1432                 },
1433                 &MaxFSMPages,
1434                 20000, 1000, INT_MAX, NULL, NULL
1435         },
1436
1437         {
1438                 {"max_locks_per_transaction", PGC_POSTMASTER, LOCK_MANAGEMENT,
1439                         gettext_noop("Sets the maximum number of locks per transaction."),
1440                         gettext_noop("The shared lock table is sized on the assumption that "
1441                           "at most max_locks_per_transaction * max_connections distinct "
1442                                                  "objects will need to be locked at any one time.")
1443                 },
1444                 &max_locks_per_xact,
1445                 64, 10, INT_MAX, NULL, NULL
1446         },
1447
1448         {
1449                 {"authentication_timeout", PGC_SIGHUP, CONN_AUTH_SECURITY,
1450                         gettext_noop("Sets the maximum allowed time to complete client authentication."),
1451                         NULL,
1452                         GUC_UNIT_S
1453                 },
1454                 &AuthenticationTimeout,
1455                 60, 1, 600, NULL, NULL
1456         },
1457
1458         {
1459                 /* Not for general use */
1460                 {"pre_auth_delay", PGC_SIGHUP, DEVELOPER_OPTIONS,
1461                         gettext_noop("Waits N seconds on connection startup before authentication."),
1462                         gettext_noop("This allows attaching a debugger to the process."),
1463                         GUC_NOT_IN_SAMPLE | GUC_UNIT_S
1464                 },
1465                 &PreAuthDelay,
1466                 0, 0, 60, NULL, NULL
1467         },
1468
1469         {
1470                 {"checkpoint_segments", PGC_SIGHUP, WAL_CHECKPOINTS,
1471                         gettext_noop("Sets the maximum distance in log segments between automatic WAL checkpoints."),
1472                         NULL
1473                 },
1474                 &CheckPointSegments,
1475                 3, 1, INT_MAX, NULL, NULL
1476         },
1477
1478         {
1479                 {"checkpoint_timeout", PGC_SIGHUP, WAL_CHECKPOINTS,
1480                         gettext_noop("Sets the maximum time between automatic WAL checkpoints."),
1481                         NULL,
1482                         GUC_UNIT_S
1483                 },
1484                 &CheckPointTimeout,
1485                 300, 30, 3600, NULL, NULL
1486         },
1487
1488         {
1489                 {"checkpoint_warning", PGC_SIGHUP, WAL_CHECKPOINTS,
1490                         gettext_noop("Enables warnings if checkpoint segments are filled more "
1491                                                  "frequently than this."),
1492                         gettext_noop("Write a message to the server log if checkpoints "
1493                         "caused by the filling of checkpoint segment files happens more "
1494                                                  "frequently than this number of seconds. Zero turns off the warning."),
1495                         GUC_UNIT_S
1496                 },
1497                 &CheckPointWarning,
1498                 30, 0, INT_MAX, NULL, NULL
1499         },
1500
1501         {
1502                 {"wal_buffers", PGC_POSTMASTER, WAL_SETTINGS,
1503                         gettext_noop("Sets the number of disk-page buffers in shared memory for WAL."),
1504                         NULL,
1505                         GUC_UNIT_XBLOCKS
1506                 },
1507                 &XLOGbuffers,
1508                 8, 4, INT_MAX, NULL, NULL
1509         },
1510
1511         {
1512                 {"wal_writer_delay", PGC_SIGHUP, WAL_SETTINGS,
1513                         gettext_noop("WAL writer sleep time between WAL flushes."),
1514                         NULL,
1515                         GUC_UNIT_MS
1516                 },
1517                 &WalWriterDelay,
1518                 200, 1, 10000, NULL, NULL
1519         },
1520
1521         {
1522                 {"commit_delay", PGC_USERSET, WAL_SETTINGS,
1523                         gettext_noop("Sets the delay in microseconds between transaction commit and "
1524                                                  "flushing WAL to disk."),
1525                         NULL
1526                 },
1527                 &CommitDelay,
1528                 0, 0, 100000, NULL, NULL
1529         },
1530
1531         {
1532                 {"commit_siblings", PGC_USERSET, WAL_SETTINGS,
1533                         gettext_noop("Sets the minimum concurrent open transactions before performing "
1534                                                  "commit_delay."),
1535                         NULL
1536                 },
1537                 &CommitSiblings,
1538                 5, 1, 1000, NULL, NULL
1539         },
1540
1541         {
1542                 {"extra_float_digits", PGC_USERSET, CLIENT_CONN_LOCALE,
1543                         gettext_noop("Sets the number of digits displayed for floating-point values."),
1544                         gettext_noop("This affects real, double precision, and geometric data types. "
1545                          "The parameter value is added to the standard number of digits "
1546                                                  "(FLT_DIG or DBL_DIG as appropriate).")
1547                 },
1548                 &extra_float_digits,
1549                 0, -15, 2, NULL, NULL
1550         },
1551
1552         {
1553                 {"log_min_duration_statement", PGC_SUSET, LOGGING_WHEN,
1554                         gettext_noop("Sets the minimum execution time above which "
1555                                                  "statements will be logged."),
1556                         gettext_noop("Zero prints all queries. -1 turns this feature off."),
1557                         GUC_UNIT_MS
1558                 },
1559                 &log_min_duration_statement,
1560                 -1, -1, INT_MAX / 1000, NULL, NULL
1561         },
1562
1563         {
1564                 {"log_autovacuum_min_duration", PGC_SIGHUP, LOGGING_WHAT,
1565                         gettext_noop("Sets the minimum execution time above which "
1566                                                  "autovacuum actions will be logged."),
1567                         gettext_noop("Zero prints all actions. -1 turns autovacuum logging off."),
1568                         GUC_UNIT_MS
1569                 },
1570                 &Log_autovacuum_min_duration,
1571                 -1, -1, INT_MAX / 1000, NULL, NULL
1572         },
1573
1574         {
1575                 {"bgwriter_delay", PGC_SIGHUP, RESOURCES,
1576                         gettext_noop("Background writer sleep time between rounds."),
1577                         NULL,
1578                         GUC_UNIT_MS
1579                 },
1580                 &BgWriterDelay,
1581                 200, 10, 10000, NULL, NULL
1582         },
1583
1584         {
1585                 {"bgwriter_lru_maxpages", PGC_SIGHUP, RESOURCES,
1586                         gettext_noop("Background writer maximum number of LRU pages to flush per round."),
1587                         NULL
1588                 },
1589                 &bgwriter_lru_maxpages,
1590                 100, 0, 1000, NULL, NULL
1591         },
1592
1593         {
1594                 {"log_rotation_age", PGC_SIGHUP, LOGGING_WHERE,
1595                         gettext_noop("Automatic log file rotation will occur after N minutes."),
1596                         NULL,
1597                         GUC_UNIT_MIN
1598                 },
1599                 &Log_RotationAge,
1600                 HOURS_PER_DAY * MINS_PER_HOUR, 0, INT_MAX / MINS_PER_HOUR, NULL, NULL
1601         },
1602
1603         {
1604                 {"log_rotation_size", PGC_SIGHUP, LOGGING_WHERE,
1605                         gettext_noop("Automatic log file rotation will occur after N kilobytes."),
1606                         NULL,
1607                         GUC_UNIT_KB
1608                 },
1609                 &Log_RotationSize,
1610                 10 * 1024, 0, INT_MAX / 1024, NULL, NULL
1611         },
1612
1613         {
1614                 {"max_function_args", PGC_INTERNAL, PRESET_OPTIONS,
1615                         gettext_noop("Shows the maximum number of function arguments."),
1616                         NULL,
1617                         GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
1618                 },
1619                 &max_function_args,
1620                 FUNC_MAX_ARGS, FUNC_MAX_ARGS, FUNC_MAX_ARGS, NULL, NULL
1621         },
1622
1623         {
1624                 {"max_index_keys", PGC_INTERNAL, PRESET_OPTIONS,
1625                         gettext_noop("Shows the maximum number of index keys."),
1626                         NULL,
1627                         GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
1628                 },
1629                 &max_index_keys,
1630                 INDEX_MAX_KEYS, INDEX_MAX_KEYS, INDEX_MAX_KEYS, NULL, NULL
1631         },
1632
1633         {
1634                 {"max_identifier_length", PGC_INTERNAL, PRESET_OPTIONS,
1635                         gettext_noop("Shows the maximum identifier length."),
1636                         NULL,
1637                         GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
1638                 },
1639                 &max_identifier_length,
1640                 NAMEDATALEN - 1, NAMEDATALEN - 1, NAMEDATALEN - 1, NULL, NULL
1641         },
1642
1643         {
1644                 {"block_size", PGC_INTERNAL, PRESET_OPTIONS,
1645                         gettext_noop("Shows the size of a disk block."),
1646                         NULL,
1647                         GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
1648                 },
1649                 &block_size,
1650                 BLCKSZ, BLCKSZ, BLCKSZ, NULL, NULL
1651         },
1652
1653         {
1654                 {"autovacuum_naptime", PGC_SIGHUP, AUTOVACUUM,
1655                         gettext_noop("Time to sleep between autovacuum runs."),
1656                         NULL,
1657                         GUC_UNIT_S
1658                 },
1659                 &autovacuum_naptime,
1660                 60, 1, INT_MAX / 1000, NULL, NULL
1661         },
1662         {
1663                 {"autovacuum_vacuum_threshold", PGC_SIGHUP, AUTOVACUUM,
1664                         gettext_noop("Minimum number of tuple updates or deletes prior to vacuum."),
1665                         NULL
1666                 },
1667                 &autovacuum_vac_thresh,
1668                 50, 0, INT_MAX, NULL, NULL
1669         },
1670         {
1671                 {"autovacuum_analyze_threshold", PGC_SIGHUP, AUTOVACUUM,
1672                         gettext_noop("Minimum number of tuple inserts, updates or deletes prior to analyze."),
1673                         NULL
1674                 },
1675                 &autovacuum_anl_thresh,
1676                 50, 0, INT_MAX, NULL, NULL
1677         },
1678         {
1679                 /* see varsup.c for why this is PGC_POSTMASTER not PGC_SIGHUP */
1680                 {"autovacuum_freeze_max_age", PGC_POSTMASTER, AUTOVACUUM,
1681                         gettext_noop("Age at which to autovacuum a table to prevent transaction ID wraparound."),
1682                         NULL
1683                 },
1684                 &autovacuum_freeze_max_age,
1685                 200000000, 100000000, 2000000000, NULL, NULL
1686         },
1687         {
1688                 /* see max_connections */
1689                 {"autovacuum_max_workers", PGC_POSTMASTER, AUTOVACUUM,
1690                         gettext_noop("Sets the maximum number of simultaneously running autovacuum worker processes."),
1691                         NULL
1692                 },
1693                 &autovacuum_max_workers,
1694                 3, 1, INT_MAX / 4, assign_autovacuum_max_workers, NULL
1695         },
1696
1697         {
1698                 {"tcp_keepalives_idle", PGC_USERSET, CLIENT_CONN_OTHER,
1699                         gettext_noop("Time between issuing TCP keepalives."),
1700                         gettext_noop("A value of 0 uses the system default."),
1701                         GUC_UNIT_S
1702                 },
1703                 &tcp_keepalives_idle,
1704                 0, 0, INT_MAX, assign_tcp_keepalives_idle, show_tcp_keepalives_idle
1705         },
1706
1707         {
1708                 {"tcp_keepalives_interval", PGC_USERSET, CLIENT_CONN_OTHER,
1709                         gettext_noop("Time between TCP keepalive retransmits."),
1710                         gettext_noop("A value of 0 uses the system default."),
1711                         GUC_UNIT_S
1712                 },
1713                 &tcp_keepalives_interval,
1714                 0, 0, INT_MAX, assign_tcp_keepalives_interval, show_tcp_keepalives_interval
1715         },
1716
1717         {
1718                 {"tcp_keepalives_count", PGC_USERSET, CLIENT_CONN_OTHER,
1719                         gettext_noop("Maximum number of TCP keepalive retransmits."),
1720                         gettext_noop("This controls the number of consecutive keepalive retransmits that can be "
1721                                                  "lost before a connection is considered dead. A value of 0 uses the "
1722                                                  "system default."),
1723                 },
1724                 &tcp_keepalives_count,
1725                 0, 0, INT_MAX, assign_tcp_keepalives_count, show_tcp_keepalives_count
1726         },
1727
1728         {
1729                 {"gin_fuzzy_search_limit", PGC_USERSET, CLIENT_CONN_OTHER,
1730                         gettext_noop("Sets the maximum allowed result for exact search by GIN."),
1731                         NULL,
1732                         0
1733                 },
1734                 &GinFuzzySearchLimit,
1735                 0, 0, INT_MAX, NULL, NULL
1736         },
1737
1738         {
1739                 {"effective_cache_size", PGC_USERSET, QUERY_TUNING_COST,
1740                         gettext_noop("Sets the planner's assumption about the size of the disk cache."),
1741                         gettext_noop("That is, the portion of the kernel's disk cache that "
1742                                                  "will be used for PostgreSQL data files. This is measured in disk "
1743                                                  "pages, which are normally 8 kB each."),
1744                         GUC_UNIT_BLOCKS,
1745                 },
1746                 &effective_cache_size,
1747                 DEFAULT_EFFECTIVE_CACHE_SIZE, 1, INT_MAX, NULL, NULL
1748         },
1749
1750         {
1751                 /* Can't be set in postgresql.conf */
1752                 {"server_version_num", PGC_INTERNAL, PRESET_OPTIONS,
1753                         gettext_noop("Shows the server version as an integer."),
1754                         NULL,
1755                         GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
1756                 },
1757                 &server_version_num,
1758                 PG_VERSION_NUM, PG_VERSION_NUM, PG_VERSION_NUM, NULL, NULL
1759         },
1760
1761         {
1762                 {"log_temp_files", PGC_USERSET, LOGGING_WHAT,
1763                         gettext_noop("Log the use of temporary files larger than this number of kilobytes."),
1764                         gettext_noop("Zero logs all files. The default is -1 (turning this feature off)."),
1765                         GUC_UNIT_KB
1766                 },
1767                 &log_temp_files,
1768                 -1, -1, INT_MAX, NULL, NULL
1769         },
1770
1771         /* End-of-list marker */
1772         {
1773                 {NULL, 0, 0, NULL, NULL}, NULL, 0, 0, 0, NULL, NULL
1774         }
1775 };
1776
1777
1778 static struct config_real ConfigureNamesReal[] =
1779 {
1780         {
1781                 {"seq_page_cost", PGC_USERSET, QUERY_TUNING_COST,
1782                         gettext_noop("Sets the planner's estimate of the cost of a "
1783                                                  "sequentially fetched disk page."),
1784                         NULL
1785                 },
1786                 &seq_page_cost,
1787                 DEFAULT_SEQ_PAGE_COST, 0, DBL_MAX, NULL, NULL
1788         },
1789         {
1790                 {"random_page_cost", PGC_USERSET, QUERY_TUNING_COST,
1791                         gettext_noop("Sets the planner's estimate of the cost of a "
1792                                                  "nonsequentially fetched disk page."),
1793                         NULL
1794                 },
1795                 &random_page_cost,
1796                 DEFAULT_RANDOM_PAGE_COST, 0, DBL_MAX, NULL, NULL
1797         },
1798         {
1799                 {"cpu_tuple_cost", PGC_USERSET, QUERY_TUNING_COST,
1800                         gettext_noop("Sets the planner's estimate of the cost of "
1801                                                  "processing each tuple (row)."),
1802                         NULL
1803                 },
1804                 &cpu_tuple_cost,
1805                 DEFAULT_CPU_TUPLE_COST, 0, DBL_MAX, NULL, NULL
1806         },
1807         {
1808                 {"cpu_index_tuple_cost", PGC_USERSET, QUERY_TUNING_COST,
1809                         gettext_noop("Sets the planner's estimate of the cost of "
1810                                                  "processing each index entry during an index scan."),
1811                         NULL
1812                 },
1813                 &cpu_index_tuple_cost,
1814                 DEFAULT_CPU_INDEX_TUPLE_COST, 0, DBL_MAX, NULL, NULL
1815         },
1816         {
1817                 {"cpu_operator_cost", PGC_USERSET, QUERY_TUNING_COST,
1818                         gettext_noop("Sets the planner's estimate of the cost of "
1819                                                  "processing each operator or function call."),
1820                         NULL
1821                 },
1822                 &cpu_operator_cost,
1823                 DEFAULT_CPU_OPERATOR_COST, 0, DBL_MAX, NULL, NULL
1824         },
1825
1826         {
1827                 {"geqo_selection_bias", PGC_USERSET, QUERY_TUNING_GEQO,
1828                         gettext_noop("GEQO: selective pressure within the population."),
1829                         NULL
1830                 },
1831                 &Geqo_selection_bias,
1832                 DEFAULT_GEQO_SELECTION_BIAS, MIN_GEQO_SELECTION_BIAS,
1833                 MAX_GEQO_SELECTION_BIAS, NULL, NULL
1834         },
1835
1836         {
1837                 {"bgwriter_lru_multiplier", PGC_SIGHUP, RESOURCES,
1838                         gettext_noop("Multiple of the average buffer usage to free per round."),
1839                         NULL
1840                 },
1841                 &bgwriter_lru_multiplier,
1842                 2.0, 0.0, 10.0, NULL, NULL
1843         },
1844
1845         {
1846                 {"seed", PGC_USERSET, UNGROUPED,
1847                         gettext_noop("Sets the seed for random-number generation."),
1848                         NULL,
1849                         GUC_NO_SHOW_ALL | GUC_NO_RESET_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
1850                 },
1851                 &phony_random_seed,
1852                 0.5, 0.0, 1.0, assign_random_seed, show_random_seed
1853         },
1854
1855         {
1856                 {"autovacuum_vacuum_scale_factor", PGC_SIGHUP, AUTOVACUUM,
1857                         gettext_noop("Number of tuple updates or deletes prior to vacuum as a fraction of reltuples."),
1858                         NULL
1859                 },
1860                 &autovacuum_vac_scale,
1861                 0.2, 0.0, 100.0, NULL, NULL
1862         },
1863         {
1864                 {"autovacuum_analyze_scale_factor", PGC_SIGHUP, AUTOVACUUM,
1865                         gettext_noop("Number of tuple inserts, updates or deletes prior to analyze as a fraction of reltuples."),
1866                         NULL
1867                 },
1868                 &autovacuum_anl_scale,
1869                 0.1, 0.0, 100.0, NULL, NULL
1870         },
1871
1872         {
1873                 {"checkpoint_completion_target", PGC_SIGHUP, WAL_CHECKPOINTS,
1874                         gettext_noop("Time spent flushing dirty buffers during checkpoint, as fraction of checkpoint interval."),
1875                         NULL
1876                 },
1877                 &CheckPointCompletionTarget,
1878                 0.5, 0.0, 1.0, NULL, NULL
1879         },
1880
1881         /* End-of-list marker */
1882         {
1883                 {NULL, 0, 0, NULL, NULL}, NULL, 0.0, 0.0, 0.0, NULL, NULL
1884         }
1885 };
1886
1887
1888 static struct config_string ConfigureNamesString[] =
1889 {
1890         {
1891                 {"archive_command", PGC_SIGHUP, WAL_SETTINGS,
1892                         gettext_noop("Sets the shell command that will be called to archive a WAL file."),
1893                         NULL
1894                 },
1895                 &XLogArchiveCommand,
1896                 "", NULL, show_archive_command
1897         },
1898
1899         {
1900                 {"backslash_quote", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
1901                         gettext_noop("Sets whether \"\\'\" is allowed in string literals."),
1902                         gettext_noop("Valid values are ON, OFF, and SAFE_ENCODING.")
1903                 },
1904                 &backslash_quote_string,
1905                 "safe_encoding", assign_backslash_quote, NULL
1906         },
1907
1908         {
1909                 {"client_encoding", PGC_USERSET, CLIENT_CONN_LOCALE,
1910                         gettext_noop("Sets the client's character set encoding."),
1911                         NULL,
1912                         GUC_IS_NAME | GUC_REPORT
1913                 },
1914                 &client_encoding_string,
1915                 "SQL_ASCII", assign_client_encoding, NULL
1916         },
1917
1918         {
1919                 {"client_min_messages", PGC_USERSET, LOGGING_WHEN,
1920                         gettext_noop("Sets the message levels that are sent to the client."),
1921                         gettext_noop("Valid values are DEBUG5, DEBUG4, DEBUG3, DEBUG2, "
1922                                                  "DEBUG1, LOG, NOTICE, WARNING, and ERROR. Each level includes all the "
1923                                                  "levels that follow it. The later the level, the fewer messages are "
1924                                                  "sent.")
1925                 },
1926                 &client_min_messages_str,
1927                 "notice", assign_client_min_messages, NULL
1928         },
1929
1930         {
1931                 {"log_min_messages", PGC_SUSET, LOGGING_WHEN,
1932                         gettext_noop("Sets the message levels that are logged."),
1933                         gettext_noop("Valid values are DEBUG5, DEBUG4, DEBUG3, DEBUG2, DEBUG1, "
1934                         "INFO, NOTICE, WARNING, ERROR, LOG, FATAL, and PANIC. Each level "
1935                                                  "includes all the levels that follow it.")
1936                 },
1937                 &log_min_messages_str,
1938                 "notice", assign_log_min_messages, NULL
1939         },
1940
1941         {
1942                 {"log_error_verbosity", PGC_SUSET, LOGGING_WHEN,
1943                         gettext_noop("Sets the verbosity of logged messages."),
1944                         gettext_noop("Valid values are \"terse\", \"default\", and \"verbose\".")
1945                 },
1946                 &log_error_verbosity_str,
1947                 "default", assign_log_error_verbosity, NULL
1948         },
1949         {
1950                 {"log_statement", PGC_SUSET, LOGGING_WHAT,
1951                         gettext_noop("Sets the type of statements logged."),
1952                         gettext_noop("Valid values are \"none\", \"ddl\", \"mod\", and \"all\".")
1953                 },
1954                 &log_statement_str,
1955                 "none", assign_log_statement, NULL
1956         },
1957
1958         {
1959                 {"log_min_error_statement", PGC_SUSET, LOGGING_WHEN,
1960                         gettext_noop("Causes all statements generating error at or above this level to be logged."),
1961                         gettext_noop("All SQL statements that cause an error of the "
1962                                                  "specified level or a higher level are logged.")
1963                 },
1964                 &log_min_error_statement_str,
1965                 "error", assign_min_error_statement, NULL
1966         },
1967
1968         {
1969                 {"log_line_prefix", PGC_SIGHUP, LOGGING_WHAT,
1970                         gettext_noop("Controls information prefixed to each log line."),
1971                         gettext_noop("If blank, no prefix is used.")
1972                 },
1973                 &Log_line_prefix,
1974                 "", NULL, NULL
1975         },
1976
1977         {
1978                 {"log_timezone", PGC_SIGHUP, LOGGING_WHAT,
1979                         gettext_noop("Sets the time zone to use in log messages."),
1980                         NULL
1981                 },
1982                 &log_timezone_string,
1983                 "UNKNOWN", assign_log_timezone, show_log_timezone
1984         },
1985
1986         {
1987                 {"DateStyle", PGC_USERSET, CLIENT_CONN_LOCALE,
1988                         gettext_noop("Sets the display format for date and time values."),
1989                         gettext_noop("Also controls interpretation of ambiguous "
1990                                                  "date inputs."),
1991                         GUC_LIST_INPUT | GUC_REPORT
1992                 },
1993                 &datestyle_string,
1994                 "ISO, MDY", assign_datestyle, NULL
1995         },
1996
1997         {
1998                 {"default_tablespace", PGC_USERSET, CLIENT_CONN_STATEMENT,
1999                         gettext_noop("Sets the default tablespace to create tables and indexes in."),
2000                         gettext_noop("An empty string selects the database's default tablespace."),
2001                         GUC_IS_NAME
2002                 },
2003                 &default_tablespace,
2004                 "", assign_default_tablespace, NULL
2005         },
2006
2007         {
2008                 {"temp_tablespaces", PGC_USERSET, CLIENT_CONN_STATEMENT,
2009                         gettext_noop("Sets the tablespace(s) to use for temporary tables and sort files."),
2010                         NULL,
2011                         GUC_LIST_INPUT | GUC_LIST_QUOTE
2012                 },
2013                 &temp_tablespaces,
2014                 "", assign_temp_tablespaces, NULL
2015         },
2016
2017         {
2018                 {"default_transaction_isolation", PGC_USERSET, CLIENT_CONN_STATEMENT,
2019                         gettext_noop("Sets the transaction isolation level of each new transaction."),
2020                         gettext_noop("Each SQL transaction has an isolation level, which "
2021                                                  "can be either \"read uncommitted\", \"read committed\", \"repeatable read\", or \"serializable\".")
2022                 },
2023                 &default_iso_level_string,
2024                 "read committed", assign_defaultxactisolevel, NULL
2025         },
2026
2027         {
2028                 {"session_replication_role", PGC_SUSET, CLIENT_CONN_STATEMENT,
2029                         gettext_noop("Sets the session's behavior for triggers and rewrite rules."),
2030                         gettext_noop("Each session can be either"
2031                                                  " \"origin\", \"replica\", or \"local\".")
2032                 },
2033                 &session_replication_role_string,
2034                 "origin", assign_session_replication_role, NULL
2035         },
2036
2037         {
2038                 {"dynamic_library_path", PGC_SUSET, CLIENT_CONN_OTHER,
2039                         gettext_noop("Sets the path for dynamically loadable modules."),
2040                         gettext_noop("If a dynamically loadable module needs to be opened and "
2041                                                  "the specified name does not have a directory component (i.e., the "
2042                                                  "name does not contain a slash), the system will search this path for "
2043                                                  "the specified file."),
2044                         GUC_SUPERUSER_ONLY
2045                 },
2046                 &Dynamic_library_path,
2047                 "$libdir", NULL, NULL
2048         },
2049
2050         {
2051                 {"krb_realm", PGC_POSTMASTER, CONN_AUTH_SECURITY,
2052                         gettext_noop("Sets realm to match Kerberos and GSSAPI users against."),
2053                         NULL,
2054                         GUC_SUPERUSER_ONLY
2055                 },
2056                 &pg_krb_realm,
2057                 NULL, NULL, NULL
2058         },
2059
2060         {
2061                 {"krb_server_keyfile", PGC_POSTMASTER, CONN_AUTH_SECURITY,
2062                         gettext_noop("Sets the location of the Kerberos server key file."),
2063                         NULL,
2064                         GUC_SUPERUSER_ONLY
2065                 },
2066                 &pg_krb_server_keyfile,
2067                 PG_KRB_SRVTAB, NULL, NULL
2068         },
2069
2070         {
2071                 {"krb_srvname", PGC_POSTMASTER, CONN_AUTH_SECURITY,
2072                         gettext_noop("Sets the name of the Kerberos service."),
2073                         NULL
2074                 },
2075                 &pg_krb_srvnam,
2076                 PG_KRB_SRVNAM, NULL, NULL
2077         },
2078
2079         {
2080                 {"krb_server_hostname", PGC_POSTMASTER, CONN_AUTH_SECURITY,
2081                         gettext_noop("Sets the hostname of the Kerberos server."),
2082                         NULL
2083                 },
2084                 &pg_krb_server_hostname,
2085                 NULL, NULL, NULL
2086         },
2087
2088         {
2089                 {"bonjour_name", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
2090                         gettext_noop("Sets the Bonjour broadcast service name."),
2091                         NULL
2092                 },
2093                 &bonjour_name,
2094                 "", NULL, NULL
2095         },
2096
2097         /* See main.c about why defaults for LC_foo are not all alike */
2098
2099         {
2100                 {"lc_collate", PGC_INTERNAL, CLIENT_CONN_LOCALE,
2101                         gettext_noop("Shows the collation order locale."),
2102                         NULL,
2103                         GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2104                 },
2105                 &locale_collate,
2106                 "C", NULL, NULL
2107         },
2108
2109         {
2110                 {"lc_ctype", PGC_INTERNAL, CLIENT_CONN_LOCALE,
2111                         gettext_noop("Shows the character classification and case conversion locale."),
2112                         NULL,
2113                         GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2114                 },
2115                 &locale_ctype,
2116                 "C", NULL, NULL
2117         },
2118
2119         {
2120                 {"lc_messages", PGC_SUSET, CLIENT_CONN_LOCALE,
2121                         gettext_noop("Sets the language in which messages are displayed."),
2122                         NULL
2123                 },
2124                 &locale_messages,
2125                 "", locale_messages_assign, NULL
2126         },
2127
2128         {
2129                 {"lc_monetary", PGC_USERSET, CLIENT_CONN_LOCALE,
2130                         gettext_noop("Sets the locale for formatting monetary amounts."),
2131                         NULL
2132                 },
2133                 &locale_monetary,
2134                 "C", locale_monetary_assign, NULL
2135         },
2136
2137         {
2138                 {"lc_numeric", PGC_USERSET, CLIENT_CONN_LOCALE,
2139                         gettext_noop("Sets the locale for formatting numbers."),
2140                         NULL
2141                 },
2142                 &locale_numeric,
2143                 "C", locale_numeric_assign, NULL
2144         },
2145
2146         {
2147                 {"lc_time", PGC_USERSET, CLIENT_CONN_LOCALE,
2148                         gettext_noop("Sets the locale for formatting date and time values."),
2149                         NULL
2150                 },
2151                 &locale_time,
2152                 "C", locale_time_assign, NULL
2153         },
2154
2155         {
2156                 {"shared_preload_libraries", PGC_POSTMASTER, RESOURCES_KERNEL,
2157                         gettext_noop("Lists shared libraries to preload into server."),
2158                         NULL,
2159                         GUC_LIST_INPUT | GUC_LIST_QUOTE | GUC_SUPERUSER_ONLY
2160                 },
2161                 &shared_preload_libraries_string,
2162                 "", NULL, NULL
2163         },
2164
2165         {
2166                 {"local_preload_libraries", PGC_BACKEND, CLIENT_CONN_OTHER,
2167                         gettext_noop("Lists shared libraries to preload into each backend."),
2168                         NULL,
2169                         GUC_LIST_INPUT | GUC_LIST_QUOTE
2170                 },
2171                 &local_preload_libraries_string,
2172                 "", NULL, NULL
2173         },
2174
2175         {
2176                 {"regex_flavor", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
2177                         gettext_noop("Sets the regular expression \"flavor\"."),
2178                         gettext_noop("This can be set to advanced, extended, or basic.")
2179                 },
2180                 &regex_flavor_string,
2181                 "advanced", assign_regex_flavor, NULL
2182         },
2183
2184         {
2185                 {"search_path", PGC_USERSET, CLIENT_CONN_STATEMENT,
2186                         gettext_noop("Sets the schema search order for names that are not schema-qualified."),
2187                         NULL,
2188                         GUC_LIST_INPUT | GUC_LIST_QUOTE
2189                 },
2190                 &namespace_search_path,
2191                 "\"$user\",public", assign_search_path, NULL
2192         },
2193
2194         {
2195                 /* Can't be set in postgresql.conf */
2196                 {"server_encoding", PGC_INTERNAL, CLIENT_CONN_LOCALE,
2197                         gettext_noop("Sets the server (database) character set encoding."),
2198                         NULL,
2199                         GUC_IS_NAME | GUC_REPORT | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2200                 },
2201                 &server_encoding_string,
2202                 "SQL_ASCII", NULL, NULL
2203         },
2204
2205         {
2206                 /* Can't be set in postgresql.conf */
2207                 {"server_version", PGC_INTERNAL, PRESET_OPTIONS,
2208                         gettext_noop("Shows the server version."),
2209                         NULL,
2210                         GUC_REPORT | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2211                 },
2212                 &server_version_string,
2213                 PG_VERSION, NULL, NULL
2214         },
2215
2216         {
2217                 /* Not for general use --- used by SET ROLE */
2218                 {"role", PGC_USERSET, UNGROUPED,
2219                         gettext_noop("Sets the current role."),
2220                         NULL,
2221                         GUC_IS_NAME | GUC_NO_SHOW_ALL | GUC_NO_RESET_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2222                 },
2223                 &role_string,
2224                 "none", assign_role, show_role
2225         },
2226
2227         {
2228                 /* Not for general use --- used by SET SESSION AUTHORIZATION */
2229                 {"session_authorization", PGC_USERSET, UNGROUPED,
2230                         gettext_noop("Sets the session user name."),
2231                         NULL,
2232                         GUC_IS_NAME | GUC_REPORT | GUC_NO_SHOW_ALL | GUC_NO_RESET_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2233                 },
2234                 &session_authorization_string,
2235                 NULL, assign_session_authorization, show_session_authorization
2236         },
2237
2238         {
2239                 {"log_destination", PGC_SIGHUP, LOGGING_WHERE,
2240                         gettext_noop("Sets the destination for server log output."),
2241                         gettext_noop("Valid values are combinations of \"stderr\", "
2242                                                  "\"syslog\", \"csvlog\", and \"eventlog\", "
2243                                                  "depending on the platform."),
2244                         GUC_LIST_INPUT
2245                 },
2246                 &log_destination_string,
2247                 "stderr", assign_log_destination, NULL
2248         },
2249         {
2250                 {"log_directory", PGC_SIGHUP, LOGGING_WHERE,
2251                         gettext_noop("Sets the destination directory for log files."),
2252                         gettext_noop("Can be specified as relative to the data directory "
2253                                                  "or as absolute path."),
2254                         GUC_SUPERUSER_ONLY
2255                 },
2256                 &Log_directory,
2257                 "pg_log", assign_canonical_path, NULL
2258         },
2259         {
2260                 {"log_filename", PGC_SIGHUP, LOGGING_WHERE,
2261                         gettext_noop("Sets the file name pattern for log files."),
2262                         NULL,
2263                         GUC_SUPERUSER_ONLY
2264                 },
2265                 &Log_filename,
2266                 "postgresql-%Y-%m-%d_%H%M%S.log", NULL, NULL
2267         },
2268
2269 #ifdef HAVE_SYSLOG
2270         {
2271                 {"syslog_facility", PGC_SIGHUP, LOGGING_WHERE,
2272                         gettext_noop("Sets the syslog \"facility\" to be used when syslog enabled."),
2273                         gettext_noop("Valid values are LOCAL0, LOCAL1, LOCAL2, LOCAL3, "
2274                                                  "LOCAL4, LOCAL5, LOCAL6, LOCAL7.")
2275                 },
2276                 &syslog_facility_str,
2277                 "LOCAL0", assign_syslog_facility, NULL
2278         },
2279         {
2280                 {"syslog_ident", PGC_SIGHUP, LOGGING_WHERE,
2281                         gettext_noop("Sets the program name used to identify PostgreSQL "
2282                                                  "messages in syslog."),
2283                         NULL
2284                 },
2285                 &syslog_ident_str,
2286                 "postgres", assign_syslog_ident, NULL
2287         },
2288 #endif
2289
2290         {
2291                 {"TimeZone", PGC_USERSET, CLIENT_CONN_LOCALE,
2292                         gettext_noop("Sets the time zone for displaying and interpreting time stamps."),
2293                         NULL,
2294                         GUC_REPORT
2295                 },
2296                 &timezone_string,
2297                 "UNKNOWN", assign_timezone, show_timezone
2298         },
2299         {
2300                 {"timezone_abbreviations", PGC_USERSET, CLIENT_CONN_LOCALE,
2301                         gettext_noop("Selects a file of time zone abbreviations."),
2302                         NULL,
2303                 },
2304                 &timezone_abbreviations_string,
2305                 "UNKNOWN", assign_timezone_abbreviations, NULL
2306         },
2307
2308         {
2309                 {"transaction_isolation", PGC_USERSET, CLIENT_CONN_STATEMENT,
2310                         gettext_noop("Sets the current transaction's isolation level."),
2311                         NULL,
2312                         GUC_NO_RESET_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2313                 },
2314                 &XactIsoLevel_string,
2315                 NULL, assign_XactIsoLevel, show_XactIsoLevel
2316         },
2317
2318         {
2319                 {"unix_socket_group", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
2320                         gettext_noop("Sets the owning group of the Unix-domain socket."),
2321                         gettext_noop("The owning user of the socket is always the user "
2322                                                  "that starts the server.")
2323                 },
2324                 &Unix_socket_group,
2325                 "", NULL, NULL
2326         },
2327
2328         {
2329                 {"unix_socket_directory", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
2330                         gettext_noop("Sets the directory where the Unix-domain socket will be created."),
2331                         NULL,
2332                         GUC_SUPERUSER_ONLY
2333                 },
2334                 &UnixSocketDir,
2335                 "", assign_canonical_path, NULL
2336         },
2337
2338         {
2339                 {"listen_addresses", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
2340                         gettext_noop("Sets the host name or IP address(es) to listen to."),
2341                         NULL,
2342                         GUC_LIST_INPUT
2343                 },
2344                 &ListenAddresses,
2345                 "localhost", NULL, NULL
2346         },
2347
2348         {
2349                 {"wal_sync_method", PGC_SIGHUP, WAL_SETTINGS,
2350                         gettext_noop("Selects the method used for forcing WAL updates to disk."),
2351                         NULL
2352                 },
2353                 &XLOG_sync_method,
2354                 XLOG_sync_method_default, assign_xlog_sync_method, NULL
2355         },
2356
2357         {
2358                 {"custom_variable_classes", PGC_SIGHUP, CUSTOM_OPTIONS,
2359                         gettext_noop("Sets the list of known custom variable classes."),
2360                         NULL,
2361                         GUC_LIST_INPUT | GUC_LIST_QUOTE
2362                 },
2363                 &custom_variable_classes,
2364                 NULL, assign_custom_variable_classes, NULL
2365         },
2366
2367         {
2368                 {"data_directory", PGC_POSTMASTER, FILE_LOCATIONS,
2369                         gettext_noop("Sets the server's data directory."),
2370                         NULL,
2371                         GUC_SUPERUSER_ONLY
2372                 },
2373                 &data_directory,
2374                 NULL, NULL, NULL
2375         },
2376
2377         {
2378                 {"config_file", PGC_POSTMASTER, FILE_LOCATIONS,
2379                         gettext_noop("Sets the server's main configuration file."),
2380                         NULL,
2381                         GUC_DISALLOW_IN_FILE | GUC_SUPERUSER_ONLY
2382                 },
2383                 &ConfigFileName,
2384                 NULL, NULL, NULL
2385         },
2386
2387         {
2388                 {"hba_file", PGC_POSTMASTER, FILE_LOCATIONS,
2389                         gettext_noop("Sets the server's \"hba\" configuration file."),
2390                         NULL,
2391                         GUC_SUPERUSER_ONLY
2392                 },
2393                 &HbaFileName,
2394                 NULL, NULL, NULL
2395         },
2396
2397         {
2398                 {"ident_file", PGC_POSTMASTER, FILE_LOCATIONS,
2399                         gettext_noop("Sets the server's \"ident\" configuration file."),
2400                         NULL,
2401                         GUC_SUPERUSER_ONLY
2402                 },
2403                 &IdentFileName,
2404                 NULL, NULL, NULL
2405         },
2406
2407         {
2408                 {"external_pid_file", PGC_POSTMASTER, FILE_LOCATIONS,
2409                         gettext_noop("Writes the postmaster PID to the specified file."),
2410                         NULL,
2411                         GUC_SUPERUSER_ONLY
2412                 },
2413                 &external_pid_file,
2414                 NULL, assign_canonical_path, NULL
2415         },
2416
2417         {
2418                 {"xmlbinary", PGC_USERSET, CLIENT_CONN_STATEMENT,
2419                         gettext_noop("Sets how binary values are to be encoded in XML."),
2420                         gettext_noop("Valid values are BASE64 and HEX.")
2421                 },
2422                 &xmlbinary_string,
2423                 "base64", assign_xmlbinary, NULL
2424         },
2425
2426         {
2427                 {"xmloption", PGC_USERSET, CLIENT_CONN_STATEMENT,
2428                         gettext_noop("Sets whether XML data in implicit parsing and serialization "
2429                                                  "operations is to be considered as documents or content fragments."),
2430                         gettext_noop("Valid values are DOCUMENT and CONTENT.")
2431                 },
2432                 &xmloption_string,
2433                 "content", assign_xmloption, NULL
2434         },
2435
2436         {
2437                 {"default_text_search_config", PGC_USERSET, CLIENT_CONN_LOCALE,
2438                         gettext_noop("Sets default text search configuration."),
2439                         NULL
2440                 },
2441                 &TSCurrentConfig,
2442                 "pg_catalog.simple", assignTSCurrentConfig, NULL
2443         },
2444
2445 #ifdef USE_SSL
2446         {
2447                 {"ssl_ciphers", PGC_POSTMASTER, CONN_AUTH_SECURITY,
2448                         gettext_noop("Sets the list of allowed SSL ciphers."),
2449                         NULL,
2450                         GUC_SUPERUSER_ONLY
2451                 },
2452                 &SSLCipherSuites,
2453                 "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH", NULL, NULL
2454         },
2455 #endif   /* USE_SSL */
2456
2457         /* End-of-list marker */
2458         {
2459                 {NULL, 0, 0, NULL, NULL}, NULL, NULL, NULL, NULL
2460         }
2461 };
2462
2463
2464 /******** end of options list ********/
2465
2466
2467 /*
2468  * To allow continued support of obsolete names for GUC variables, we apply
2469  * the following mappings to any unrecognized name.  Note that an old name
2470  * should be mapped to a new one only if the new variable has very similar
2471  * semantics to the old.
2472  */
2473 static const char *const map_old_guc_names[] = {
2474         "sort_mem", "work_mem",
2475         "vacuum_mem", "maintenance_work_mem",
2476         NULL
2477 };
2478
2479
2480 /*
2481  * Actual lookup of variables is done through this single, sorted array.
2482  */
2483 static struct config_generic **guc_variables;
2484
2485 /* Current number of variables contained in the vector */
2486 static int      num_guc_variables;
2487
2488 /* Vector capacity */
2489 static int      size_guc_variables;
2490
2491
2492 static bool guc_dirty;                  /* TRUE if need to do commit/abort work */
2493
2494 static bool reporting_enabled;  /* TRUE to enable GUC_REPORT */
2495
2496 static int      GUCNestLevel = 0;       /* 1 when in main transaction */
2497
2498
2499 static int      guc_var_compare(const void *a, const void *b);
2500 static int      guc_name_compare(const char *namea, const char *nameb);
2501 static void push_old_value(struct config_generic * gconf, GucAction action);
2502 static void ReportGUCOption(struct config_generic * record);
2503 static void ShowGUCConfigOption(const char *name, DestReceiver *dest);
2504 static void ShowAllGUCConfig(DestReceiver *dest);
2505 static char *_ShowOption(struct config_generic * record, bool use_units);
2506 static bool is_newvalue_equal(struct config_generic * record, const char *newvalue);
2507
2508
2509 /*
2510  * Some infrastructure for checking malloc/strdup/realloc calls
2511  */
2512 static void *
2513 guc_malloc(int elevel, size_t size)
2514 {
2515         void       *data;
2516
2517         data = malloc(size);
2518         if (data == NULL)
2519                 ereport(elevel,
2520                                 (errcode(ERRCODE_OUT_OF_MEMORY),
2521                                  errmsg("out of memory")));
2522         return data;
2523 }
2524
2525 static void *
2526 guc_realloc(int elevel, void *old, size_t size)
2527 {
2528         void       *data;
2529
2530         data = realloc(old, size);
2531         if (data == NULL)
2532                 ereport(elevel,
2533                                 (errcode(ERRCODE_OUT_OF_MEMORY),
2534                                  errmsg("out of memory")));
2535         return data;
2536 }
2537
2538 static char *
2539 guc_strdup(int elevel, const char *src)
2540 {
2541         char       *data;
2542
2543         data = strdup(src);
2544         if (data == NULL)
2545                 ereport(elevel,
2546                                 (errcode(ERRCODE_OUT_OF_MEMORY),
2547                                  errmsg("out of memory")));
2548         return data;
2549 }
2550
2551
2552 /*
2553  * Support for assigning to a field of a string GUC item.  Free the prior
2554  * value if it's not referenced anywhere else in the item (including stacked
2555  * states).
2556  */
2557 static void
2558 set_string_field(struct config_string * conf, char **field, char *newval)
2559 {
2560         char       *oldval = *field;
2561         GucStack   *stack;
2562
2563         /* Do the assignment */
2564         *field = newval;
2565
2566         /* Exit if any duplicate references, or if old value was NULL anyway */
2567         if (oldval == NULL ||
2568                 oldval == *(conf->variable) ||
2569                 oldval == conf->reset_val ||
2570                 oldval == conf->boot_val)
2571                 return;
2572         for (stack = conf->gen.stack; stack; stack = stack->prev)
2573         {
2574                 if (oldval == stack->prior.stringval ||
2575                         oldval == stack->masked.stringval)
2576                         return;
2577         }
2578
2579         /* Not used anymore, so free it */
2580         free(oldval);
2581 }
2582
2583 /*
2584  * Detect whether strval is referenced anywhere in a GUC string item
2585  */
2586 static bool
2587 string_field_used(struct config_string * conf, char *strval)
2588 {
2589         GucStack   *stack;
2590
2591         if (strval == *(conf->variable) ||
2592                 strval == conf->reset_val ||
2593                 strval == conf->boot_val)
2594                 return true;
2595         for (stack = conf->gen.stack; stack; stack = stack->prev)
2596         {
2597                 if (strval == stack->prior.stringval ||
2598                         strval == stack->masked.stringval)
2599                         return true;
2600         }
2601         return false;
2602 }
2603
2604 /*
2605  * Support for copying a variable's active value into a stack entry
2606  */
2607 static void
2608 set_stack_value(struct config_generic * gconf, union config_var_value * val)
2609 {
2610         switch (gconf->vartype)
2611         {
2612                 case PGC_BOOL:
2613                         val->boolval =
2614                                 *((struct config_bool *) gconf)->variable;
2615                         break;
2616                 case PGC_INT:
2617                         val->intval =
2618                                 *((struct config_int *) gconf)->variable;
2619                         break;
2620                 case PGC_REAL:
2621                         val->realval =
2622                                 *((struct config_real *) gconf)->variable;
2623                         break;
2624                 case PGC_STRING:
2625                         /* we assume stringval is NULL if not valid */
2626                         set_string_field((struct config_string *) gconf,
2627                                                          &(val->stringval),
2628                                                          *((struct config_string *) gconf)->variable);
2629                         break;
2630         }
2631 }
2632
2633 /*
2634  * Support for discarding a no-longer-needed value in a stack entry
2635  */
2636 static void
2637 discard_stack_value(struct config_generic * gconf, union config_var_value * val)
2638 {
2639         switch (gconf->vartype)
2640         {
2641                 case PGC_BOOL:
2642                 case PGC_INT:
2643                 case PGC_REAL:
2644                         /* no need to do anything */
2645                         break;
2646                 case PGC_STRING:
2647                         set_string_field((struct config_string *) gconf,
2648                                                          &(val->stringval),
2649                                                          NULL);
2650                         break;
2651         }
2652 }
2653
2654
2655 /*
2656  * Fetch the sorted array pointer (exported for help_config.c's use ONLY)
2657  */
2658 struct config_generic **
2659 get_guc_variables(void)
2660 {
2661         return guc_variables;
2662 }
2663
2664
2665 /*
2666  * Build the sorted array.      This is split out so that it could be
2667  * re-executed after startup (eg, we could allow loadable modules to
2668  * add vars, and then we'd need to re-sort).
2669  */
2670 void
2671 build_guc_variables(void)
2672 {
2673         int                     size_vars;
2674         int                     num_vars = 0;
2675         struct config_generic **guc_vars;
2676         int                     i;
2677
2678         for (i = 0; ConfigureNamesBool[i].gen.name; i++)
2679         {
2680                 struct config_bool *conf = &ConfigureNamesBool[i];
2681
2682                 /* Rather than requiring vartype to be filled in by hand, do this: */
2683                 conf->gen.vartype = PGC_BOOL;
2684                 num_vars++;
2685         }
2686
2687         for (i = 0; ConfigureNamesInt[i].gen.name; i++)
2688         {
2689                 struct config_int *conf = &ConfigureNamesInt[i];
2690
2691                 conf->gen.vartype = PGC_INT;
2692                 num_vars++;
2693         }
2694
2695         for (i = 0; ConfigureNamesReal[i].gen.name; i++)
2696         {
2697                 struct config_real *conf = &ConfigureNamesReal[i];
2698
2699                 conf->gen.vartype = PGC_REAL;
2700                 num_vars++;
2701         }
2702
2703         for (i = 0; ConfigureNamesString[i].gen.name; i++)
2704         {
2705                 struct config_string *conf = &ConfigureNamesString[i];
2706
2707                 conf->gen.vartype = PGC_STRING;
2708                 num_vars++;
2709         }
2710
2711         /*
2712          * Create table with 20% slack
2713          */
2714         size_vars = num_vars + num_vars / 4;
2715
2716         guc_vars = (struct config_generic **)
2717                 guc_malloc(FATAL, size_vars * sizeof(struct config_generic *));
2718
2719         num_vars = 0;
2720
2721         for (i = 0; ConfigureNamesBool[i].gen.name; i++)
2722                 guc_vars[num_vars++] = &ConfigureNamesBool[i].gen;
2723
2724         for (i = 0; ConfigureNamesInt[i].gen.name; i++)
2725                 guc_vars[num_vars++] = &ConfigureNamesInt[i].gen;
2726
2727         for (i = 0; ConfigureNamesReal[i].gen.name; i++)
2728                 guc_vars[num_vars++] = &ConfigureNamesReal[i].gen;
2729
2730         for (i = 0; ConfigureNamesString[i].gen.name; i++)
2731                 guc_vars[num_vars++] = &ConfigureNamesString[i].gen;
2732
2733         if (guc_variables)
2734                 free(guc_variables);
2735         guc_variables = guc_vars;
2736         num_guc_variables = num_vars;
2737         size_guc_variables = size_vars;
2738         qsort((void *) guc_variables, num_guc_variables,
2739                   sizeof(struct config_generic *), guc_var_compare);
2740 }
2741
2742 /*
2743  * Add a new GUC variable to the list of known variables. The
2744  * list is expanded if needed.
2745  */
2746 static bool
2747 add_guc_variable(struct config_generic * var, int elevel)
2748 {
2749         if (num_guc_variables + 1 >= size_guc_variables)
2750         {
2751                 /*
2752                  * Increase the vector by 25%
2753                  */
2754                 int                     size_vars = size_guc_variables + size_guc_variables / 4;
2755                 struct config_generic **guc_vars;
2756
2757                 if (size_vars == 0)
2758                 {
2759                         size_vars = 100;
2760                         guc_vars = (struct config_generic **)
2761                                 guc_malloc(elevel, size_vars * sizeof(struct config_generic *));
2762                 }
2763                 else
2764                 {
2765                         guc_vars = (struct config_generic **)
2766                                 guc_realloc(elevel, guc_variables, size_vars * sizeof(struct config_generic *));
2767                 }
2768
2769                 if (guc_vars == NULL)
2770                         return false;           /* out of memory */
2771
2772                 guc_variables = guc_vars;
2773                 size_guc_variables = size_vars;
2774         }
2775         guc_variables[num_guc_variables++] = var;
2776         qsort((void *) guc_variables, num_guc_variables,
2777                   sizeof(struct config_generic *), guc_var_compare);
2778         return true;
2779 }
2780
2781 /*
2782  * Create and add a placeholder variable. It's presumed to belong
2783  * to a valid custom variable class at this point.
2784  */
2785 static struct config_generic *
2786 add_placeholder_variable(const char *name, int elevel)
2787 {
2788         size_t          sz = sizeof(struct config_string) + sizeof(char *);
2789         struct config_string *var;
2790         struct config_generic *gen;
2791
2792         var = (struct config_string *) guc_malloc(elevel, sz);
2793         if (var == NULL)
2794                 return NULL;
2795         memset(var, 0, sz);
2796         gen = &var->gen;
2797
2798         gen->name = guc_strdup(elevel, name);
2799         if (gen->name == NULL)
2800         {
2801                 free(var);
2802                 return NULL;
2803         }
2804
2805         gen->context = PGC_USERSET;
2806         gen->group = CUSTOM_OPTIONS;
2807         gen->short_desc = "GUC placeholder variable";
2808         gen->flags = GUC_NO_SHOW_ALL | GUC_NOT_IN_SAMPLE | GUC_CUSTOM_PLACEHOLDER;
2809         gen->vartype = PGC_STRING;
2810
2811         /*
2812          * The char* is allocated at the end of the struct since we have no
2813          * 'static' place to point to.  Note that the current value, as well as
2814          * the boot and reset values, start out NULL.
2815          */
2816         var->variable = (char **) (var + 1);
2817
2818         if (!add_guc_variable((struct config_generic *) var, elevel))
2819         {
2820                 free((void *) gen->name);
2821                 free(var);
2822                 return NULL;
2823         }
2824
2825         return gen;
2826 }
2827
2828 /*
2829  * Detect whether the portion of "name" before dotPos matches any custom
2830  * variable class name listed in custom_var_classes.  The latter must be
2831  * formatted the way that assign_custom_variable_classes does it, ie,
2832  * no whitespace.  NULL is valid for custom_var_classes.
2833  */
2834 static bool
2835 is_custom_class(const char *name, int dotPos, const char *custom_var_classes)
2836 {
2837         bool            result = false;
2838         const char *ccs = custom_var_classes;
2839
2840         if (ccs != NULL)
2841         {
2842                 const char *start = ccs;
2843
2844                 for (;; ++ccs)
2845                 {
2846                         char            c = *ccs;
2847
2848                         if (c == '\0' || c == ',')
2849                         {
2850                                 if (dotPos == ccs - start && strncmp(start, name, dotPos) == 0)
2851                                 {
2852                                         result = true;
2853                                         break;
2854                                 }
2855                                 if (c == '\0')
2856                                         break;
2857                                 start = ccs + 1;
2858                         }
2859                 }
2860         }
2861         return result;
2862 }
2863
2864 /*
2865  * Look up option NAME.  If it exists, return a pointer to its record,
2866  * else return NULL.  If create_placeholders is TRUE, we'll create a
2867  * placeholder record for a valid-looking custom variable name.
2868  */
2869 static struct config_generic *
2870 find_option(const char *name, bool create_placeholders, int elevel)
2871 {
2872         const char **key = &name;
2873         struct config_generic **res;
2874         int                     i;
2875
2876         Assert(name);
2877
2878         /*
2879          * By equating const char ** with struct config_generic *, we are assuming
2880          * the name field is first in config_generic.
2881          */
2882         res = (struct config_generic **) bsearch((void *) &key,
2883                                                                                          (void *) guc_variables,
2884                                                                                          num_guc_variables,
2885                                                                                          sizeof(struct config_generic *),
2886                                                                                          guc_var_compare);
2887         if (res)
2888                 return *res;
2889
2890         /*
2891          * See if the name is an obsolete name for a variable.  We assume that the
2892          * set of supported old names is short enough that a brute-force search is
2893          * the best way.
2894          */
2895         for (i = 0; map_old_guc_names[i] != NULL; i += 2)
2896         {
2897                 if (guc_name_compare(name, map_old_guc_names[i]) == 0)
2898                         return find_option(map_old_guc_names[i + 1], false, elevel);
2899         }
2900
2901         if (create_placeholders)
2902         {
2903                 /*
2904                  * Check if the name is qualified, and if so, check if the qualifier
2905                  * matches any custom variable class.  If so, add a placeholder.
2906                  */
2907                 const char *dot = strchr(name, GUC_QUALIFIER_SEPARATOR);
2908
2909                 if (dot != NULL &&
2910                         is_custom_class(name, dot - name, custom_variable_classes))
2911                         return add_placeholder_variable(name, elevel);
2912         }
2913
2914         /* Unknown name */
2915         return NULL;
2916 }
2917
2918
2919 /*
2920  * comparator for qsorting and bsearching guc_variables array
2921  */
2922 static int
2923 guc_var_compare(const void *a, const void *b)
2924 {
2925         struct config_generic *confa = *(struct config_generic **) a;
2926         struct config_generic *confb = *(struct config_generic **) b;
2927
2928         return guc_name_compare(confa->name, confb->name);
2929 }
2930
2931 /*
2932  * the bare comparison function for GUC names
2933  */
2934 static int
2935 guc_name_compare(const char *namea, const char *nameb)
2936 {
2937         /*
2938          * The temptation to use strcasecmp() here must be resisted, because the
2939          * array ordering has to remain stable across setlocale() calls. So, build
2940          * our own with a simple ASCII-only downcasing.
2941          */
2942         while (*namea && *nameb)
2943         {
2944                 char            cha = *namea++;
2945                 char            chb = *nameb++;
2946
2947                 if (cha >= 'A' && cha <= 'Z')
2948                         cha += 'a' - 'A';
2949                 if (chb >= 'A' && chb <= 'Z')
2950                         chb += 'a' - 'A';
2951                 if (cha != chb)
2952                         return cha - chb;
2953         }
2954         if (*namea)
2955                 return 1;                               /* a is longer */
2956         if (*nameb)
2957                 return -1;                              /* b is longer */
2958         return 0;
2959 }
2960
2961
2962 /*
2963  * Initialize GUC options during program startup.
2964  *
2965  * Note that we cannot read the config file yet, since we have not yet
2966  * processed command-line switches.
2967  */
2968 void
2969 InitializeGUCOptions(void)
2970 {
2971         int                     i;
2972         char       *env;
2973         long            stack_rlimit;
2974
2975         /*
2976          * Before log_line_prefix could possibly receive a nonempty setting, make
2977          * sure that timezone processing is minimally alive (see elog.c).
2978          */
2979         pg_timezone_pre_initialize();
2980
2981         /*
2982          * Build sorted array of all GUC variables.
2983          */
2984         build_guc_variables();
2985
2986         /*
2987          * Load all variables with their compiled-in defaults, and initialize
2988          * status fields as needed.
2989          */
2990         for (i = 0; i < num_guc_variables; i++)
2991         {
2992                 struct config_generic *gconf = guc_variables[i];
2993
2994                 gconf->status = 0;
2995                 gconf->reset_source = PGC_S_DEFAULT;
2996                 gconf->source = PGC_S_DEFAULT;
2997                 gconf->stack = NULL;
2998
2999                 switch (gconf->vartype)
3000                 {
3001                         case PGC_BOOL:
3002                                 {
3003                                         struct config_bool *conf = (struct config_bool *) gconf;
3004
3005                                         if (conf->assign_hook)
3006                                                 if (!(*conf->assign_hook) (conf->boot_val, true,
3007                                                                                                    PGC_S_DEFAULT))
3008                                                         elog(FATAL, "failed to initialize %s to %d",
3009                                                                  conf->gen.name, (int) conf->boot_val);
3010                                         *conf->variable = conf->reset_val = conf->boot_val;
3011                                         break;
3012                                 }
3013                         case PGC_INT:
3014                                 {
3015                                         struct config_int *conf = (struct config_int *) gconf;
3016
3017                                         Assert(conf->boot_val >= conf->min);
3018                                         Assert(conf->boot_val <= conf->max);
3019                                         if (conf->assign_hook)
3020                                                 if (!(*conf->assign_hook) (conf->boot_val, true,
3021                                                                                                    PGC_S_DEFAULT))
3022                                                         elog(FATAL, "failed to initialize %s to %d",
3023                                                                  conf->gen.name, conf->boot_val);
3024                                         *conf->variable = conf->reset_val = conf->boot_val;
3025                                         break;
3026                                 }
3027                         case PGC_REAL:
3028                                 {
3029                                         struct config_real *conf = (struct config_real *) gconf;
3030
3031                                         Assert(conf->boot_val >= conf->min);
3032                                         Assert(conf->boot_val <= conf->max);
3033                                         if (conf->assign_hook)
3034                                                 if (!(*conf->assign_hook) (conf->boot_val, true,
3035                                                                                                    PGC_S_DEFAULT))
3036                                                         elog(FATAL, "failed to initialize %s to %g",
3037                                                                  conf->gen.name, conf->boot_val);
3038                                         *conf->variable = conf->reset_val = conf->boot_val;
3039                                         break;
3040                                 }
3041                         case PGC_STRING:
3042                                 {
3043                                         struct config_string *conf = (struct config_string *) gconf;
3044                                         char       *str;
3045
3046                                         *conf->variable = NULL;
3047                                         conf->reset_val = NULL;
3048
3049                                         if (conf->boot_val == NULL)
3050                                         {
3051                                                 /* leave the value NULL, do not call assign hook */
3052                                                 break;
3053                                         }
3054
3055                                         str = guc_strdup(FATAL, conf->boot_val);
3056                                         conf->reset_val = str;
3057
3058                                         if (conf->assign_hook)
3059                                         {
3060                                                 const char *newstr;
3061
3062                                                 newstr = (*conf->assign_hook) (str, true,
3063                                                                                                            PGC_S_DEFAULT);
3064                                                 if (newstr == NULL)
3065                                                 {
3066                                                         elog(FATAL, "failed to initialize %s to \"%s\"",
3067                                                                  conf->gen.name, str);
3068                                                 }
3069                                                 else if (newstr != str)
3070                                                 {
3071                                                         free(str);
3072
3073                                                         /*
3074                                                          * See notes in set_config_option about casting
3075                                                          */
3076                                                         str = (char *) newstr;
3077                                                         conf->reset_val = str;
3078                                                 }
3079                                         }
3080                                         *conf->variable = str;
3081                                         break;
3082                                 }
3083                 }
3084         }
3085
3086         guc_dirty = false;
3087
3088         reporting_enabled = false;
3089
3090         /*
3091          * Prevent any attempt to override the transaction modes from
3092          * non-interactive sources.
3093          */
3094         SetConfigOption("transaction_isolation", "default",
3095                                         PGC_POSTMASTER, PGC_S_OVERRIDE);
3096         SetConfigOption("transaction_read_only", "no",
3097                                         PGC_POSTMASTER, PGC_S_OVERRIDE);
3098
3099         /*
3100          * For historical reasons, some GUC parameters can receive defaults from
3101          * environment variables.  Process those settings.      NB: if you add or
3102          * remove anything here, see also ProcessConfigFile().
3103          */
3104
3105         env = getenv("PGPORT");
3106         if (env != NULL)
3107                 SetConfigOption("port", env, PGC_POSTMASTER, PGC_S_ENV_VAR);
3108
3109         env = getenv("PGDATESTYLE");
3110         if (env != NULL)
3111                 SetConfigOption("datestyle", env, PGC_POSTMASTER, PGC_S_ENV_VAR);
3112
3113         env = getenv("PGCLIENTENCODING");
3114         if (env != NULL)
3115                 SetConfigOption("client_encoding", env, PGC_POSTMASTER, PGC_S_ENV_VAR);
3116
3117         /*
3118          * rlimit isn't exactly an "environment variable", but it behaves about
3119          * the same.  If we can identify the platform stack depth rlimit, increase
3120          * default stack depth setting up to whatever is safe (but at most 2MB).
3121          */
3122         stack_rlimit = get_stack_depth_rlimit();
3123         if (stack_rlimit > 0)
3124         {
3125                 int                     new_limit = (stack_rlimit - STACK_DEPTH_SLOP) / 1024L;
3126
3127                 if (new_limit > 100)
3128                 {
3129                         char            limbuf[16];
3130
3131                         new_limit = Min(new_limit, 2048);
3132                         sprintf(limbuf, "%d", new_limit);
3133                         SetConfigOption("max_stack_depth", limbuf,
3134                                                         PGC_POSTMASTER, PGC_S_ENV_VAR);
3135                 }
3136         }
3137 }
3138
3139
3140 /*
3141  * Select the configuration files and data directory to be used, and
3142  * do the initial read of postgresql.conf.
3143  *
3144  * This is called after processing command-line switches.
3145  *              userDoption is the -D switch value if any (NULL if unspecified).
3146  *              progname is just for use in error messages.
3147  *
3148  * Returns true on success; on failure, prints a suitable error message
3149  * to stderr and returns false.
3150  */
3151 bool
3152 SelectConfigFiles(const char *userDoption, const char *progname)
3153 {
3154         char       *configdir;
3155         char       *fname;
3156         struct stat stat_buf;
3157
3158         /* configdir is -D option, or $PGDATA if no -D */
3159         if (userDoption)
3160                 configdir = make_absolute_path(userDoption);
3161         else
3162                 configdir = make_absolute_path(getenv("PGDATA"));
3163
3164         /*
3165          * Find the configuration file: if config_file was specified on the
3166          * command line, use it, else use configdir/postgresql.conf.  In any case
3167          * ensure the result is an absolute path, so that it will be interpreted
3168          * the same way by future backends.
3169          */
3170         if (ConfigFileName)
3171                 fname = make_absolute_path(ConfigFileName);
3172         else if (configdir)
3173         {
3174                 fname = guc_malloc(FATAL,
3175                                                    strlen(configdir) + strlen(CONFIG_FILENAME) + 2);
3176                 sprintf(fname, "%s/%s", configdir, CONFIG_FILENAME);
3177         }
3178         else
3179         {
3180                 write_stderr("%s does not know where to find the server configuration file.\n"
3181                                          "You must specify the --config-file or -D invocation "
3182                                          "option or set the PGDATA environment variable.\n",
3183                                          progname);
3184                 return false;
3185         }
3186
3187         /*
3188          * Set the ConfigFileName GUC variable to its final value, ensuring that
3189          * it can't be overridden later.
3190          */
3191         SetConfigOption("config_file", fname, PGC_POSTMASTER, PGC_S_OVERRIDE);
3192         free(fname);
3193
3194         /*
3195          * Now read the config file for the first time.
3196          */
3197         if (stat(ConfigFileName, &stat_buf) != 0)
3198         {
3199                 write_stderr("%s cannot access the server configuration file \"%s\": %s\n",
3200                                          progname, ConfigFileName, strerror(errno));
3201                 return false;
3202         }
3203
3204         ProcessConfigFile(PGC_POSTMASTER);
3205
3206         /*
3207          * If the data_directory GUC variable has been set, use that as DataDir;
3208          * otherwise use configdir if set; else punt.
3209          *
3210          * Note: SetDataDir will copy and absolute-ize its argument, so we don't
3211          * have to.
3212          */
3213         if (data_directory)
3214                 SetDataDir(data_directory);
3215         else if (configdir)
3216                 SetDataDir(configdir);
3217         else
3218         {
3219                 write_stderr("%s does not know where to find the database system data.\n"
3220                                          "This can be specified as \"data_directory\" in \"%s\", "
3221                                          "or by the -D invocation option, or by the "
3222                                          "PGDATA environment variable.\n",
3223                                          progname, ConfigFileName);
3224                 return false;
3225         }
3226
3227         /*
3228          * Reflect the final DataDir value back into the data_directory GUC var.
3229          * (If you are wondering why we don't just make them a single variable,
3230          * it's because the EXEC_BACKEND case needs DataDir to be transmitted to
3231          * child backends specially.  XXX is that still true?  Given that we now
3232          * chdir to DataDir, EXEC_BACKEND can read the config file without knowing
3233          * DataDir in advance.)
3234          */
3235         SetConfigOption("data_directory", DataDir, PGC_POSTMASTER, PGC_S_OVERRIDE);
3236
3237         /*
3238          * Figure out where pg_hba.conf is, and make sure the path is absolute.
3239          */
3240         if (HbaFileName)
3241                 fname = make_absolute_path(HbaFileName);
3242         else if (configdir)
3243         {
3244                 fname = guc_malloc(FATAL,
3245                                                    strlen(configdir) + strlen(HBA_FILENAME) + 2);
3246                 sprintf(fname, "%s/%s", configdir, HBA_FILENAME);
3247         }
3248         else
3249         {
3250                 write_stderr("%s does not know where to find the \"hba\" configuration file.\n"
3251                                          "This can be specified as \"hba_file\" in \"%s\", "
3252                                          "or by the -D invocation option, or by the "
3253                                          "PGDATA environment variable.\n",
3254                                          progname, ConfigFileName);
3255                 return false;
3256         }
3257         SetConfigOption("hba_file", fname, PGC_POSTMASTER, PGC_S_OVERRIDE);
3258         free(fname);
3259
3260         /*
3261          * Likewise for pg_ident.conf.
3262          */
3263         if (IdentFileName)
3264                 fname = make_absolute_path(IdentFileName);
3265         else if (configdir)
3266         {
3267                 fname = guc_malloc(FATAL,
3268                                                    strlen(configdir) + strlen(IDENT_FILENAME) + 2);
3269                 sprintf(fname, "%s/%s", configdir, IDENT_FILENAME);
3270         }
3271         else
3272         {
3273                 write_stderr("%s does not know where to find the \"ident\" configuration file.\n"
3274                                          "This can be specified as \"ident_file\" in \"%s\", "
3275                                          "or by the -D invocation option, or by the "
3276                                          "PGDATA environment variable.\n",
3277                                          progname, ConfigFileName);
3278                 return false;
3279         }
3280         SetConfigOption("ident_file", fname, PGC_POSTMASTER, PGC_S_OVERRIDE);
3281         free(fname);
3282
3283         free(configdir);
3284
3285         return true;
3286 }
3287
3288
3289 /*
3290  * Reset all options to their saved default values (implements RESET ALL)
3291  */
3292 void
3293 ResetAllOptions(void)
3294 {
3295         int                     i;
3296
3297         for (i = 0; i < num_guc_variables; i++)
3298         {
3299                 struct config_generic *gconf = guc_variables[i];
3300
3301                 /* Don't reset non-SET-able values */
3302                 if (gconf->context != PGC_SUSET &&
3303                         gconf->context != PGC_USERSET)
3304                         continue;
3305                 /* Don't reset if special exclusion from RESET ALL */
3306                 if (gconf->flags & GUC_NO_RESET_ALL)
3307                         continue;
3308                 /* No need to reset if wasn't SET */
3309                 if (gconf->source <= PGC_S_OVERRIDE)
3310                         continue;
3311
3312                 /* Save old value to support transaction abort */
3313                 push_old_value(gconf, GUC_ACTION_SET);
3314
3315                 switch (gconf->vartype)
3316                 {
3317                         case PGC_BOOL:
3318                                 {
3319                                         struct config_bool *conf = (struct config_bool *) gconf;
3320
3321                                         if (conf->assign_hook)
3322                                                 if (!(*conf->assign_hook) (conf->reset_val, true,
3323                                                                                                    PGC_S_SESSION))
3324                                                         elog(ERROR, "failed to reset %s", conf->gen.name);
3325                                         *conf->variable = conf->reset_val;
3326                                         conf->gen.source = conf->gen.reset_source;
3327                                         break;
3328                                 }
3329                         case PGC_INT:
3330                                 {
3331                                         struct config_int *conf = (struct config_int *) gconf;
3332
3333                                         if (conf->assign_hook)
3334                                                 if (!(*conf->assign_hook) (conf->reset_val, true,
3335                                                                                                    PGC_S_SESSION))
3336                                                         elog(ERROR, "failed to reset %s", conf->gen.name);
3337                                         *conf->variable = conf->reset_val;
3338                                         conf->gen.source = conf->gen.reset_source;
3339                                         break;
3340                                 }
3341                         case PGC_REAL:
3342                                 {
3343                                         struct config_real *conf = (struct config_real *) gconf;
3344
3345                                         if (conf->assign_hook)
3346                                                 if (!(*conf->assign_hook) (conf->reset_val, true,
3347                                                                                                    PGC_S_SESSION))
3348                                                         elog(ERROR, "failed to reset %s", conf->gen.name);
3349                                         *conf->variable = conf->reset_val;
3350                                         conf->gen.source = conf->gen.reset_source;
3351                                         break;
3352                                 }
3353                         case PGC_STRING:
3354                                 {
3355                                         struct config_string *conf = (struct config_string *) gconf;
3356                                         char       *str;
3357
3358                                         /* We need not strdup here */
3359                                         str = conf->reset_val;
3360
3361                                         if (conf->assign_hook && str)
3362                                         {
3363                                                 const char *newstr;
3364
3365                                                 newstr = (*conf->assign_hook) (str, true,
3366                                                                                                            PGC_S_SESSION);
3367                                                 if (newstr == NULL)
3368                                                         elog(ERROR, "failed to reset %s", conf->gen.name);
3369                                                 else if (newstr != str)
3370                                                 {
3371                                                         /*
3372                                                          * See notes in set_config_option about casting
3373                                                          */
3374                                                         str = (char *) newstr;
3375                                                 }
3376                                         }
3377
3378                                         set_string_field(conf, conf->variable, str);
3379                                         conf->gen.source = conf->gen.reset_source;
3380                                         break;
3381                                 }
3382                 }
3383
3384                 if (gconf->flags & GUC_REPORT)
3385                         ReportGUCOption(gconf);
3386         }
3387 }
3388
3389
3390 /*
3391  * push_old_value
3392  *              Push previous state during transactional assignment to a GUC variable.
3393  */
3394 static void
3395 push_old_value(struct config_generic * gconf, GucAction action)
3396 {
3397         GucStack   *stack;
3398
3399         /* If we're not inside a nest level, do nothing */
3400         if (GUCNestLevel == 0)
3401                 return;
3402
3403         /* Do we already have a stack entry of the current nest level? */
3404         stack = gconf->stack;
3405         if (stack && stack->nest_level >= GUCNestLevel)
3406         {
3407                 /* Yes, so adjust its state if necessary */
3408                 Assert(stack->nest_level == GUCNestLevel);
3409                 switch (action)
3410                 {
3411                         case GUC_ACTION_SET:
3412                                 /* SET overrides any prior action at same nest level */
3413                                 if (stack->state == GUC_SET_LOCAL)
3414                                 {
3415                                         /* must discard old masked value */
3416                                         discard_stack_value(gconf, &stack->masked);
3417                                 }
3418                                 stack->state = GUC_SET;
3419                                 break;
3420                         case GUC_ACTION_LOCAL:
3421                                 if (stack->state == GUC_SET)
3422                                 {
3423                                         /* SET followed by SET LOCAL, remember SET's value */
3424                                         set_stack_value(gconf, &stack->masked);
3425                                         stack->state = GUC_SET_LOCAL;
3426                                 }
3427                                 /* in all other cases, no change to stack entry */
3428                                 break;
3429                         case GUC_ACTION_SAVE:
3430                                 /* Could only have a prior SAVE of same variable */
3431                                 Assert(stack->state == GUC_SAVE);
3432                                 break;
3433                 }
3434                 Assert(guc_dirty);              /* must be set already */
3435                 return;
3436         }
3437
3438         /*
3439          * Push a new stack entry
3440          *
3441          * We keep all the stack entries in TopTransactionContext for simplicity.
3442          */
3443         stack = (GucStack *) MemoryContextAllocZero(TopTransactionContext,
3444                                                                                                 sizeof(GucStack));
3445
3446         stack->prev = gconf->stack;
3447         stack->nest_level = GUCNestLevel;
3448         switch (action)
3449         {
3450                 case GUC_ACTION_SET:
3451                         stack->state = GUC_SET;
3452                         break;
3453                 case GUC_ACTION_LOCAL:
3454                         stack->state = GUC_LOCAL;
3455                         break;
3456                 case GUC_ACTION_SAVE:
3457                         stack->state = GUC_SAVE;
3458                         break;
3459         }
3460         stack->source = gconf->source;
3461         set_stack_value(gconf, &stack->prior);
3462
3463         gconf->stack = stack;
3464
3465         /* Ensure we remember to pop at end of xact */
3466         guc_dirty = true;
3467 }
3468
3469
3470 /*
3471  * Do GUC processing at main transaction start.
3472  */
3473 void
3474 AtStart_GUC(void)
3475 {
3476         /*
3477          * The nest level should be 0 between transactions; if it isn't, somebody
3478          * didn't call AtEOXact_GUC, or called it with the wrong nestLevel.  We
3479          * throw a warning but make no other effort to clean up.
3480          */
3481         if (GUCNestLevel != 0)
3482                 elog(WARNING, "GUC nest level = %d at transaction start",
3483                          GUCNestLevel);
3484         GUCNestLevel = 1;
3485 }
3486
3487 /*
3488  * Enter a new nesting level for GUC values.  This is called at subtransaction
3489  * start and when entering a function that has proconfig settings.      NOTE that
3490  * we must not risk error here, else subtransaction start will be unhappy.
3491  */
3492 int
3493 NewGUCNestLevel(void)
3494 {
3495         return ++GUCNestLevel;
3496 }
3497
3498 /*
3499  * Do GUC processing at transaction or subtransaction commit or abort, or
3500  * when exiting a function that has proconfig settings.  (The name is thus
3501  * a bit of a misnomer; perhaps it should be ExitGUCNestLevel or some such.)
3502  * During abort, we discard all GUC settings that were applied at nesting
3503  * levels >= nestLevel.  nestLevel == 1 corresponds to the main transaction.
3504  */
3505 void
3506 AtEOXact_GUC(bool isCommit, int nestLevel)
3507 {
3508         bool            still_dirty;
3509         int                     i;
3510
3511         Assert(nestLevel > 0 && nestLevel <= GUCNestLevel);
3512
3513         /* Quick exit if nothing's changed in this transaction */
3514         if (!guc_dirty)
3515         {
3516                 GUCNestLevel = nestLevel - 1;
3517                 return;
3518         }
3519
3520         still_dirty = false;
3521         for (i = 0; i < num_guc_variables; i++)
3522         {
3523                 struct config_generic *gconf = guc_variables[i];
3524                 GucStack   *stack;
3525
3526                 /*
3527                  * Process and pop each stack entry within the nest level.      To
3528                  * simplify fmgr_security_definer(), we allow failure exit from a
3529                  * function-with-SET-options to be recovered at the surrounding
3530                  * transaction or subtransaction abort; so there could be more than
3531                  * one stack entry to pop.
3532                  */
3533                 while ((stack = gconf->stack) != NULL &&
3534                            stack->nest_level >= nestLevel)
3535                 {
3536                         GucStack   *prev = stack->prev;
3537                         bool            restorePrior = false;
3538                         bool            restoreMasked = false;
3539                         bool            changed;
3540
3541                         /*
3542                          * In this next bit, if we don't set either restorePrior or
3543                          * restoreMasked, we must "discard" any unwanted fields of the
3544                          * stack entries to avoid leaking memory.  If we do set one of
3545                          * those flags, unused fields will be cleaned up after restoring.
3546                          */
3547                         if (!isCommit)          /* if abort, always restore prior value */
3548                                 restorePrior = true;
3549                         else if (stack->state == GUC_SAVE)
3550                                 restorePrior = true;
3551                         else if (stack->nest_level == 1)
3552                         {
3553                                 /* transaction commit */
3554                                 if (stack->state == GUC_SET_LOCAL)
3555                                         restoreMasked = true;
3556                                 else if (stack->state == GUC_SET)
3557                                 {
3558                                         /* we keep the current active value */
3559                                         discard_stack_value(gconf, &stack->prior);
3560                                 }
3561                                 else    /* must be GUC_LOCAL */
3562                                         restorePrior = true;
3563                         }
3564                         else if (prev == NULL ||
3565                                          prev->nest_level < stack->nest_level - 1)
3566                         {
3567                                 /* decrement entry's level and do not pop it */
3568                                 stack->nest_level--;
3569                                 continue;
3570                         }
3571                         else
3572                         {
3573                                 /*
3574                                  * We have to merge this stack entry into prev. See README for
3575                                  * discussion of this bit.
3576                                  */
3577                                 switch (stack->state)
3578                                 {
3579                                         case GUC_SAVE:
3580                                                 Assert(false);  /* can't get here */
3581
3582                                         case GUC_SET:
3583                                                 /* next level always becomes SET */
3584                                                 discard_stack_value(gconf, &stack->prior);
3585                                                 if (prev->state == GUC_SET_LOCAL)
3586                                                         discard_stack_value(gconf, &prev->masked);
3587                                                 prev->state = GUC_SET;
3588                                                 break;
3589
3590                                         case GUC_LOCAL:
3591                                                 if (prev->state == GUC_SET)
3592                                                 {
3593                                                         /* LOCAL migrates down */
3594                                                         prev->masked = stack->prior;
3595                                                         prev->state = GUC_SET_LOCAL;
3596                                                 }
3597                                                 else
3598                                                 {
3599                                                         /* else just forget this stack level */
3600                                                         discard_stack_value(gconf, &stack->prior);
3601                                                 }
3602                                                 break;
3603
3604                                         case GUC_SET_LOCAL:
3605                                                 /* prior state at this level no longer wanted */
3606                                                 discard_stack_value(gconf, &stack->prior);
3607                                                 /* copy down the masked state */
3608                                                 if (prev->state == GUC_SET_LOCAL)
3609                                                         discard_stack_value(gconf, &prev->masked);
3610                                                 prev->masked = stack->masked;
3611                                                 prev->state = GUC_SET_LOCAL;
3612                                                 break;
3613                                 }
3614                         }
3615
3616                         changed = false;
3617
3618                         if (restorePrior || restoreMasked)
3619                         {
3620                                 /* Perform appropriate restoration of the stacked value */
3621                                 union config_var_value newvalue;
3622                                 GucSource       newsource;
3623
3624                                 if (restoreMasked)
3625                                 {
3626                                         newvalue = stack->masked;
3627                                         newsource = PGC_S_SESSION;
3628                                 }
3629                                 else
3630                                 {
3631                                         newvalue = stack->prior;
3632                                         newsource = stack->source;
3633                                 }
3634
3635                                 switch (gconf->vartype)
3636                                 {
3637                                         case PGC_BOOL:
3638                                                 {
3639                                                         struct config_bool *conf = (struct config_bool *) gconf;
3640                                                         bool            newval = newvalue.boolval;
3641
3642                                                         if (*conf->variable != newval)
3643                                                         {
3644                                                                 if (conf->assign_hook)
3645                                                                         if (!(*conf->assign_hook) (newval,
3646                                                                                                            true, PGC_S_OVERRIDE))
3647                                                                                 elog(LOG, "failed to commit %s",
3648                                                                                          conf->gen.name);
3649                                                                 *conf->variable = newval;
3650                                                                 changed = true;
3651                                                         }
3652                                                         break;
3653                                                 }
3654                                         case PGC_INT:
3655                                                 {
3656                                                         struct config_int *conf = (struct config_int *) gconf;
3657                                                         int                     newval = newvalue.intval;
3658
3659                                                         if (*conf->variable != newval)
3660                                                         {
3661                                                                 if (conf->assign_hook)
3662                                                                         if (!(*conf->assign_hook) (newval,
3663                                                                                                            true, PGC_S_OVERRIDE))
3664                                                                                 elog(LOG, "failed to commit %s",
3665                                                                                          conf->gen.name);
3666                                                                 *conf->variable = newval;
3667                                                                 changed = true;
3668                                                         }
3669                                                         break;
3670                                                 }
3671                                         case PGC_REAL:
3672                                                 {
3673                                                         struct config_real *conf = (struct config_real *) gconf;
3674                                                         double          newval = newvalue.realval;
3675
3676                                                         if (*conf->variable != newval)
3677                                                         {
3678                                                                 if (conf->assign_hook)
3679                                                                         if (!(*conf->assign_hook) (newval,
3680                                                                                                            true, PGC_S_OVERRIDE))
3681                                                                                 elog(LOG, "failed to commit %s",
3682                                                                                          conf->gen.name);
3683                                                                 *conf->variable = newval;
3684                                                                 changed = true;
3685                                                         }
3686                                                         break;
3687                                                 }
3688                                         case PGC_STRING:
3689                                                 {
3690                                                         struct config_string *conf = (struct config_string *) gconf;
3691                                                         char       *newval = newvalue.stringval;
3692
3693                                                         if (*conf->variable != newval)
3694                                                         {
3695                                                                 if (conf->assign_hook && newval)
3696                                                                 {
3697                                                                         const char *newstr;
3698
3699                                                                         newstr = (*conf->assign_hook) (newval, true,
3700                                                                                                                          PGC_S_OVERRIDE);
3701                                                                         if (newstr == NULL)
3702                                                                                 elog(LOG, "failed to commit %s",
3703                                                                                          conf->gen.name);
3704                                                                         else if (newstr != newval)
3705                                                                         {
3706                                                                                 /*
3707                                                                                  * If newval should now be freed,
3708                                                                                  * it'll be taken care of below.
3709                                                                                  *
3710                                                                                  * See notes in set_config_option
3711                                                                                  * about casting
3712                                                                                  */
3713                                                                                 newval = (char *) newstr;
3714                                                                         }
3715                                                                 }
3716
3717                                                                 set_string_field(conf, conf->variable, newval);
3718                                                                 changed = true;
3719                                                         }
3720
3721                                                         /*
3722                                                          * Release stacked values if not used anymore. We
3723                                                          * could use discard_stack_value() here, but since
3724                                                          * we have type-specific code anyway, might as
3725                                                          * well inline it.
3726                                                          */
3727                                                         set_string_field(conf, &stack->prior.stringval, NULL);
3728                                                         set_string_field(conf, &stack->masked.stringval, NULL);
3729                                                         break;
3730                                                 }
3731                                 }
3732
3733                                 gconf->source = newsource;
3734                         }
3735
3736                         /* Finish popping the state stack */
3737                         gconf->stack = prev;
3738                         pfree(stack);
3739
3740                         /* Report new value if we changed it */
3741                         if (changed && (gconf->flags & GUC_REPORT))
3742                                 ReportGUCOption(gconf);
3743                 }                                               /* end of stack-popping loop */
3744
3745                 if (stack != NULL)
3746                         still_dirty = true;
3747         }
3748
3749         /* If there are no remaining stack entries, we can reset guc_dirty */
3750         guc_dirty = still_dirty;
3751
3752         /* Update nesting level */
3753         GUCNestLevel = nestLevel - 1;
3754 }
3755
3756
3757 /*
3758  * Start up automatic reporting of changes to variables marked GUC_REPORT.
3759  * This is executed at completion of backend startup.
3760  */
3761 void
3762 BeginReportingGUCOptions(void)
3763 {
3764         int                     i;
3765
3766         /*
3767          * Don't do anything unless talking to an interactive frontend of protocol
3768          * 3.0 or later.
3769          */
3770         if (whereToSendOutput != DestRemote ||
3771                 PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
3772                 return;
3773
3774         reporting_enabled = true;
3775
3776         /* Transmit initial values of interesting variables */
3777         for (i = 0; i < num_guc_variables; i++)
3778         {
3779                 struct config_generic *conf = guc_variables[i];
3780
3781                 if (conf->flags & GUC_REPORT)
3782                         ReportGUCOption(conf);
3783         }
3784 }
3785
3786 /*
3787  * ReportGUCOption: if appropriate, transmit option value to frontend
3788  */
3789 static void
3790 ReportGUCOption(struct config_generic * record)
3791 {
3792         if (reporting_enabled && (record->flags & GUC_REPORT))
3793         {
3794                 char       *val = _ShowOption(record, false);
3795                 StringInfoData msgbuf;
3796
3797                 pq_beginmessage(&msgbuf, 'S');
3798                 pq_sendstring(&msgbuf, record->name);
3799                 pq_sendstring(&msgbuf, val);
3800                 pq_endmessage(&msgbuf);
3801
3802                 pfree(val);
3803         }
3804 }
3805
3806
3807 /*
3808  * Try to interpret value as boolean value.  Valid values are: true,
3809  * false, yes, no, on, off, 1, 0; as well as unique prefixes thereof.
3810  * If the string parses okay, return true, else false.
3811  * If okay and result is not NULL, return the value in *result.
3812  */
3813 static bool
3814 parse_bool(const char *value, bool *result)
3815 {
3816         size_t          len = strlen(value);
3817
3818         if (pg_strncasecmp(value, "true", len) == 0)
3819         {
3820                 if (result)
3821                         *result = true;
3822         }
3823         else if (pg_strncasecmp(value, "false", len) == 0)
3824         {
3825                 if (result)
3826                         *result = false;
3827         }
3828
3829         else if (pg_strncasecmp(value, "yes", len) == 0)
3830         {
3831                 if (result)
3832                         *result = true;
3833         }
3834         else if (pg_strncasecmp(value, "no", len) == 0)
3835         {
3836                 if (result)
3837                         *result = false;
3838         }
3839
3840         /* 'o' is not unique enough */
3841         else if (pg_strncasecmp(value, "on", (len > 2 ? len : 2)) == 0)
3842         {
3843                 if (result)
3844                         *result = true;
3845         }
3846         else if (pg_strncasecmp(value, "off", (len > 2 ? len : 2)) == 0)
3847         {
3848                 if (result)
3849                         *result = false;
3850         }
3851
3852         else if (pg_strcasecmp(value, "1") == 0)
3853         {
3854                 if (result)
3855                         *result = true;
3856         }
3857         else if (pg_strcasecmp(value, "0") == 0)
3858         {
3859                 if (result)
3860                         *result = false;
3861         }
3862
3863         else
3864         {
3865                 if (result)
3866                         *result = false;        /* suppress compiler warning */
3867                 return false;
3868         }
3869         return true;
3870 }
3871
3872
3873
3874 /*
3875  * Try to parse value as an integer.  The accepted formats are the
3876  * usual decimal, octal, or hexadecimal formats, optionally followed by
3877  * a unit name if "flags" indicates a unit is allowed.
3878  *
3879  * If the string parses okay, return true, else false.
3880  * If okay and result is not NULL, return the value in *result.
3881  * If not okay and hintmsg is not NULL, *hintmsg is set to a suitable
3882  *      HINT message, or NULL if no hint provided.
3883  */
3884 static bool
3885 parse_int(const char *value, int *result, int flags, const char **hintmsg)
3886 {
3887         int64           val;
3888         char       *endptr;
3889
3890         /* To suppress compiler warnings, always set output params */
3891         if (result)
3892                 *result = 0;
3893         if (hintmsg)
3894                 *hintmsg = NULL;
3895
3896         /* We assume here that int64 is at least as wide as long */
3897         errno = 0;
3898         val = strtol(value, &endptr, 0);
3899
3900         if (endptr == value)
3901                 return false;                   /* no HINT for integer syntax error */
3902
3903         if (errno == ERANGE || val != (int64) ((int32) val))
3904         {
3905                 if (hintmsg)
3906                         *hintmsg = gettext_noop("Value exceeds integer range.");
3907                 return false;
3908         }
3909
3910         /* allow whitespace between integer and unit */
3911         while (isspace((unsigned char) *endptr))
3912                 endptr++;
3913
3914         /* Handle possible unit */
3915         if (*endptr != '\0')
3916         {
3917                 /*
3918                  * Note: the multiple-switch coding technique here is a bit tedious,
3919                  * but seems necessary to avoid intermediate-value overflows.
3920                  *
3921                  * If INT64_IS_BUSTED (ie, it's really int32) we will fail to detect
3922                  * overflow due to units conversion, but there are few enough such
3923                  * machines that it does not seem worth trying to be smarter.
3924                  */
3925                 if (flags & GUC_UNIT_MEMORY)
3926                 {
3927                         /* Set hint for use if no match or trailing garbage */
3928                         if (hintmsg)
3929                                 *hintmsg = gettext_noop("Valid units for this parameter are \"kB\", \"MB\", and \"GB\".");
3930
3931 #if BLCKSZ < 1024 || BLCKSZ > (1024*1024)
3932 #error BLCKSZ must be between 1KB and 1MB
3933 #endif
3934 #if XLOG_BLCKSZ < 1024 || XLOG_BLCKSZ > (1024*1024)
3935 #error XLOG_BLCKSZ must be between 1KB and 1MB
3936 #endif
3937
3938                         if (strncmp(endptr, "kB", 2) == 0)
3939                         {
3940                                 endptr += 2;
3941                                 switch (flags & GUC_UNIT_MEMORY)
3942                                 {
3943                                         case GUC_UNIT_BLOCKS:
3944                                                 val /= (BLCKSZ / 1024);
3945                                                 break;
3946                                         case GUC_UNIT_XBLOCKS:
3947                                                 val /= (XLOG_BLCKSZ / 1024);
3948                                                 break;
3949                                 }
3950                         }
3951                         else if (strncmp(endptr, "MB", 2) == 0)
3952                         {
3953                                 endptr += 2;
3954                                 switch (flags & GUC_UNIT_MEMORY)
3955                                 {
3956                                         case GUC_UNIT_KB:
3957                                                 val *= KB_PER_MB;
3958                                                 break;
3959                                         case GUC_UNIT_BLOCKS:
3960                                                 val *= KB_PER_MB / (BLCKSZ / 1024);
3961                                                 break;
3962                                         case GUC_UNIT_XBLOCKS:
3963                                                 val *= KB_PER_MB / (XLOG_BLCKSZ / 1024);
3964                                                 break;
3965                                 }
3966                         }
3967                         else if (strncmp(endptr, "GB", 2) == 0)
3968                         {
3969                                 endptr += 2;
3970                                 switch (flags & GUC_UNIT_MEMORY)
3971                                 {
3972                                         case GUC_UNIT_KB:
3973                                                 val *= KB_PER_GB;
3974                                                 break;
3975                                         case GUC_UNIT_BLOCKS:
3976                                                 val *= KB_PER_GB / (BLCKSZ / 1024);
3977                                                 break;
3978                                         case GUC_UNIT_XBLOCKS:
3979                                                 val *= KB_PER_GB / (XLOG_BLCKSZ / 1024);
3980                                                 break;
3981                                 }
3982                         }
3983                 }
3984                 else if (flags & GUC_UNIT_TIME)
3985                 {
3986                         /* Set hint for use if no match or trailing garbage */
3987                         if (hintmsg)
3988                                 *hintmsg = gettext_noop("Valid units for this parameter are \"ms\", \"s\", \"min\", \"h\", and \"d\".");
3989
3990                         if (strncmp(endptr, "ms", 2) == 0)
3991                         {
3992                                 endptr += 2;
3993                                 switch (flags & GUC_UNIT_TIME)
3994                                 {
3995                                         case GUC_UNIT_S:
3996                                                 val /= MS_PER_S;
3997                                                 break;
3998                                         case GUC_UNIT_MIN:
3999                                                 val /= MS_PER_MIN;
4000                                                 break;
4001                                 }
4002                         }
4003                         else if (strncmp(endptr, "s", 1) == 0)
4004                         {
4005                                 endptr += 1;
4006                                 switch (flags & GUC_UNIT_TIME)
4007                                 {
4008                                         case GUC_UNIT_MS:
4009                                                 val *= MS_PER_S;
4010                                                 break;
4011                                         case GUC_UNIT_MIN:
4012                                                 val /= S_PER_MIN;
4013                                                 break;
4014                                 }
4015                         }
4016                         else if (strncmp(endptr, "min", 3) == 0)
4017                         {
4018                                 endptr += 3;
4019                                 switch (flags & GUC_UNIT_TIME)
4020                                 {
4021                                         case GUC_UNIT_MS:
4022                                                 val *= MS_PER_MIN;
4023                                                 break;
4024                                         case GUC_UNIT_S:
4025                                                 val *= S_PER_MIN;
4026                                                 break;
4027                                 }
4028                         }
4029                         else if (strncmp(endptr, "h", 1) == 0)
4030                         {
4031                                 endptr += 1;
4032                                 switch (flags & GUC_UNIT_TIME)
4033                                 {
4034                                         case GUC_UNIT_MS:
4035                                                 val *= MS_PER_H;
4036                                                 break;
4037                                         case GUC_UNIT_S:
4038                                                 val *= S_PER_H;
4039                                                 break;
4040                                         case GUC_UNIT_MIN:
4041                                                 val *= MIN_PER_H;
4042                                                 break;
4043                                 }
4044                         }
4045                         else if (strncmp(endptr, "d", 1) == 0)
4046                         {
4047                                 endptr += 1;
4048                                 switch (flags & GUC_UNIT_TIME)
4049                                 {
4050                                         case GUC_UNIT_MS:
4051                                                 val *= MS_PER_D;
4052                                                 break;
4053                                         case GUC_UNIT_S:
4054                                                 val *= S_PER_D;
4055                                                 break;
4056                                         case GUC_UNIT_MIN:
4057                                                 val *= MIN_PER_D;
4058                                                 break;
4059                                 }
4060                         }
4061                 }
4062
4063                 /* allow whitespace after unit */
4064                 while (isspace((unsigned char) *endptr))
4065                         endptr++;
4066
4067                 if (*endptr != '\0')
4068                         return false;           /* appropriate hint, if any, already set */
4069
4070                 /* Check for overflow due to units conversion */
4071                 if (val != (int64) ((int32) val))
4072                 {
4073                         if (hintmsg)
4074                                 *hintmsg = gettext_noop("Value exceeds integer range.");
4075                         return false;
4076                 }
4077         }
4078
4079         if (result)
4080                 *result = (int) val;
4081         return true;
4082 }
4083
4084
4085
4086 /*
4087  * Try to parse value as a floating point number in the usual format.
4088  * If the string parses okay, return true, else false.
4089  * If okay and result is not NULL, return the value in *result.
4090  */
4091 static bool
4092 parse_real(const char *value, double *result)
4093 {
4094         double          val;
4095         char       *endptr;
4096
4097         if (result)
4098                 *result = 0;                    /* suppress compiler warning */
4099
4100         errno = 0;
4101         val = strtod(value, &endptr);
4102         if (endptr == value || errno == ERANGE)
4103                 return false;
4104
4105         /* allow whitespace after number */
4106         while (isspace((unsigned char) *endptr))
4107                 endptr++;
4108         if (*endptr != '\0')
4109                 return false;
4110
4111         if (result)
4112                 *result = val;
4113         return true;
4114 }
4115
4116
4117 /*
4118  * Call a GucStringAssignHook function, being careful to free the
4119  * "newval" string if the hook ereports.
4120  *
4121  * This is split out of set_config_option just to avoid the "volatile"
4122  * qualifiers that would otherwise have to be plastered all over.
4123  */
4124 static const char *
4125 call_string_assign_hook(GucStringAssignHook assign_hook,
4126                                                 char *newval, bool doit, GucSource source)
4127 {
4128         const char *result;
4129
4130         PG_TRY();
4131         {
4132                 result = (*assign_hook) (newval, doit, source);
4133         }
4134         PG_CATCH();
4135         {
4136                 free(newval);
4137                 PG_RE_THROW();
4138         }
4139         PG_END_TRY();
4140
4141         return result;
4142 }
4143
4144
4145 /*
4146  * Sets option `name' to given value. The value should be a string
4147  * which is going to be parsed and converted to the appropriate data
4148  * type.  The context and source parameters indicate in which context this
4149  * function is being called so it can apply the access restrictions
4150  * properly.
4151  *
4152  * If value is NULL, set the option to its default value (normally the
4153  * reset_val, but if source == PGC_S_DEFAULT we instead use the boot_val).
4154  *
4155  * action indicates whether to set the value globally in the session, locally
4156  * to the current top transaction, or just for the duration of a function call.
4157  *
4158  * If changeVal is false then don't really set the option but do all
4159  * the checks to see if it would work.
4160  *
4161  * If there is an error (non-existing option, invalid value) then an
4162  * ereport(ERROR) is thrown *unless* this is called in a context where we
4163  * don't want to ereport (currently, startup or SIGHUP config file reread).
4164  * In that case we write a suitable error message via ereport(LOG) and
4165  * return false. This is working around the deficiencies in the ereport
4166  * mechanism, so don't blame me.  In all other cases, the function
4167  * returns true, including cases where the input is valid but we chose
4168  * not to apply it because of context or source-priority considerations.
4169  *
4170  * See also SetConfigOption for an external interface.
4171  */
4172 bool
4173 set_config_option(const char *name, const char *value,
4174                                   GucContext context, GucSource source,
4175                                   GucAction action, bool changeVal)
4176 {
4177         struct config_generic *record;
4178         int                     elevel;
4179         bool            makeDefault;
4180
4181         if (context == PGC_SIGHUP || source == PGC_S_DEFAULT)
4182         {
4183                 /*
4184                  * To avoid cluttering the log, only the postmaster bleats loudly
4185                  * about problems with the config file.
4186                  */
4187                 elevel = IsUnderPostmaster ? DEBUG3 : LOG;
4188         }
4189         else if (source == PGC_S_DATABASE || source == PGC_S_USER)
4190                 elevel = INFO;
4191         else
4192                 elevel = ERROR;
4193
4194         record = find_option(name, true, elevel);
4195         if (record == NULL)
4196         {
4197                 ereport(elevel,
4198                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
4199                            errmsg("unrecognized configuration parameter \"%s\"", name)));
4200                 return false;
4201         }
4202
4203         /*
4204          * If source is postgresql.conf, mark the found record with
4205          * GUC_IS_IN_FILE. This is for the convenience of ProcessConfigFile.  Note
4206          * that we do it even if changeVal is false, since ProcessConfigFile wants
4207          * the marking to occur during its testing pass.
4208          */
4209         if (source == PGC_S_FILE)
4210                 record->status |= GUC_IS_IN_FILE;
4211
4212         /*
4213          * Check if the option can be set at this time. See guc.h for the precise
4214          * rules. Note that we don't want to throw errors if we're in the SIGHUP
4215          * context. In that case we just ignore the attempt and return true.
4216          */
4217         switch (record->context)
4218         {
4219                 case PGC_INTERNAL:
4220                         if (context == PGC_SIGHUP)
4221                                 return true;
4222                         if (context != PGC_INTERNAL)
4223                         {
4224                                 ereport(elevel,
4225                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
4226                                                  errmsg("parameter \"%s\" cannot be changed",
4227                                                                 name)));
4228                                 return false;
4229                         }
4230                         break;
4231                 case PGC_POSTMASTER:
4232                         if (context == PGC_SIGHUP)
4233                         {
4234                                 /*
4235                                  * We are reading a PGC_POSTMASTER var from postgresql.conf.
4236                                  * We can't change the setting, so give a warning if the DBA
4237                                  * tries to change it.  (Throwing an error would be more
4238                                  * consistent, but seems overly rigid.)
4239                                  */
4240                                 if (changeVal && !is_newvalue_equal(record, value))
4241                                         ereport(elevel,
4242                                                         (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
4243                                                          errmsg("parameter \"%s\" cannot be changed after server start; configuration file change ignored",
4244                                                                         name)));
4245                                 return true;
4246                         }
4247                         if (context != PGC_POSTMASTER)
4248                         {
4249                                 ereport(elevel,
4250                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
4251                                                  errmsg("parameter \"%s\" cannot be changed after server start",
4252                                                                 name)));
4253                                 return false;
4254                         }
4255                         break;
4256                 case PGC_SIGHUP:
4257                         if (context != PGC_SIGHUP && context != PGC_POSTMASTER)
4258                         {
4259                                 ereport(elevel,
4260                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
4261                                                  errmsg("parameter \"%s\" cannot be changed now",
4262                                                                 name)));
4263                                 return false;
4264                         }
4265
4266                         /*
4267                          * Hmm, the idea of the SIGHUP context is "ought to be global, but
4268                          * can be changed after postmaster start". But there's nothing
4269                          * that prevents a crafty administrator from sending SIGHUP
4270                          * signals to individual backends only.
4271                          */
4272                         break;
4273                 case PGC_BACKEND:
4274                         if (context == PGC_SIGHUP)
4275                         {
4276                                 /*
4277                                  * If a PGC_BACKEND parameter is changed in the config file,
4278                                  * we want to accept the new value in the postmaster (whence
4279                                  * it will propagate to subsequently-started backends), but
4280                                  * ignore it in existing backends.      This is a tad klugy, but
4281                                  * necessary because we don't re-read the config file during
4282                                  * backend start.
4283                                  */
4284                                 if (IsUnderPostmaster)
4285                                         return true;
4286                         }
4287                         else if (context != PGC_BACKEND && context != PGC_POSTMASTER)
4288                         {
4289                                 ereport(elevel,
4290                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
4291                                                  errmsg("parameter \"%s\" cannot be set after connection start",
4292                                                                 name)));
4293                                 return false;
4294                         }
4295                         break;
4296                 case PGC_SUSET:
4297                         if (context == PGC_USERSET || context == PGC_BACKEND)
4298                         {
4299                                 ereport(elevel,
4300                                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
4301                                                  errmsg("permission denied to set parameter \"%s\"",
4302                                                                 name)));
4303                                 return false;
4304                         }
4305                         break;
4306                 case PGC_USERSET:
4307                         /* always okay */
4308                         break;
4309         }
4310
4311         /*
4312          * Should we set reset/stacked values?  (If so, the behavior is not
4313          * transactional.)      This is done either when we get a default value from
4314          * the database's/user's/client's default settings or when we reset a
4315          * value to its default.
4316          */
4317         makeDefault = changeVal && (source <= PGC_S_OVERRIDE) &&
4318                 ((value != NULL) || source == PGC_S_DEFAULT);
4319
4320         /*
4321          * Ignore attempted set if overridden by previously processed setting.
4322          * However, if changeVal is false then plow ahead anyway since we are
4323          * trying to find out if the value is potentially good, not actually use
4324          * it. Also keep going if makeDefault is true, since we may want to set
4325          * the reset/stacked values even if we can't set the variable itself.
4326          */
4327         if (record->source > source)
4328         {
4329                 if (changeVal && !makeDefault)
4330                 {
4331                         elog(DEBUG3, "\"%s\": setting ignored because previous source is higher priority",
4332                                  name);
4333                         return true;
4334                 }
4335                 changeVal = false;
4336         }
4337
4338         /*
4339          * Evaluate value and set variable.
4340          */
4341         switch (record->vartype)
4342         {
4343                 case PGC_BOOL:
4344                         {
4345                                 struct config_bool *conf = (struct config_bool *) record;
4346                                 bool            newval;
4347
4348                                 if (value)
4349                                 {
4350                                         if (!parse_bool(value, &newval))
4351                                         {
4352                                                 ereport(elevel,
4353                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4354                                                   errmsg("parameter \"%s\" requires a Boolean value",
4355                                                                  name)));
4356                                                 return false;
4357                                         }
4358                                 }
4359                                 else if (source == PGC_S_DEFAULT)
4360                                         newval = conf->boot_val;
4361                                 else
4362                                 {
4363                                         newval = conf->reset_val;
4364                                         source = conf->gen.reset_source;
4365                                 }
4366
4367                                 if (conf->assign_hook)
4368                                         if (!(*conf->assign_hook) (newval, changeVal, source))
4369                                         {
4370                                                 ereport(elevel,
4371                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4372                                                          errmsg("invalid value for parameter \"%s\": %d",
4373                                                                         name, (int) newval)));
4374                                                 return false;
4375                                         }
4376
4377                                 if (changeVal || makeDefault)
4378                                 {
4379                                         /* Save old value to support transaction abort */
4380                                         if (!makeDefault)
4381                                                 push_old_value(&conf->gen, action);
4382                                         if (changeVal)
4383                                         {
4384                                                 *conf->variable = newval;
4385                                                 conf->gen.source = source;
4386                                         }
4387                                         if (makeDefault)
4388                                         {
4389                                                 GucStack   *stack;
4390
4391                                                 if (conf->gen.reset_source <= source)
4392                                                 {
4393                                                         conf->reset_val = newval;
4394                                                         conf->gen.reset_source = source;
4395                                                 }
4396                                                 for (stack = conf->gen.stack; stack; stack = stack->prev)
4397                                                 {
4398                                                         if (stack->source <= source)
4399                                                         {
4400                                                                 stack->prior.boolval = newval;
4401                                                                 stack->source = source;
4402                                                         }
4403                                                 }
4404                                         }
4405                                 }
4406                                 break;
4407                         }
4408
4409                 case PGC_INT:
4410                         {
4411                                 struct config_int *conf = (struct config_int *) record;
4412                                 int                     newval;
4413
4414                                 if (value)
4415                                 {
4416                                         const char *hintmsg;
4417
4418                                         if (!parse_int(value, &newval, conf->gen.flags, &hintmsg))
4419                                         {
4420                                                 ereport(elevel,
4421                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4422                                                  errmsg("invalid value for parameter \"%s\": \"%s\"",
4423                                                                 name, value),
4424                                                                  hintmsg ? errhint(hintmsg) : 0));
4425                                                 return false;
4426                                         }
4427                                         if (newval < conf->min || newval > conf->max)
4428                                         {
4429                                                 ereport(elevel,
4430                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4431                                                                  errmsg("%d is outside the valid range for parameter \"%s\" (%d .. %d)",
4432                                                                                 newval, name, conf->min, conf->max)));
4433                                                 return false;
4434                                         }
4435                                 }
4436                                 else if (source == PGC_S_DEFAULT)
4437                                         newval = conf->boot_val;
4438                                 else
4439                                 {
4440                                         newval = conf->reset_val;
4441                                         source = conf->gen.reset_source;
4442                                 }
4443
4444                                 if (conf->assign_hook)
4445                                         if (!(*conf->assign_hook) (newval, changeVal, source))
4446                                         {
4447                                                 ereport(elevel,
4448                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4449                                                          errmsg("invalid value for parameter \"%s\": %d",
4450                                                                         name, newval)));
4451                                                 return false;
4452                                         }
4453
4454                                 if (changeVal || makeDefault)
4455                                 {
4456                                         /* Save old value to support transaction abort */
4457                                         if (!makeDefault)
4458                                                 push_old_value(&conf->gen, action);
4459                                         if (changeVal)
4460                                         {
4461                                                 *conf->variable = newval;
4462                                                 conf->gen.source = source;
4463                                         }
4464                                         if (makeDefault)
4465                                         {
4466                                                 GucStack   *stack;
4467
4468                                                 if (conf->gen.reset_source <= source)
4469                                                 {
4470                                                         conf->reset_val = newval;
4471                                                         conf->gen.reset_source = source;
4472                                                 }
4473                                                 for (stack = conf->gen.stack; stack; stack = stack->prev)
4474                                                 {
4475                                                         if (stack->source <= source)
4476                                                         {
4477                                                                 stack->prior.intval = newval;
4478                                                                 stack->source = source;
4479                                                         }
4480                                                 }
4481                                         }
4482                                 }
4483                                 break;
4484                         }
4485
4486                 case PGC_REAL:
4487                         {
4488                                 struct config_real *conf = (struct config_real *) record;
4489                                 double          newval;
4490
4491                                 if (value)
4492                                 {
4493                                         if (!parse_real(value, &newval))
4494                                         {
4495                                                 ereport(elevel,
4496                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4497                                                   errmsg("parameter \"%s\" requires a numeric value",
4498                                                                  name)));
4499                                                 return false;
4500                                         }
4501                                         if (newval < conf->min || newval > conf->max)
4502                                         {
4503                                                 ereport(elevel,
4504                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4505                                                                  errmsg("%g is outside the valid range for parameter \"%s\" (%g .. %g)",
4506                                                                                 newval, name, conf->min, conf->max)));
4507                                                 return false;
4508                                         }
4509                                 }
4510                                 else if (source == PGC_S_DEFAULT)
4511                                         newval = conf->boot_val;
4512                                 else
4513                                 {
4514                                         newval = conf->reset_val;
4515                                         source = conf->gen.reset_source;
4516                                 }
4517
4518                                 if (conf->assign_hook)
4519                                         if (!(*conf->assign_hook) (newval, changeVal, source))
4520                                         {
4521                                                 ereport(elevel,
4522                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4523                                                          errmsg("invalid value for parameter \"%s\": %g",
4524                                                                         name, newval)));
4525                                                 return false;
4526                                         }
4527
4528                                 if (changeVal || makeDefault)
4529                                 {
4530                                         /* Save old value to support transaction abort */
4531                                         if (!makeDefault)
4532                                                 push_old_value(&conf->gen, action);
4533                                         if (changeVal)
4534                                         {
4535                                                 *conf->variable = newval;
4536                                                 conf->gen.source = source;
4537                                         }
4538                                         if (makeDefault)
4539                                         {
4540                                                 GucStack   *stack;
4541
4542                                                 if (conf->gen.reset_source <= source)
4543                                                 {
4544                                                         conf->reset_val = newval;
4545                                                         conf->gen.reset_source = source;
4546                                                 }
4547                                                 for (stack = conf->gen.stack; stack; stack = stack->prev)
4548                                                 {
4549                                                         if (stack->source <= source)
4550                                                         {
4551                                                                 stack->prior.realval = newval;
4552                                                                 stack->source = source;
4553                                                         }
4554                                                 }
4555                                         }
4556                                 }
4557                                 break;
4558                         }
4559
4560                 case PGC_STRING:
4561                         {
4562                                 struct config_string *conf = (struct config_string *) record;
4563                                 char       *newval;
4564
4565                                 if (value)
4566                                 {
4567                                         newval = guc_strdup(elevel, value);
4568                                         if (newval == NULL)
4569                                                 return false;
4570
4571                                         /*
4572                                          * The only sort of "parsing" check we need to do is apply
4573                                          * truncation if GUC_IS_NAME.
4574                                          */
4575                                         if (conf->gen.flags & GUC_IS_NAME)
4576                                                 truncate_identifier(newval, strlen(newval), true);
4577                                 }
4578                                 else if (source == PGC_S_DEFAULT)
4579                                 {
4580                                         if (conf->boot_val == NULL)
4581                                                 newval = NULL;
4582                                         else
4583                                         {
4584                                                 newval = guc_strdup(elevel, conf->boot_val);
4585                                                 if (newval == NULL)
4586                                                         return false;
4587                                         }
4588                                 }
4589                                 else
4590                                 {
4591                                         /*
4592                                          * We could possibly avoid strdup here, but easier to make
4593                                          * this case work the same as the normal assignment case;
4594                                          * note the possible free of newval below.
4595                                          */
4596                                         if (conf->reset_val == NULL)
4597                                                 newval = NULL;
4598                                         else
4599                                         {
4600                                                 newval = guc_strdup(elevel, conf->reset_val);
4601                                                 if (newval == NULL)
4602                                                         return false;
4603                                         }
4604                                         source = conf->gen.reset_source;
4605                                 }
4606
4607                                 if (conf->assign_hook && newval)
4608                                 {
4609                                         const char *hookresult;
4610
4611                                         /*
4612                                          * If the hook ereports, we have to make sure we free
4613                                          * newval, else it will be a permanent memory leak.
4614                                          */
4615                                         hookresult = call_string_assign_hook(conf->assign_hook,
4616                                                                                                                  newval,
4617                                                                                                                  changeVal,
4618                                                                                                                  source);
4619                                         if (hookresult == NULL)
4620                                         {
4621                                                 free(newval);
4622                                                 ereport(elevel,
4623                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4624                                                  errmsg("invalid value for parameter \"%s\": \"%s\"",
4625                                                                 name, value ? value : "")));
4626                                                 return false;
4627                                         }
4628                                         else if (hookresult != newval)
4629                                         {
4630                                                 free(newval);
4631
4632                                                 /*
4633                                                  * Having to cast away const here is annoying, but the
4634                                                  * alternative is to declare assign_hooks as returning
4635                                                  * char*, which would mean they'd have to cast away
4636                                                  * const, or as both taking and returning char*, which
4637                                                  * doesn't seem attractive either --- we don't want
4638                                                  * them to scribble on the passed str.
4639                                                  */
4640                                                 newval = (char *) hookresult;
4641                                         }
4642                                 }
4643
4644                                 if (changeVal || makeDefault)
4645                                 {
4646                                         /* Save old value to support transaction abort */
4647                                         if (!makeDefault)
4648                                                 push_old_value(&conf->gen, action);
4649                                         if (changeVal)
4650                                         {
4651                                                 set_string_field(conf, conf->variable, newval);
4652                                                 conf->gen.source = source;
4653                                         }
4654                                         if (makeDefault)
4655                                         {
4656                                                 GucStack   *stack;
4657
4658                                                 if (conf->gen.reset_source <= source)
4659                                                 {
4660                                                         set_string_field(conf, &conf->reset_val, newval);
4661                                                         conf->gen.reset_source = source;
4662                                                 }
4663                                                 for (stack = conf->gen.stack; stack; stack = stack->prev)
4664                                                 {
4665                                                         if (stack->source <= source)
4666                                                         {
4667                                                                 set_string_field(conf, &stack->prior.stringval,
4668                                                                                                  newval);
4669                                                                 stack->source = source;
4670                                                         }
4671                                                 }
4672                                                 /* Perhaps we didn't install newval anywhere */
4673                                                 if (newval && !string_field_used(conf, newval))
4674                                                         free(newval);
4675                                         }
4676                                 }
4677                                 else if (newval)
4678                                         free(newval);
4679                                 break;
4680                         }
4681         }
4682
4683         if (changeVal && (record->flags & GUC_REPORT))
4684                 ReportGUCOption(record);
4685
4686         return true;
4687 }
4688
4689
4690 /*
4691  * Set a config option to the given value. See also set_config_option,
4692  * this is just the wrapper to be called from outside GUC.      NB: this
4693  * is used only for non-transactional operations.
4694  */
4695 void
4696 SetConfigOption(const char *name, const char *value,
4697                                 GucContext context, GucSource source)
4698 {
4699         (void) set_config_option(name, value, context, source,
4700                                                          GUC_ACTION_SET, true);
4701 }
4702
4703
4704
4705 /*
4706  * Fetch the current value of the option `name'. If the option doesn't exist,
4707  * throw an ereport and don't return.
4708  *
4709  * The string is *not* allocated for modification and is really only
4710  * valid until the next call to configuration related functions.
4711  */
4712 const char *
4713 GetConfigOption(const char *name)
4714 {
4715         struct config_generic *record;
4716         static char buffer[256];
4717
4718         record = find_option(name, false, ERROR);
4719         if (record == NULL)
4720                 ereport(ERROR,
4721                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
4722                            errmsg("unrecognized configuration parameter \"%s\"", name)));
4723         if ((record->flags & GUC_SUPERUSER_ONLY) && !superuser())
4724                 ereport(ERROR,
4725                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
4726                                  errmsg("must be superuser to examine \"%s\"", name)));
4727
4728         switch (record->vartype)
4729         {
4730                 case PGC_BOOL:
4731                         return *((struct config_bool *) record)->variable ? "on" : "off";
4732
4733                 case PGC_INT:
4734                         snprintf(buffer, sizeof(buffer), "%d",
4735                                          *((struct config_int *) record)->variable);
4736                         return buffer;
4737
4738                 case PGC_REAL:
4739                         snprintf(buffer, sizeof(buffer), "%g",
4740                                          *((struct config_real *) record)->variable);
4741                         return buffer;
4742
4743                 case PGC_STRING:
4744                         return *((struct config_string *) record)->variable;
4745         }
4746         return NULL;
4747 }
4748
4749 /*
4750  * Get the RESET value associated with the given option.
4751  *
4752  * Note: this is not re-entrant, due to use of static result buffer;
4753  * not to mention that a string variable could have its reset_val changed.
4754  * Beware of assuming the result value is good for very long.
4755  */
4756 const char *
4757 GetConfigOptionResetString(const char *name)
4758 {
4759         struct config_generic *record;
4760         static char buffer[256];
4761
4762         record = find_option(name, false, ERROR);
4763         if (record == NULL)
4764                 ereport(ERROR,
4765                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
4766                            errmsg("unrecognized configuration parameter \"%s\"", name)));
4767         if ((record->flags & GUC_SUPERUSER_ONLY) && !superuser())
4768                 ereport(ERROR,
4769                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
4770                                  errmsg("must be superuser to examine \"%s\"", name)));
4771
4772         switch (record->vartype)
4773         {
4774                 case PGC_BOOL:
4775                         return ((struct config_bool *) record)->reset_val ? "on" : "off";
4776
4777                 case PGC_INT:
4778                         snprintf(buffer, sizeof(buffer), "%d",
4779                                          ((struct config_int *) record)->reset_val);
4780                         return buffer;
4781
4782                 case PGC_REAL:
4783                         snprintf(buffer, sizeof(buffer), "%g",
4784                                          ((struct config_real *) record)->reset_val);
4785                         return buffer;
4786
4787                 case PGC_STRING:
4788                         return ((struct config_string *) record)->reset_val;
4789         }
4790         return NULL;
4791 }
4792
4793 /*
4794  * Detect whether the given configuration option can only be set by
4795  * a superuser.
4796  */
4797 bool
4798 IsSuperuserConfigOption(const char *name)
4799 {
4800         struct config_generic *record;
4801
4802         record = find_option(name, false, ERROR);
4803         /* On an unrecognized name, don't error, just return false. */
4804         if (record == NULL)
4805                 return false;
4806         return (record->context == PGC_SUSET);
4807 }
4808
4809
4810 /*
4811  * GUC_complaint_elevel
4812  *              Get the ereport error level to use in an assign_hook's error report.
4813  *
4814  * This should be used by assign hooks that want to emit a custom error
4815  * report (in addition to the generic "invalid value for option FOO" that
4816  * guc.c will provide).  Note that the result might be ERROR or a lower
4817  * level, so the caller must be prepared for control to return from ereport,
4818  * or not.  If control does return, return false/NULL from the hook function.
4819  *
4820  * At some point it'd be nice to replace this with a mechanism that allows
4821  * the custom message to become the DETAIL line of guc.c's generic message.
4822  */
4823 int
4824 GUC_complaint_elevel(GucSource source)
4825 {
4826         int                     elevel;
4827
4828         if (source == PGC_S_FILE)
4829         {
4830                 /*
4831                  * To avoid cluttering the log, only the postmaster bleats loudly
4832                  * about problems with the config file.
4833                  */
4834                 elevel = IsUnderPostmaster ? DEBUG3 : LOG;
4835         }
4836         else if (source == PGC_S_OVERRIDE)
4837         {
4838                 /*
4839                  * If we're a postmaster child, this is probably "undo" during
4840                  * transaction abort, so we don't want to clutter the log.  There's
4841                  * a small chance of a real problem with an OVERRIDE setting,
4842                  * though, so suppressing the message entirely wouldn't be desirable.
4843                  */
4844                 elevel = IsUnderPostmaster ? DEBUG5 : LOG;
4845         }
4846         else if (source < PGC_S_INTERACTIVE)
4847                 elevel = LOG;
4848         else
4849                 elevel = ERROR;
4850
4851         return elevel;
4852 }
4853
4854
4855 /*
4856  * flatten_set_variable_args
4857  *              Given a parsenode List as emitted by the grammar for SET,
4858  *              convert to the flat string representation used by GUC.
4859  *
4860  * We need to be told the name of the variable the args are for, because
4861  * the flattening rules vary (ugh).
4862  *
4863  * The result is NULL if args is NIL (ie, SET ... TO DEFAULT), otherwise
4864  * a palloc'd string.
4865  */
4866 static char *
4867 flatten_set_variable_args(const char *name, List *args)
4868 {
4869         struct config_generic *record;
4870         int                     flags;
4871         StringInfoData buf;
4872         ListCell   *l;
4873
4874         /* Fast path if just DEFAULT */
4875         if (args == NIL)
4876                 return NULL;
4877
4878         /* Else get flags for the variable */
4879         record = find_option(name, true, ERROR);
4880         if (record == NULL)
4881                 ereport(ERROR,
4882                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
4883                            errmsg("unrecognized configuration parameter \"%s\"", name)));
4884
4885         flags = record->flags;
4886
4887         /* Complain if list input and non-list variable */
4888         if ((flags & GUC_LIST_INPUT) == 0 &&
4889                 list_length(args) != 1)
4890                 ereport(ERROR,
4891                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4892                                  errmsg("SET %s takes only one argument", name)));
4893
4894         initStringInfo(&buf);
4895
4896         foreach(l, args)
4897         {
4898                 A_Const    *arg = (A_Const *) lfirst(l);
4899                 char       *val;
4900
4901                 if (l != list_head(args))
4902                         appendStringInfo(&buf, ", ");
4903
4904                 if (!IsA(arg, A_Const))
4905                         elog(ERROR, "unrecognized node type: %d", (int) nodeTag(arg));
4906
4907                 switch (nodeTag(&arg->val))
4908                 {
4909                         case T_Integer:
4910                                 appendStringInfo(&buf, "%ld", intVal(&arg->val));
4911                                 break;
4912                         case T_Float:
4913                                 /* represented as a string, so just copy it */
4914                                 appendStringInfoString(&buf, strVal(&arg->val));
4915                                 break;
4916                         case T_String:
4917                                 val = strVal(&arg->val);
4918                                 if (arg->typename != NULL)
4919                                 {
4920                                         /*
4921                                          * Must be a ConstInterval argument for TIME ZONE. Coerce
4922                                          * to interval and back to normalize the value and account
4923                                          * for any typmod.
4924                                          */
4925                                         Oid                     typoid;
4926                                         int32           typmod;
4927                                         Datum           interval;
4928                                         char       *intervalout;
4929
4930                                         typoid = typenameTypeId(NULL, arg->typename, &typmod);
4931                                         Assert(typoid == INTERVALOID);
4932
4933                                         interval =
4934                                                 DirectFunctionCall3(interval_in,
4935                                                                                         CStringGetDatum(val),
4936                                                                                         ObjectIdGetDatum(InvalidOid),
4937                                                                                         Int32GetDatum(typmod));
4938
4939                                         intervalout =
4940                                                 DatumGetCString(DirectFunctionCall1(interval_out,
4941                                                                                                                         interval));
4942                                         appendStringInfo(&buf, "INTERVAL '%s'", intervalout);
4943                                 }
4944                                 else
4945                                 {
4946                                         /*
4947                                          * Plain string literal or identifier.  For quote mode,
4948                                          * quote it if it's not a vanilla identifier.
4949                                          */
4950                                         if (flags & GUC_LIST_QUOTE)
4951                                                 appendStringInfoString(&buf, quote_identifier(val));
4952                                         else
4953                                                 appendStringInfoString(&buf, val);
4954                                 }
4955                                 break;
4956                         default:
4957                                 elog(ERROR, "unrecognized node type: %d",
4958                                          (int) nodeTag(&arg->val));
4959                                 break;
4960                 }
4961         }
4962
4963         return buf.data;
4964 }
4965
4966
4967 /*
4968  * SET command
4969  */
4970 void
4971 ExecSetVariableStmt(VariableSetStmt *stmt)
4972 {
4973         GucAction       action = stmt->is_local ? GUC_ACTION_LOCAL : GUC_ACTION_SET;
4974
4975         switch (stmt->kind)
4976         {
4977                 case VAR_SET_VALUE:
4978                 case VAR_SET_CURRENT:
4979                         set_config_option(stmt->name,
4980                                                           ExtractSetVariableArgs(stmt),
4981                                                           (superuser() ? PGC_SUSET : PGC_USERSET),
4982                                                           PGC_S_SESSION,
4983                                                           action,
4984                                                           true);
4985                         break;
4986                 case VAR_SET_MULTI:
4987
4988                         /*
4989                          * Special case for special SQL syntax that effectively sets more
4990                          * than one variable per statement.
4991                          */
4992                         if (strcmp(stmt->name, "TRANSACTION") == 0)
4993                         {
4994                                 ListCell   *head;
4995
4996                                 foreach(head, stmt->args)
4997                                 {
4998                                         DefElem    *item = (DefElem *) lfirst(head);
4999
5000                                         if (strcmp(item->defname, "transaction_isolation") == 0)
5001                                                 SetPGVariable("transaction_isolation",
5002                                                                           list_make1(item->arg), stmt->is_local);
5003                                         else if (strcmp(item->defname, "transaction_read_only") == 0)
5004                                                 SetPGVariable("transaction_read_only",
5005                                                                           list_make1(item->arg), stmt->is_local);
5006                                         else
5007                                                 elog(ERROR, "unexpected SET TRANSACTION element: %s",
5008                                                          item->defname);
5009                                 }
5010                         }
5011                         else if (strcmp(stmt->name, "SESSION CHARACTERISTICS") == 0)
5012                         {
5013                                 ListCell   *head;
5014
5015                                 foreach(head, stmt->args)
5016                                 {
5017                                         DefElem    *item = (DefElem *) lfirst(head);
5018
5019                                         if (strcmp(item->defname, "transaction_isolation") == 0)
5020                                                 SetPGVariable("default_transaction_isolation",
5021                                                                           list_make1(item->arg), stmt->is_local);
5022                                         else if (strcmp(item->defname, "transaction_read_only") == 0)
5023                                                 SetPGVariable("default_transaction_read_only",
5024                                                                           list_make1(item->arg), stmt->is_local);
5025                                         else
5026                                                 elog(ERROR, "unexpected SET SESSION element: %s",
5027                                                          item->defname);
5028                                 }
5029                         }
5030                         else
5031                                 elog(ERROR, "unexpected SET MULTI element: %s",
5032                                          stmt->name);
5033                         break;
5034                 case VAR_SET_DEFAULT:
5035                 case VAR_RESET:
5036                         set_config_option(stmt->name,
5037                                                           NULL,
5038                                                           (superuser() ? PGC_SUSET : PGC_USERSET),
5039                                                           PGC_S_SESSION,
5040                                                           action,
5041                                                           true);
5042                         break;
5043                 case VAR_RESET_ALL:
5044                         ResetAllOptions();
5045                         break;
5046         }
5047 }
5048
5049 /*
5050  * Get the value to assign for a VariableSetStmt, or NULL if it's RESET.
5051  * The result is palloc'd.
5052  *
5053  * This is exported for use by actions such as ALTER ROLE SET.
5054  */
5055 char *
5056 ExtractSetVariableArgs(VariableSetStmt *stmt)
5057 {
5058         switch (stmt->kind)
5059         {
5060                 case VAR_SET_VALUE:
5061                         return flatten_set_variable_args(stmt->name, stmt->args);
5062                 case VAR_SET_CURRENT:
5063                         return GetConfigOptionByName(stmt->name, NULL);
5064                 default:
5065                         return NULL;
5066         }
5067 }
5068
5069 /*
5070  * SetPGVariable - SET command exported as an easily-C-callable function.
5071  *
5072  * This provides access to SET TO value, as well as SET TO DEFAULT (expressed
5073  * by passing args == NIL), but not SET FROM CURRENT functionality.
5074  */
5075 void
5076 SetPGVariable(const char *name, List *args, bool is_local)
5077 {
5078         char       *argstring = flatten_set_variable_args(name, args);
5079
5080         /* Note SET DEFAULT (argstring == NULL) is equivalent to RESET */
5081         set_config_option(name,
5082                                           argstring,
5083                                           (superuser() ? PGC_SUSET : PGC_USERSET),
5084                                           PGC_S_SESSION,
5085                                           is_local ? GUC_ACTION_LOCAL : GUC_ACTION_SET,
5086                                           true);
5087 }
5088
5089 /*
5090  * SET command wrapped as a SQL callable function.
5091  */
5092 Datum
5093 set_config_by_name(PG_FUNCTION_ARGS)
5094 {
5095         char       *name;
5096         char       *value;
5097         char       *new_value;
5098         bool            is_local;
5099         text       *result_text;
5100
5101         if (PG_ARGISNULL(0))
5102                 ereport(ERROR,
5103                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5104                                  errmsg("SET requires parameter name")));
5105
5106         /* Get the GUC variable name */
5107         name = DatumGetCString(DirectFunctionCall1(textout, PG_GETARG_DATUM(0)));
5108
5109         /* Get the desired value or set to NULL for a reset request */
5110         if (PG_ARGISNULL(1))
5111                 value = NULL;
5112         else
5113                 value = DatumGetCString(DirectFunctionCall1(textout, PG_GETARG_DATUM(1)));
5114
5115         /*
5116          * Get the desired state of is_local. Default to false if provided value
5117          * is NULL
5118          */
5119         if (PG_ARGISNULL(2))
5120                 is_local = false;
5121         else
5122                 is_local = PG_GETARG_BOOL(2);
5123
5124         /* Note SET DEFAULT (argstring == NULL) is equivalent to RESET */
5125         set_config_option(name,
5126                                           value,
5127                                           (superuser() ? PGC_SUSET : PGC_USERSET),
5128                                           PGC_S_SESSION,
5129                                           is_local ? GUC_ACTION_LOCAL : GUC_ACTION_SET,
5130                                           true);
5131
5132         /* get the new current value */
5133         new_value = GetConfigOptionByName(name, NULL);
5134
5135         /* Convert return string to text */
5136         result_text = DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum(new_value)));
5137
5138         /* return it */
5139         PG_RETURN_TEXT_P(result_text);
5140 }
5141
5142
5143 /*
5144  * Common code for DefineCustomXXXVariable subroutines: allocate the
5145  * new variable's config struct and fill in generic fields.
5146  */
5147 static struct config_generic *
5148 init_custom_variable(const char *name,
5149                                          const char *short_desc,
5150                                          const char *long_desc,
5151                                          GucContext context,
5152                                          enum config_type type,
5153                                          size_t sz)
5154 {
5155         struct config_generic *gen;
5156
5157         gen = (struct config_generic *) guc_malloc(ERROR, sz);
5158         memset(gen, 0, sz);
5159
5160         gen->name = guc_strdup(ERROR, name);
5161         gen->context = context;
5162         gen->group = CUSTOM_OPTIONS;
5163         gen->short_desc = short_desc;
5164         gen->long_desc = long_desc;
5165         gen->vartype = type;
5166
5167         return gen;
5168 }
5169
5170 /*
5171  * Common code for DefineCustomXXXVariable subroutines: insert the new
5172  * variable into the GUC variable array, replacing any placeholder.
5173  */
5174 static void
5175 define_custom_variable(struct config_generic * variable)
5176 {
5177         const char *name = variable->name;
5178         const char **nameAddr = &name;
5179         const char *value;
5180         struct config_string *pHolder;
5181         struct config_generic **res;
5182
5183         res = (struct config_generic **) bsearch((void *) &nameAddr,
5184                                                                                          (void *) guc_variables,
5185                                                                                          num_guc_variables,
5186                                                                                          sizeof(struct config_generic *),
5187                                                                                          guc_var_compare);
5188         if (res == NULL)
5189         {
5190                 /* No placeholder to replace, so just add it */
5191                 add_guc_variable(variable, ERROR);
5192                 return;
5193         }
5194
5195         /*
5196          * This better be a placeholder
5197          */
5198         if (((*res)->flags & GUC_CUSTOM_PLACEHOLDER) == 0)
5199                 ereport(ERROR,
5200                                 (errcode(ERRCODE_INTERNAL_ERROR),
5201                                  errmsg("attempt to redefine parameter \"%s\"", name)));
5202
5203         Assert((*res)->vartype == PGC_STRING);
5204         pHolder = (struct config_string *) (*res);
5205
5206         /*
5207          * Replace the placeholder. We aren't changing the name, so no re-sorting
5208          * is necessary
5209          */
5210         *res = variable;
5211
5212         /*
5213          * Assign the string value stored in the placeholder to the real variable.
5214          *
5215          * XXX this is not really good enough --- it should be a nontransactional
5216          * assignment, since we don't want it to roll back if the current xact
5217          * fails later.
5218          */
5219         value = *pHolder->variable;
5220
5221         if (value)
5222                 set_config_option(name, value,
5223                                                   pHolder->gen.context, pHolder->gen.source,
5224                                                   GUC_ACTION_SET, true);
5225
5226         /*
5227          * Free up as much as we conveniently can of the placeholder structure
5228          * (this neglects any stack items...)
5229          */
5230         set_string_field(pHolder, pHolder->variable, NULL);
5231         set_string_field(pHolder, &pHolder->reset_val, NULL);
5232
5233         free(pHolder);
5234 }
5235
5236 void
5237 DefineCustomBoolVariable(const char *name,
5238                                                  const char *short_desc,
5239                                                  const char *long_desc,
5240                                                  bool *valueAddr,
5241                                                  GucContext context,
5242                                                  GucBoolAssignHook assign_hook,
5243                                                  GucShowHook show_hook)
5244 {
5245         struct config_bool *var;
5246
5247         var = (struct config_bool *)
5248                 init_custom_variable(name, short_desc, long_desc, context,
5249                                                          PGC_BOOL, sizeof(struct config_bool));
5250         var->variable = valueAddr;
5251         var->boot_val = *valueAddr;
5252         var->reset_val = *valueAddr;
5253         var->assign_hook = assign_hook;
5254         var->show_hook = show_hook;
5255         define_custom_variable(&var->gen);
5256 }
5257
5258 void
5259 DefineCustomIntVariable(const char *name,
5260                                                 const char *short_desc,
5261                                                 const char *long_desc,
5262                                                 int *valueAddr,
5263                                                 int minValue,
5264                                                 int maxValue,
5265                                                 GucContext context,
5266                                                 GucIntAssignHook assign_hook,
5267                                                 GucShowHook show_hook)
5268 {
5269         struct config_int *var;
5270
5271         var = (struct config_int *)
5272                 init_custom_variable(name, short_desc, long_desc, context,
5273                                                          PGC_INT, sizeof(struct config_int));
5274         var->variable = valueAddr;
5275         var->boot_val = *valueAddr;
5276         var->reset_val = *valueAddr;
5277         var->min = minValue;
5278         var->max = maxValue;
5279         var->assign_hook = assign_hook;
5280         var->show_hook = show_hook;
5281         define_custom_variable(&var->gen);
5282 }
5283
5284 void
5285 DefineCustomRealVariable(const char *name,
5286                                                  const char *short_desc,
5287                                                  const char *long_desc,
5288                                                  double *valueAddr,
5289                                                  double minValue,
5290                                                  double maxValue,
5291                                                  GucContext context,
5292                                                  GucRealAssignHook assign_hook,
5293                                                  GucShowHook show_hook)
5294 {
5295         struct config_real *var;
5296
5297         var = (struct config_real *)
5298                 init_custom_variable(name, short_desc, long_desc, context,
5299                                                          PGC_REAL, sizeof(struct config_real));
5300         var->variable = valueAddr;
5301         var->boot_val = *valueAddr;
5302         var->reset_val = *valueAddr;
5303         var->min = minValue;
5304         var->max = maxValue;
5305         var->assign_hook = assign_hook;
5306         var->show_hook = show_hook;
5307         define_custom_variable(&var->gen);
5308 }
5309
5310 void
5311 DefineCustomStringVariable(const char *name,
5312                                                    const char *short_desc,
5313                                                    const char *long_desc,
5314                                                    char **valueAddr,
5315                                                    GucContext context,
5316                                                    GucStringAssignHook assign_hook,
5317                                                    GucShowHook show_hook)
5318 {
5319         struct config_string *var;
5320
5321         var = (struct config_string *)
5322                 init_custom_variable(name, short_desc, long_desc, context,
5323                                                          PGC_STRING, sizeof(struct config_string));
5324         var->variable = valueAddr;
5325         var->boot_val = *valueAddr;
5326         /* we could probably do without strdup, but keep it like normal case */
5327         if (var->boot_val)
5328                 var->reset_val = guc_strdup(ERROR, var->boot_val);
5329         var->assign_hook = assign_hook;
5330         var->show_hook = show_hook;
5331         define_custom_variable(&var->gen);
5332 }
5333
5334 void
5335 EmitWarningsOnPlaceholders(const char *className)
5336 {
5337         struct config_generic **vars = guc_variables;
5338         struct config_generic **last = vars + num_guc_variables;
5339
5340         int                     nameLen = strlen(className);
5341
5342         while (vars < last)
5343         {
5344                 struct config_generic *var = *vars++;
5345
5346                 if ((var->flags & GUC_CUSTOM_PLACEHOLDER) != 0 &&
5347                         strncmp(className, var->name, nameLen) == 0 &&
5348                         var->name[nameLen] == GUC_QUALIFIER_SEPARATOR)
5349                 {
5350                         ereport(INFO,
5351                                         (errcode(ERRCODE_UNDEFINED_OBJECT),
5352                                          errmsg("unrecognized configuration parameter \"%s\"", var->name)));
5353                 }
5354         }
5355 }
5356
5357
5358 /*
5359  * SHOW command
5360  */
5361 void
5362 GetPGVariable(const char *name, DestReceiver *dest)
5363 {
5364         if (guc_name_compare(name, "all") == 0)
5365                 ShowAllGUCConfig(dest);
5366         else
5367                 ShowGUCConfigOption(name, dest);
5368 }
5369
5370 TupleDesc
5371 GetPGVariableResultDesc(const char *name)
5372 {
5373         TupleDesc       tupdesc;
5374
5375         if (guc_name_compare(name, "all") == 0)
5376         {
5377                 /* need a tuple descriptor representing three TEXT columns */
5378                 tupdesc = CreateTemplateTupleDesc(3, false);
5379                 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
5380                                                    TEXTOID, -1, 0);
5381                 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "setting",
5382                                                    TEXTOID, -1, 0);
5383                 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "description",
5384                                                    TEXTOID, -1, 0);
5385
5386         }
5387         else
5388         {
5389                 const char *varname;
5390
5391                 /* Get the canonical spelling of name */
5392                 (void) GetConfigOptionByName(name, &varname);
5393
5394                 /* need a tuple descriptor representing a single TEXT column */
5395                 tupdesc = CreateTemplateTupleDesc(1, false);
5396                 TupleDescInitEntry(tupdesc, (AttrNumber) 1, varname,
5397                                                    TEXTOID, -1, 0);
5398         }
5399         return tupdesc;
5400 }
5401
5402
5403 /*
5404  * SHOW command
5405  */
5406 static void
5407 ShowGUCConfigOption(const char *name, DestReceiver *dest)
5408 {
5409         TupOutputState *tstate;
5410         TupleDesc       tupdesc;
5411         const char *varname;
5412         char       *value;
5413
5414         /* Get the value and canonical spelling of name */
5415         value = GetConfigOptionByName(name, &varname);
5416
5417         /* need a tuple descriptor representing a single TEXT column */
5418         tupdesc = CreateTemplateTupleDesc(1, false);
5419         TupleDescInitEntry(tupdesc, (AttrNumber) 1, varname,
5420                                            TEXTOID, -1, 0);
5421
5422         /* prepare for projection of tuples */
5423         tstate = begin_tup_output_tupdesc(dest, tupdesc);
5424
5425         /* Send it */
5426         do_text_output_oneline(tstate, value);
5427
5428         end_tup_output(tstate);
5429 }
5430
5431 /*
5432  * SHOW ALL command
5433  */
5434 static void
5435 ShowAllGUCConfig(DestReceiver *dest)
5436 {
5437         bool            am_superuser = superuser();
5438         int                     i;
5439         TupOutputState *tstate;
5440         TupleDesc       tupdesc;
5441         char       *values[3];
5442
5443         /* need a tuple descriptor representing three TEXT columns */
5444         tupdesc = CreateTemplateTupleDesc(3, false);
5445         TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
5446                                            TEXTOID, -1, 0);
5447         TupleDescInitEntry(tupdesc, (AttrNumber) 2, "setting",
5448                                            TEXTOID, -1, 0);
5449         TupleDescInitEntry(tupdesc, (AttrNumber) 3, "description",
5450                                            TEXTOID, -1, 0);
5451
5452
5453         /* prepare for projection of tuples */
5454         tstate = begin_tup_output_tupdesc(dest, tupdesc);
5455
5456         for (i = 0; i < num_guc_variables; i++)
5457         {
5458                 struct config_generic *conf = guc_variables[i];
5459
5460                 if ((conf->flags & GUC_NO_SHOW_ALL) ||
5461                         ((conf->flags & GUC_SUPERUSER_ONLY) && !am_superuser))
5462                         continue;
5463
5464                 /* assign to the values array */
5465                 values[0] = (char *) conf->name;
5466                 values[1] = _ShowOption(conf, true);
5467                 values[2] = (char *) conf->short_desc;
5468
5469                 /* send it to dest */
5470                 do_tup_output(tstate, values);
5471
5472                 /* clean up */
5473                 if (values[1] != NULL)
5474                         pfree(values[1]);
5475         }
5476
5477         end_tup_output(tstate);
5478 }
5479
5480 /*
5481  * Return GUC variable value by name; optionally return canonical
5482  * form of name.  Return value is palloc'd.
5483  */
5484 char *
5485 GetConfigOptionByName(const char *name, const char **varname)
5486 {
5487         struct config_generic *record;
5488
5489         record = find_option(name, false, ERROR);
5490         if (record == NULL)
5491                 ereport(ERROR,
5492                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
5493                            errmsg("unrecognized configuration parameter \"%s\"", name)));
5494         if ((record->flags & GUC_SUPERUSER_ONLY) && !superuser())
5495                 ereport(ERROR,
5496                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
5497                                  errmsg("must be superuser to examine \"%s\"", name)));
5498
5499         if (varname)
5500                 *varname = record->name;
5501
5502         return _ShowOption(record, true);
5503 }
5504
5505 /*
5506  * Return GUC variable value by variable number; optionally return canonical
5507  * form of name.  Return value is palloc'd.
5508  */
5509 void
5510 GetConfigOptionByNum(int varnum, const char **values, bool *noshow)
5511 {
5512         char            buffer[256];
5513         struct config_generic *conf;
5514
5515         /* check requested variable number valid */
5516         Assert((varnum >= 0) && (varnum < num_guc_variables));
5517
5518         conf = guc_variables[varnum];
5519
5520         if (noshow)
5521         {
5522                 if ((conf->flags & GUC_NO_SHOW_ALL) ||
5523                         ((conf->flags & GUC_SUPERUSER_ONLY) && !superuser()))
5524                         *noshow = true;
5525                 else
5526                         *noshow = false;
5527         }
5528
5529         /* first get the generic attributes */
5530
5531         /* name */
5532         values[0] = conf->name;
5533
5534         /* setting : use _ShowOption in order to avoid duplicating the logic */
5535         values[1] = _ShowOption(conf, false);
5536
5537         /* unit */
5538         if (conf->vartype == PGC_INT)
5539         {
5540                 static char buf[8];
5541
5542                 switch (conf->flags & (GUC_UNIT_MEMORY | GUC_UNIT_TIME))
5543                 {
5544                         case GUC_UNIT_KB:
5545                                 values[2] = "kB";
5546                                 break;
5547                         case GUC_UNIT_BLOCKS:
5548                                 snprintf(buf, sizeof(buf), "%dkB", BLCKSZ / 1024);
5549                                 values[2] = buf;
5550                                 break;
5551                         case GUC_UNIT_XBLOCKS:
5552                                 snprintf(buf, sizeof(buf), "%dkB", XLOG_BLCKSZ / 1024);
5553                                 values[2] = buf;
5554                                 break;
5555                         case GUC_UNIT_MS:
5556                                 values[2] = "ms";
5557                                 break;
5558                         case GUC_UNIT_S:
5559                                 values[2] = "s";
5560                                 break;
5561                         case GUC_UNIT_MIN:
5562                                 values[2] = "min";
5563                                 break;
5564                         default:
5565                                 values[2] = "";
5566                                 break;
5567                 }
5568         }
5569         else
5570                 values[2] = NULL;
5571
5572         /* group */
5573         values[3] = config_group_names[conf->group];
5574
5575         /* short_desc */
5576         values[4] = conf->short_desc;
5577
5578         /* extra_desc */
5579         values[5] = conf->long_desc;
5580
5581         /* context */
5582         values[6] = GucContext_Names[conf->context];
5583
5584         /* vartype */
5585         values[7] = config_type_names[conf->vartype];
5586
5587         /* source */
5588         values[8] = GucSource_Names[conf->source];
5589
5590         /* now get the type specifc attributes */
5591         switch (conf->vartype)
5592         {
5593                 case PGC_BOOL:
5594                         {
5595                                 /* min_val */
5596                                 values[9] = NULL;
5597
5598                                 /* max_val */
5599                                 values[10] = NULL;
5600                         }
5601                         break;
5602
5603                 case PGC_INT:
5604                         {
5605                                 struct config_int *lconf = (struct config_int *) conf;
5606
5607                                 /* min_val */
5608                                 snprintf(buffer, sizeof(buffer), "%d", lconf->min);
5609                                 values[9] = pstrdup(buffer);
5610
5611                                 /* max_val */
5612                                 snprintf(buffer, sizeof(buffer), "%d", lconf->max);
5613                                 values[10] = pstrdup(buffer);
5614                         }
5615                         break;
5616
5617                 case PGC_REAL:
5618                         {
5619                                 struct config_real *lconf = (struct config_real *) conf;
5620
5621                                 /* min_val */
5622                                 snprintf(buffer, sizeof(buffer), "%g", lconf->min);
5623                                 values[9] = pstrdup(buffer);
5624
5625                                 /* max_val */
5626                                 snprintf(buffer, sizeof(buffer), "%g", lconf->max);
5627                                 values[10] = pstrdup(buffer);
5628                         }
5629                         break;
5630
5631                 case PGC_STRING:
5632                         {
5633                                 /* min_val */
5634                                 values[9] = NULL;
5635
5636                                 /* max_val */
5637                                 values[10] = NULL;
5638                         }
5639                         break;
5640
5641                 default:
5642                         {
5643                                 /*
5644                                  * should never get here, but in case we do, set 'em to NULL
5645                                  */
5646
5647                                 /* min_val */
5648                                 values[9] = NULL;
5649
5650                                 /* max_val */
5651                                 values[10] = NULL;
5652                         }
5653                         break;
5654         }
5655 }
5656
5657 /*
5658  * Return the total number of GUC variables
5659  */
5660 int
5661 GetNumConfigOptions(void)
5662 {
5663         return num_guc_variables;
5664 }
5665
5666 /*
5667  * show_config_by_name - equiv to SHOW X command but implemented as
5668  * a function.
5669  */
5670 Datum
5671 show_config_by_name(PG_FUNCTION_ARGS)
5672 {
5673         char       *varname;
5674         char       *varval;
5675         text       *result_text;
5676
5677         /* Get the GUC variable name */
5678         varname = DatumGetCString(DirectFunctionCall1(textout, PG_GETARG_DATUM(0)));
5679
5680         /* Get the value */
5681         varval = GetConfigOptionByName(varname, NULL);
5682
5683         /* Convert to text */
5684         result_text = DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum(varval)));
5685
5686         /* return it */
5687         PG_RETURN_TEXT_P(result_text);
5688 }
5689
5690 /*
5691  * show_all_settings - equiv to SHOW ALL command but implemented as
5692  * a Table Function.
5693  */
5694 #define NUM_PG_SETTINGS_ATTS    11
5695
5696 Datum
5697 show_all_settings(PG_FUNCTION_ARGS)
5698 {
5699         FuncCallContext *funcctx;
5700         TupleDesc       tupdesc;
5701         int                     call_cntr;
5702         int                     max_calls;
5703         AttInMetadata *attinmeta;
5704         MemoryContext oldcontext;
5705
5706         /* stuff done only on the first call of the function */
5707         if (SRF_IS_FIRSTCALL())
5708         {
5709                 /* create a function context for cross-call persistence */
5710                 funcctx = SRF_FIRSTCALL_INIT();
5711
5712                 /*
5713                  * switch to memory context appropriate for multiple function calls
5714                  */
5715                 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
5716
5717                 /*
5718                  * need a tuple descriptor representing NUM_PG_SETTINGS_ATTS columns
5719                  * of the appropriate types
5720                  */
5721                 tupdesc = CreateTemplateTupleDesc(NUM_PG_SETTINGS_ATTS, false);
5722                 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
5723                                                    TEXTOID, -1, 0);
5724                 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "setting",
5725                                                    TEXTOID, -1, 0);
5726                 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "unit",
5727                                                    TEXTOID, -1, 0);
5728                 TupleDescInitEntry(tupdesc, (AttrNumber) 4, "category",
5729                                                    TEXTOID, -1, 0);
5730                 TupleDescInitEntry(tupdesc, (AttrNumber) 5, "short_desc",
5731                                                    TEXTOID, -1, 0);
5732                 TupleDescInitEntry(tupdesc, (AttrNumber) 6, "extra_desc",
5733                                                    TEXTOID, -1, 0);
5734                 TupleDescInitEntry(tupdesc, (AttrNumber) 7, "context",
5735                                                    TEXTOID, -1, 0);
5736                 TupleDescInitEntry(tupdesc, (AttrNumber) 8, "vartype",
5737                                                    TEXTOID, -1, 0);
5738                 TupleDescInitEntry(tupdesc, (AttrNumber) 9, "source",
5739                                                    TEXTOID, -1, 0);
5740                 TupleDescInitEntry(tupdesc, (AttrNumber) 10, "min_val",
5741                                                    TEXTOID, -1, 0);
5742                 TupleDescInitEntry(tupdesc, (AttrNumber) 11, "max_val",
5743                                                    TEXTOID, -1, 0);
5744
5745                 /*
5746                  * Generate attribute metadata needed later to produce tuples from raw
5747                  * C strings
5748                  */
5749                 attinmeta = TupleDescGetAttInMetadata(tupdesc);
5750                 funcctx->attinmeta = attinmeta;
5751
5752                 /* total number of tuples to be returned */
5753                 funcctx->max_calls = GetNumConfigOptions();
5754
5755                 MemoryContextSwitchTo(oldcontext);
5756         }
5757
5758         /* stuff done on every call of the function */
5759         funcctx = SRF_PERCALL_SETUP();
5760
5761         call_cntr = funcctx->call_cntr;
5762         max_calls = funcctx->max_calls;
5763         attinmeta = funcctx->attinmeta;
5764
5765         if (call_cntr < max_calls)      /* do when there is more left to send */
5766         {
5767                 char       *values[NUM_PG_SETTINGS_ATTS];
5768                 bool            noshow;
5769                 HeapTuple       tuple;
5770                 Datum           result;
5771
5772                 /*
5773                  * Get the next visible GUC variable name and value
5774                  */
5775                 do
5776                 {
5777                         GetConfigOptionByNum(call_cntr, (const char **) values, &noshow);
5778                         if (noshow)
5779                         {
5780                                 /* bump the counter and get the next config setting */
5781                                 call_cntr = ++funcctx->call_cntr;
5782
5783                                 /* make sure we haven't gone too far now */
5784                                 if (call_cntr >= max_calls)
5785                                         SRF_RETURN_DONE(funcctx);
5786                         }
5787                 } while (noshow);
5788
5789                 /* build a tuple */
5790                 tuple = BuildTupleFromCStrings(attinmeta, values);
5791
5792                 /* make the tuple into a datum */
5793                 result = HeapTupleGetDatum(tuple);
5794
5795                 SRF_RETURN_NEXT(funcctx, result);
5796         }
5797         else
5798         {
5799                 /* do when there is no more left */
5800                 SRF_RETURN_DONE(funcctx);
5801         }
5802 }
5803
5804 static char *
5805 _ShowOption(struct config_generic * record, bool use_units)
5806 {
5807         char            buffer[256];
5808         const char *val;
5809
5810         switch (record->vartype)
5811         {
5812                 case PGC_BOOL:
5813                         {
5814                                 struct config_bool *conf = (struct config_bool *) record;
5815
5816                                 if (conf->show_hook)
5817                                         val = (*conf->show_hook) ();
5818                                 else
5819                                         val = *conf->variable ? "on" : "off";
5820                         }
5821                         break;
5822
5823                 case PGC_INT:
5824                         {
5825                                 struct config_int *conf = (struct config_int *) record;
5826
5827                                 if (conf->show_hook)
5828                                         val = (*conf->show_hook) ();
5829                                 else
5830                                 {
5831                                         char            unit[4];
5832                                         int                     result = *conf->variable;
5833
5834                                         if (use_units && result > 0 && (record->flags & GUC_UNIT_MEMORY))
5835                                         {
5836                                                 switch (record->flags & GUC_UNIT_MEMORY)
5837                                                 {
5838                                                         case GUC_UNIT_BLOCKS:
5839                                                                 result *= BLCKSZ / 1024;
5840                                                                 break;
5841                                                         case GUC_UNIT_XBLOCKS:
5842                                                                 result *= XLOG_BLCKSZ / 1024;
5843                                                                 break;
5844                                                 }
5845
5846                                                 if (result % KB_PER_GB == 0)
5847                                                 {
5848                                                         result /= KB_PER_GB;
5849                                                         strcpy(unit, "GB");
5850                                                 }
5851                                                 else if (result % KB_PER_MB == 0)
5852                                                 {
5853                                                         result /= KB_PER_MB;
5854                                                         strcpy(unit, "MB");
5855                                                 }
5856                                                 else
5857                                                 {
5858                                                         strcpy(unit, "kB");
5859                                                 }
5860                                         }
5861                                         else if (use_units && result > 0 && (record->flags & GUC_UNIT_TIME))
5862                                         {
5863                                                 switch (record->flags & GUC_UNIT_TIME)
5864                                                 {
5865                                                         case GUC_UNIT_S:
5866                                                                 result *= MS_PER_S;
5867                                                                 break;
5868                                                         case GUC_UNIT_MIN:
5869                                                                 result *= MS_PER_MIN;
5870                                                                 break;
5871                                                 }
5872
5873                                                 if (result % MS_PER_D == 0)
5874                                                 {
5875                                                         result /= MS_PER_D;
5876                                                         strcpy(unit, "d");
5877                                                 }
5878                                                 else if (result % MS_PER_H == 0)
5879                                                 {
5880                                                         result /= MS_PER_H;
5881                                                         strcpy(unit, "h");
5882                                                 }
5883                                                 else if (result % MS_PER_MIN == 0)
5884                                                 {
5885                                                         result /= MS_PER_MIN;
5886                                                         strcpy(unit, "min");
5887                                                 }
5888                                                 else if (result % MS_PER_S == 0)
5889                                                 {
5890                                                         result /= MS_PER_S;
5891                                                         strcpy(unit, "s");
5892                                                 }
5893                                                 else
5894                                                 {
5895                                                         strcpy(unit, "ms");
5896                                                 }
5897                                         }
5898                                         else
5899                                                 strcpy(unit, "");
5900
5901                                         snprintf(buffer, sizeof(buffer), "%d%s",
5902                                                          (int) result, unit);
5903                                         val = buffer;
5904                                 }
5905                         }
5906                         break;
5907
5908                 case PGC_REAL:
5909                         {
5910                                 struct config_real *conf = (struct config_real *) record;
5911
5912                                 if (conf->show_hook)
5913                                         val = (*conf->show_hook) ();
5914                                 else
5915                                 {
5916                                         snprintf(buffer, sizeof(buffer), "%g",
5917                                                          *conf->variable);
5918                                         val = buffer;
5919                                 }
5920                         }
5921                         break;
5922
5923                 case PGC_STRING:
5924                         {
5925                                 struct config_string *conf = (struct config_string *) record;
5926
5927                                 if (conf->show_hook)
5928                                         val = (*conf->show_hook) ();
5929                                 else if (*conf->variable && **conf->variable)
5930                                         val = *conf->variable;
5931                                 else
5932                                         val = "";
5933                         }
5934                         break;
5935
5936                 default:
5937                         /* just to keep compiler quiet */
5938                         val = "???";
5939                         break;
5940         }
5941
5942         return pstrdup(val);
5943 }
5944
5945
5946 /*
5947  * Attempt (badly) to detect if a proposed new GUC setting is the same
5948  * as the current value.
5949  *
5950  * XXX this does not really work because it doesn't account for the
5951  * effects of canonicalization of string values by assign_hooks.
5952  */
5953 static bool
5954 is_newvalue_equal(struct config_generic * record, const char *newvalue)
5955 {
5956         /* newvalue == NULL isn't supported */
5957         Assert(newvalue != NULL);
5958
5959         switch (record->vartype)
5960         {
5961                 case PGC_BOOL:
5962                         {
5963                                 struct config_bool *conf = (struct config_bool *) record;
5964                                 bool            newval;
5965
5966                                 return parse_bool(newvalue, &newval)
5967                                         && *conf->variable == newval;
5968                         }
5969                 case PGC_INT:
5970                         {
5971                                 struct config_int *conf = (struct config_int *) record;
5972                                 int                     newval;
5973
5974                                 return parse_int(newvalue, &newval, record->flags, NULL)
5975                                         && *conf->variable == newval;
5976                         }
5977                 case PGC_REAL:
5978                         {
5979                                 struct config_real *conf = (struct config_real *) record;
5980                                 double          newval;
5981
5982                                 return parse_real(newvalue, &newval)
5983                                         && *conf->variable == newval;
5984                         }
5985                 case PGC_STRING:
5986                         {
5987                                 struct config_string *conf = (struct config_string *) record;
5988
5989                                 return *conf->variable != NULL &&
5990                                         strcmp(*conf->variable, newvalue) == 0;
5991                         }
5992         }
5993
5994         return false;
5995 }
5996
5997
5998 #ifdef EXEC_BACKEND
5999
6000 /*
6001  *      This routine dumps out all non-default GUC options into a binary
6002  *      file that is read by all exec'ed backends.  The format is:
6003  *
6004  *              variable name, string, null terminated
6005  *              variable value, string, null terminated
6006  *              variable source, integer
6007  */
6008 void
6009 write_nondefault_variables(GucContext context)
6010 {
6011         int                     i;
6012         int                     elevel;
6013         FILE       *fp;
6014
6015         Assert(context == PGC_POSTMASTER || context == PGC_SIGHUP);
6016
6017         elevel = (context == PGC_SIGHUP) ? LOG : ERROR;
6018
6019         /*
6020          * Open file
6021          */
6022         fp = AllocateFile(CONFIG_EXEC_PARAMS_NEW, "w");
6023         if (!fp)
6024         {
6025                 ereport(elevel,
6026                                 (errcode_for_file_access(),
6027                                  errmsg("could not write to file \"%s\": %m",
6028                                                 CONFIG_EXEC_PARAMS_NEW)));
6029                 return;
6030         }
6031
6032         for (i = 0; i < num_guc_variables; i++)
6033         {
6034                 struct config_generic *gconf = guc_variables[i];
6035
6036                 if (gconf->source != PGC_S_DEFAULT)
6037                 {
6038                         fprintf(fp, "%s", gconf->name);
6039                         fputc(0, fp);
6040
6041                         switch (gconf->vartype)
6042                         {
6043                                 case PGC_BOOL:
6044                                         {
6045                                                 struct config_bool *conf = (struct config_bool *) gconf;
6046
6047                                                 if (*conf->variable == 0)
6048                                                         fprintf(fp, "false");
6049                                                 else
6050                                                         fprintf(fp, "true");
6051                                         }
6052                                         break;
6053
6054                                 case PGC_INT:
6055                                         {
6056                                                 struct config_int *conf = (struct config_int *) gconf;
6057
6058                                                 fprintf(fp, "%d", *conf->variable);
6059                                         }
6060                                         break;
6061
6062                                 case PGC_REAL:
6063                                         {
6064                                                 struct config_real *conf = (struct config_real *) gconf;
6065
6066                                                 /* Could lose precision here? */
6067                                                 fprintf(fp, "%f", *conf->variable);
6068                                         }
6069                                         break;
6070
6071                                 case PGC_STRING:
6072                                         {
6073                                                 struct config_string *conf = (struct config_string *) gconf;
6074
6075                                                 fprintf(fp, "%s", *conf->variable);
6076                                         }
6077                                         break;
6078                         }
6079
6080                         fputc(0, fp);
6081
6082                         fwrite(&gconf->source, sizeof(gconf->source), 1, fp);
6083                 }
6084         }
6085
6086         if (FreeFile(fp))
6087         {
6088                 ereport(elevel,
6089                                 (errcode_for_file_access(),
6090                                  errmsg("could not write to file \"%s\": %m",
6091                                                 CONFIG_EXEC_PARAMS_NEW)));
6092                 return;
6093         }
6094
6095         /*
6096          * Put new file in place.  This could delay on Win32, but we don't hold
6097          * any exclusive locks.
6098          */
6099         rename(CONFIG_EXEC_PARAMS_NEW, CONFIG_EXEC_PARAMS);
6100 }
6101
6102
6103 /*
6104  *      Read string, including null byte from file
6105  *
6106  *      Return NULL on EOF and nothing read
6107  */
6108 static char *
6109 read_string_with_null(FILE *fp)
6110 {
6111         int                     i = 0,
6112                                 ch,
6113                                 maxlen = 256;
6114         char       *str = NULL;
6115
6116         do
6117         {
6118                 if ((ch = fgetc(fp)) == EOF)
6119                 {
6120                         if (i == 0)
6121                                 return NULL;
6122                         else
6123                                 elog(FATAL, "invalid format of exec config params file");
6124                 }
6125                 if (i == 0)
6126                         str = guc_malloc(FATAL, maxlen);
6127                 else if (i == maxlen)
6128                         str = guc_realloc(FATAL, str, maxlen *= 2);
6129                 str[i++] = ch;
6130         } while (ch != 0);
6131
6132         return str;
6133 }
6134
6135
6136 /*
6137  *      This routine loads a previous postmaster dump of its non-default
6138  *      settings.
6139  */
6140 void
6141 read_nondefault_variables(void)
6142 {
6143         FILE       *fp;
6144         char       *varname,
6145                            *varvalue;
6146         int                     varsource;
6147
6148         /*
6149          * Open file
6150          */
6151         fp = AllocateFile(CONFIG_EXEC_PARAMS, "r");
6152         if (!fp)
6153         {
6154                 /* File not found is fine */
6155                 if (errno != ENOENT)
6156                         ereport(FATAL,
6157                                         (errcode_for_file_access(),
6158                                          errmsg("could not read from file \"%s\": %m",
6159                                                         CONFIG_EXEC_PARAMS)));
6160                 return;
6161         }
6162
6163         for (;;)
6164         {
6165                 struct config_generic *record;
6166
6167                 if ((varname = read_string_with_null(fp)) == NULL)
6168                         break;
6169
6170                 if ((record = find_option(varname, true, FATAL)) == NULL)
6171                         elog(FATAL, "failed to locate variable %s in exec config params file", varname);
6172                 if ((varvalue = read_string_with_null(fp)) == NULL)
6173                         elog(FATAL, "invalid format of exec config params file");
6174                 if (fread(&varsource, sizeof(varsource), 1, fp) == 0)
6175                         elog(FATAL, "invalid format of exec config params file");
6176
6177                 (void) set_config_option(varname, varvalue, record->context,
6178                                                                  varsource, GUC_ACTION_SET, true);
6179                 free(varname);
6180                 free(varvalue);
6181         }
6182
6183         FreeFile(fp);
6184 }
6185 #endif   /* EXEC_BACKEND */
6186
6187
6188 /*
6189  * A little "long argument" simulation, although not quite GNU
6190  * compliant. Takes a string of the form "some-option=some value" and
6191  * returns name = "some_option" and value = "some value" in malloc'ed
6192  * storage. Note that '-' is converted to '_' in the option name. If
6193  * there is no '=' in the input string then value will be NULL.
6194  */
6195 void
6196 ParseLongOption(const char *string, char **name, char **value)
6197 {
6198         size_t          equal_pos;
6199         char       *cp;
6200
6201         AssertArg(string);
6202         AssertArg(name);
6203         AssertArg(value);
6204
6205         equal_pos = strcspn(string, "=");
6206
6207         if (string[equal_pos] == '=')
6208         {
6209                 *name = guc_malloc(FATAL, equal_pos + 1);
6210                 strlcpy(*name, string, equal_pos + 1);
6211
6212                 *value = guc_strdup(FATAL, &string[equal_pos + 1]);
6213         }
6214         else
6215         {
6216                 /* no equal sign in string */
6217                 *name = guc_strdup(FATAL, string);
6218                 *value = NULL;
6219         }
6220
6221         for (cp = *name; *cp; cp++)
6222                 if (*cp == '-')
6223                         *cp = '_';
6224 }
6225
6226
6227 /*
6228  * Handle options fetched from pg_database.datconfig, pg_authid.rolconfig,
6229  * pg_proc.proconfig, etc.      Caller must specify proper context/source/action.
6230  *
6231  * The array parameter must be an array of TEXT (it must not be NULL).
6232  */
6233 void
6234 ProcessGUCArray(ArrayType *array,
6235                                 GucContext context, GucSource source, GucAction action)
6236 {
6237         int                     i;
6238
6239         Assert(array != NULL);
6240         Assert(ARR_ELEMTYPE(array) == TEXTOID);
6241         Assert(ARR_NDIM(array) == 1);
6242         Assert(ARR_LBOUND(array)[0] == 1);
6243
6244         for (i = 1; i <= ARR_DIMS(array)[0]; i++)
6245         {
6246                 Datum           d;
6247                 bool            isnull;
6248                 char       *s;
6249                 char       *name;
6250                 char       *value;
6251
6252                 d = array_ref(array, 1, &i,
6253                                           -1 /* varlenarray */ ,
6254                                           -1 /* TEXT's typlen */ ,
6255                                           false /* TEXT's typbyval */ ,
6256                                           'i' /* TEXT's typalign */ ,
6257                                           &isnull);
6258
6259                 if (isnull)
6260                         continue;
6261
6262                 s = DatumGetCString(DirectFunctionCall1(textout, d));
6263
6264                 ParseLongOption(s, &name, &value);
6265                 if (!value)
6266                 {
6267                         ereport(WARNING,
6268                                         (errcode(ERRCODE_SYNTAX_ERROR),
6269                                          errmsg("could not parse setting for parameter \"%s\"",
6270                                                         name)));
6271                         free(name);
6272                         continue;
6273                 }
6274
6275                 (void) set_config_option(name, value, context, source, action, true);
6276
6277                 free(name);
6278                 if (value)
6279                         free(value);
6280         }
6281 }
6282
6283
6284 /*
6285  * Add an entry to an option array.  The array parameter may be NULL
6286  * to indicate the current table entry is NULL.
6287  */
6288 ArrayType *
6289 GUCArrayAdd(ArrayType *array, const char *name, const char *value)
6290 {
6291         const char *varname;
6292         Datum           datum;
6293         char       *newval;
6294         ArrayType  *a;
6295
6296         Assert(name);
6297         Assert(value);
6298
6299         /* test if the option is valid */
6300         set_config_option(name, value,
6301                                           superuser() ? PGC_SUSET : PGC_USERSET,
6302                                           PGC_S_TEST, GUC_ACTION_SET, false);
6303
6304         /* convert name to canonical spelling, so we can use plain strcmp */
6305         (void) GetConfigOptionByName(name, &varname);
6306         name = varname;
6307
6308         newval = palloc(strlen(name) + 1 + strlen(value) + 1);
6309         sprintf(newval, "%s=%s", name, value);
6310         datum = DirectFunctionCall1(textin, CStringGetDatum(newval));
6311
6312         if (array)
6313         {
6314                 int                     index;
6315                 bool            isnull;
6316                 int                     i;
6317
6318                 Assert(ARR_ELEMTYPE(array) == TEXTOID);
6319                 Assert(ARR_NDIM(array) == 1);
6320                 Assert(ARR_LBOUND(array)[0] == 1);
6321
6322                 index = ARR_DIMS(array)[0] + 1; /* add after end */
6323
6324                 for (i = 1; i <= ARR_DIMS(array)[0]; i++)
6325                 {
6326                         Datum           d;
6327                         char       *current;
6328
6329                         d = array_ref(array, 1, &i,
6330                                                   -1 /* varlenarray */ ,
6331                                                   -1 /* TEXT's typlen */ ,
6332                                                   false /* TEXT's typbyval */ ,
6333                                                   'i' /* TEXT's typalign */ ,
6334                                                   &isnull);
6335                         if (isnull)
6336                                 continue;
6337                         current = DatumGetCString(DirectFunctionCall1(textout, d));
6338                         if (strncmp(current, newval, strlen(name) + 1) == 0)
6339                         {
6340                                 index = i;
6341                                 break;
6342                         }
6343                 }
6344
6345                 a = array_set(array, 1, &index,
6346                                           datum,
6347                                           false,
6348                                           -1 /* varlena array */ ,
6349                                           -1 /* TEXT's typlen */ ,
6350                                           false /* TEXT's typbyval */ ,
6351                                           'i' /* TEXT's typalign */ );
6352         }
6353         else
6354                 a = construct_array(&datum, 1,
6355                                                         TEXTOID,
6356                                                         -1, false, 'i');
6357
6358         return a;
6359 }
6360
6361
6362 /*
6363  * Delete an entry from an option array.  The array parameter may be NULL
6364  * to indicate the current table entry is NULL.  Also, if the return value
6365  * is NULL then a null should be stored.
6366  */
6367 ArrayType *
6368 GUCArrayDelete(ArrayType *array, const char *name)
6369 {
6370         const char *varname;
6371         ArrayType  *newarray;
6372         int                     i;
6373         int                     index;
6374
6375         Assert(name);
6376
6377         /* test if the option is valid */
6378         set_config_option(name, NULL,
6379                                           superuser() ? PGC_SUSET : PGC_USERSET,
6380                                           PGC_S_TEST, GUC_ACTION_SET, false);
6381
6382         /* convert name to canonical spelling, so we can use plain strcmp */
6383         (void) GetConfigOptionByName(name, &varname);
6384         name = varname;
6385
6386         /* if array is currently null, then surely nothing to delete */
6387         if (!array)
6388                 return NULL;
6389
6390         newarray = NULL;
6391         index = 1;
6392
6393         for (i = 1; i <= ARR_DIMS(array)[0]; i++)
6394         {
6395                 Datum           d;
6396                 char       *val;
6397                 bool            isnull;
6398
6399                 d = array_ref(array, 1, &i,
6400                                           -1 /* varlenarray */ ,
6401                                           -1 /* TEXT's typlen */ ,
6402                                           false /* TEXT's typbyval */ ,
6403                                           'i' /* TEXT's typalign */ ,
6404                                           &isnull);
6405                 if (isnull)
6406                         continue;
6407                 val = DatumGetCString(DirectFunctionCall1(textout, d));
6408
6409                 /* ignore entry if it's what we want to delete */
6410                 if (strncmp(val, name, strlen(name)) == 0
6411                         && val[strlen(name)] == '=')
6412                         continue;
6413
6414                 /* else add it to the output array */
6415                 if (newarray)
6416                 {
6417                         newarray = array_set(newarray, 1, &index,
6418                                                                  d,
6419                                                                  false,
6420                                                                  -1 /* varlenarray */ ,
6421                                                                  -1 /* TEXT's typlen */ ,
6422                                                                  false /* TEXT's typbyval */ ,
6423                                                                  'i' /* TEXT's typalign */ );
6424                 }
6425                 else
6426                         newarray = construct_array(&d, 1,
6427                                                                            TEXTOID,
6428                                                                            -1, false, 'i');
6429
6430                 index++;
6431         }
6432
6433         return newarray;
6434 }
6435
6436
6437 /*
6438  * assign_hook and show_hook subroutines
6439  */
6440
6441 static const char *
6442 assign_log_destination(const char *value, bool doit, GucSource source)
6443 {
6444         char       *rawstring;
6445         List       *elemlist;
6446         ListCell   *l;
6447         int                     newlogdest = 0;
6448
6449         /* Need a modifiable copy of string */
6450         rawstring = pstrdup(value);
6451
6452         /* Parse string into list of identifiers */
6453         if (!SplitIdentifierString(rawstring, ',', &elemlist))
6454         {
6455                 /* syntax error in list */
6456                 pfree(rawstring);
6457                 list_free(elemlist);
6458                 ereport(GUC_complaint_elevel(source),
6459                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6460                         errmsg("invalid list syntax for parameter \"log_destination\"")));
6461                 return NULL;
6462         }
6463
6464         foreach(l, elemlist)
6465         {
6466                 char       *tok = (char *) lfirst(l);
6467
6468                 if (pg_strcasecmp(tok, "stderr") == 0)
6469                         newlogdest |= LOG_DESTINATION_STDERR;
6470                 else if (pg_strcasecmp(tok, "csvlog") == 0)
6471                         newlogdest |= LOG_DESTINATION_CSVLOG;
6472 #ifdef HAVE_SYSLOG
6473                 else if (pg_strcasecmp(tok, "syslog") == 0)
6474                         newlogdest |= LOG_DESTINATION_SYSLOG;
6475 #endif
6476 #ifdef WIN32
6477                 else if (pg_strcasecmp(tok, "eventlog") == 0)
6478                         newlogdest |= LOG_DESTINATION_EVENTLOG;
6479 #endif
6480                 else
6481                 {
6482                         ereport(GUC_complaint_elevel(source),
6483                                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6484                                   errmsg("unrecognized \"log_destination\" key word: \"%s\"",
6485                                                  tok)));
6486                         pfree(rawstring);
6487                         list_free(elemlist);
6488                         return NULL;
6489                 }
6490         }
6491
6492         if (doit)
6493                 Log_destination = newlogdest;
6494
6495         pfree(rawstring);
6496         list_free(elemlist);
6497
6498         return value;
6499 }
6500
6501 #ifdef HAVE_SYSLOG
6502
6503 static const char *
6504 assign_syslog_facility(const char *facility, bool doit, GucSource source)
6505 {
6506         int                     syslog_fac;
6507
6508         if (pg_strcasecmp(facility, "LOCAL0") == 0)
6509                 syslog_fac = LOG_LOCAL0;
6510         else if (pg_strcasecmp(facility, "LOCAL1") == 0)
6511                 syslog_fac = LOG_LOCAL1;
6512         else if (pg_strcasecmp(facility, "LOCAL2") == 0)
6513                 syslog_fac = LOG_LOCAL2;
6514         else if (pg_strcasecmp(facility, "LOCAL3") == 0)
6515                 syslog_fac = LOG_LOCAL3;
6516         else if (pg_strcasecmp(facility, "LOCAL4") == 0)
6517                 syslog_fac = LOG_LOCAL4;
6518         else if (pg_strcasecmp(facility, "LOCAL5") == 0)
6519                 syslog_fac = LOG_LOCAL5;
6520         else if (pg_strcasecmp(facility, "LOCAL6") == 0)
6521                 syslog_fac = LOG_LOCAL6;
6522         else if (pg_strcasecmp(facility, "LOCAL7") == 0)
6523                 syslog_fac = LOG_LOCAL7;
6524         else
6525                 return NULL;                    /* reject */
6526
6527         if (doit)
6528         {
6529                 syslog_facility = syslog_fac;
6530                 set_syslog_parameters(syslog_ident_str ? syslog_ident_str : "postgres",
6531                                                           syslog_facility);
6532         }
6533
6534         return facility;
6535 }
6536
6537 static const char *
6538 assign_syslog_ident(const char *ident, bool doit, GucSource source)
6539 {
6540         if (doit)
6541                 set_syslog_parameters(ident, syslog_facility);
6542
6543         return ident;
6544 }
6545 #endif   /* HAVE_SYSLOG */
6546
6547
6548 static const char *
6549 assign_defaultxactisolevel(const char *newval, bool doit, GucSource source)
6550 {
6551         if (pg_strcasecmp(newval, "serializable") == 0)
6552         {
6553                 if (doit)
6554                         DefaultXactIsoLevel = XACT_SERIALIZABLE;
6555         }
6556         else if (pg_strcasecmp(newval, "repeatable read") == 0)
6557         {
6558                 if (doit)
6559                         DefaultXactIsoLevel = XACT_REPEATABLE_READ;
6560         }
6561         else if (pg_strcasecmp(newval, "read committed") == 0)
6562         {
6563                 if (doit)
6564                         DefaultXactIsoLevel = XACT_READ_COMMITTED;
6565         }
6566         else if (pg_strcasecmp(newval, "read uncommitted") == 0)
6567         {
6568                 if (doit)
6569                         DefaultXactIsoLevel = XACT_READ_UNCOMMITTED;
6570         }
6571         else
6572                 return NULL;
6573         return newval;
6574 }
6575
6576 static const char *
6577 assign_session_replication_role(const char *newval, bool doit, GucSource source)
6578 {
6579         int                     newrole;
6580
6581         if (pg_strcasecmp(newval, "origin") == 0)
6582                 newrole = SESSION_REPLICATION_ROLE_ORIGIN;
6583         else if (pg_strcasecmp(newval, "replica") == 0)
6584                 newrole = SESSION_REPLICATION_ROLE_REPLICA;
6585         else if (pg_strcasecmp(newval, "local") == 0)
6586                 newrole = SESSION_REPLICATION_ROLE_LOCAL;
6587         else
6588                 return NULL;
6589
6590         /*
6591          * Must flush the plan cache when changing replication role; but don't
6592          * flush unnecessarily.
6593          */
6594         if (doit && SessionReplicationRole != newrole)
6595         {
6596                 ResetPlanCache();
6597                 SessionReplicationRole = newrole;
6598         }
6599
6600         return newval;
6601 }
6602
6603 static const char *
6604 assign_log_min_messages(const char *newval, bool doit, GucSource source)
6605 {
6606         return (assign_msglvl(&log_min_messages, newval, doit, source));
6607 }
6608
6609 static const char *
6610 assign_client_min_messages(const char *newval, bool doit, GucSource source)
6611 {
6612         return (assign_msglvl(&client_min_messages, newval, doit, source));
6613 }
6614
6615 static const char *
6616 assign_min_error_statement(const char *newval, bool doit, GucSource source)
6617 {
6618         return (assign_msglvl(&log_min_error_statement, newval, doit, source));
6619 }
6620
6621 static const char *
6622 assign_msglvl(int *var, const char *newval, bool doit, GucSource source)
6623 {
6624         if (pg_strcasecmp(newval, "debug") == 0)
6625         {
6626                 if (doit)
6627                         (*var) = DEBUG2;
6628         }
6629         else if (pg_strcasecmp(newval, "debug5") == 0)
6630         {
6631                 if (doit)
6632                         (*var) = DEBUG5;
6633         }
6634         else if (pg_strcasecmp(newval, "debug4") == 0)
6635         {
6636                 if (doit)
6637                         (*var) = DEBUG4;
6638         }
6639         else if (pg_strcasecmp(newval, "debug3") == 0)
6640         {
6641                 if (doit)
6642                         (*var) = DEBUG3;
6643         }
6644         else if (pg_strcasecmp(newval, "debug2") == 0)
6645         {
6646                 if (doit)
6647                         (*var) = DEBUG2;
6648         }
6649         else if (pg_strcasecmp(newval, "debug1") == 0)
6650         {
6651                 if (doit)
6652                         (*var) = DEBUG1;
6653         }
6654         else if (pg_strcasecmp(newval, "log") == 0)
6655         {
6656                 if (doit)
6657                         (*var) = LOG;
6658         }
6659
6660         /*
6661          * Client_min_messages always prints 'info', but we allow it as a value
6662          * anyway.
6663          */
6664         else if (pg_strcasecmp(newval, "info") == 0)
6665         {
6666                 if (doit)
6667                         (*var) = INFO;
6668         }
6669         else if (pg_strcasecmp(newval, "notice") == 0)
6670         {
6671                 if (doit)
6672                         (*var) = NOTICE;
6673         }
6674         else if (pg_strcasecmp(newval, "warning") == 0)
6675         {
6676                 if (doit)
6677                         (*var) = WARNING;
6678         }
6679         else if (pg_strcasecmp(newval, "error") == 0)
6680         {
6681                 if (doit)
6682                         (*var) = ERROR;
6683         }
6684         /* We allow FATAL/PANIC for client-side messages too. */
6685         else if (pg_strcasecmp(newval, "fatal") == 0)
6686         {
6687                 if (doit)
6688                         (*var) = FATAL;
6689         }
6690         else if (pg_strcasecmp(newval, "panic") == 0)
6691         {
6692                 if (doit)
6693                         (*var) = PANIC;
6694         }
6695         else
6696                 return NULL;                    /* fail */
6697         return newval;                          /* OK */
6698 }
6699
6700 static const char *
6701 assign_log_error_verbosity(const char *newval, bool doit, GucSource source)
6702 {
6703         if (pg_strcasecmp(newval, "terse") == 0)
6704         {
6705                 if (doit)
6706                         Log_error_verbosity = PGERROR_TERSE;
6707         }
6708         else if (pg_strcasecmp(newval, "default") == 0)
6709         {
6710                 if (doit)
6711                         Log_error_verbosity = PGERROR_DEFAULT;
6712         }
6713         else if (pg_strcasecmp(newval, "verbose") == 0)
6714         {
6715                 if (doit)
6716                         Log_error_verbosity = PGERROR_VERBOSE;
6717         }
6718         else
6719                 return NULL;                    /* fail */
6720         return newval;                          /* OK */
6721 }
6722
6723 static const char *
6724 assign_log_statement(const char *newval, bool doit, GucSource source)
6725 {
6726         if (pg_strcasecmp(newval, "none") == 0)
6727         {
6728                 if (doit)
6729                         log_statement = LOGSTMT_NONE;
6730         }
6731         else if (pg_strcasecmp(newval, "ddl") == 0)
6732         {
6733                 if (doit)
6734                         log_statement = LOGSTMT_DDL;
6735         }
6736         else if (pg_strcasecmp(newval, "mod") == 0)
6737         {
6738                 if (doit)
6739                         log_statement = LOGSTMT_MOD;
6740         }
6741         else if (pg_strcasecmp(newval, "all") == 0)
6742         {
6743                 if (doit)
6744                         log_statement = LOGSTMT_ALL;
6745         }
6746         else
6747                 return NULL;                    /* fail */
6748         return newval;                          /* OK */
6749 }
6750
6751 static const char *
6752 show_num_temp_buffers(void)
6753 {
6754         /*
6755          * We show the GUC var until local buffers have been initialized, and
6756          * NLocBuffer afterwards.
6757          */
6758         static char nbuf[32];
6759
6760         sprintf(nbuf, "%d", NLocBuffer ? NLocBuffer : num_temp_buffers);
6761         return nbuf;
6762 }
6763
6764 static bool
6765 assign_phony_autocommit(bool newval, bool doit, GucSource source)
6766 {
6767         if (!newval)
6768         {
6769                 ereport(GUC_complaint_elevel(source),
6770                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6771                                  errmsg("SET AUTOCOMMIT TO OFF is no longer supported")));
6772                 return false;
6773         }
6774         return true;
6775 }
6776
6777 static const char *
6778 assign_custom_variable_classes(const char *newval, bool doit, GucSource source)
6779 {
6780         /*
6781          * Check syntax. newval must be a comma separated list of identifiers.
6782          * Whitespace is allowed but removed from the result.
6783          */
6784         bool            hasSpaceAfterToken = false;
6785         const char *cp = newval;
6786         int                     symLen = 0;
6787         char            c;
6788         StringInfoData buf;
6789
6790         initStringInfo(&buf);
6791         while ((c = *cp++) != '\0')
6792         {
6793                 if (isspace((unsigned char) c))
6794                 {
6795                         if (symLen > 0)
6796                                 hasSpaceAfterToken = true;
6797                         continue;
6798                 }
6799
6800                 if (c == ',')
6801                 {
6802                         if (symLen > 0)         /* terminate identifier */
6803                         {
6804                                 appendStringInfoChar(&buf, ',');
6805                                 symLen = 0;
6806                         }
6807                         hasSpaceAfterToken = false;
6808                         continue;
6809                 }
6810
6811                 if (hasSpaceAfterToken || !isalnum((unsigned char) c))
6812                 {
6813                         /*
6814                          * Syntax error due to token following space after token or non
6815                          * alpha numeric character
6816                          */
6817                         pfree(buf.data);
6818                         return NULL;
6819                 }
6820                 appendStringInfoChar(&buf, c);
6821                 symLen++;
6822         }
6823
6824         /* Remove stray ',' at end */
6825         if (symLen == 0 && buf.len > 0)
6826                 buf.data[--buf.len] = '\0';
6827
6828         /* GUC wants the result malloc'd */
6829         newval = guc_strdup(LOG, buf.data);
6830
6831         pfree(buf.data);
6832         return newval;
6833 }
6834
6835 static bool
6836 assign_debug_assertions(bool newval, bool doit, GucSource source)
6837 {
6838 #ifndef USE_ASSERT_CHECKING
6839         if (newval)
6840         {
6841                 ereport(GUC_complaint_elevel(source),
6842                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6843                            errmsg("assertion checking is not supported by this build")));
6844                 return false;
6845         }
6846 #endif
6847         return true;
6848 }
6849
6850 static bool
6851 assign_ssl(bool newval, bool doit, GucSource source)
6852 {
6853 #ifndef USE_SSL
6854         if (newval)
6855         {
6856                 ereport(GUC_complaint_elevel(source),
6857                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6858                                  errmsg("SSL is not supported by this build")));
6859                 return false;
6860         }
6861 #endif
6862         return true;
6863 }
6864
6865 static bool
6866 assign_stage_log_stats(bool newval, bool doit, GucSource source)
6867 {
6868         if (newval && log_statement_stats)
6869         {
6870                 ereport(GUC_complaint_elevel(source),
6871                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6872                                  errmsg("cannot enable parameter when \"log_statement_stats\" is true")));
6873                 /* source == PGC_S_OVERRIDE means do it anyway, eg at xact abort */
6874                 if (source != PGC_S_OVERRIDE)
6875                         return false;
6876         }
6877         return true;
6878 }
6879
6880 static bool
6881 assign_log_stats(bool newval, bool doit, GucSource source)
6882 {
6883         if (newval &&
6884                 (log_parser_stats || log_planner_stats || log_executor_stats))
6885         {
6886                 ereport(GUC_complaint_elevel(source),
6887                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6888                                  errmsg("cannot enable \"log_statement_stats\" when "
6889                                                 "\"log_parser_stats\", \"log_planner_stats\", "
6890                                                 "or \"log_executor_stats\" is true")));
6891                 /* source == PGC_S_OVERRIDE means do it anyway, eg at xact abort */
6892                 if (source != PGC_S_OVERRIDE)
6893                         return false;
6894         }
6895         return true;
6896 }
6897
6898 static bool
6899 assign_transaction_read_only(bool newval, bool doit, GucSource source)
6900 {
6901         /* Can't go to r/w mode inside a r/o transaction */
6902         if (newval == false && XactReadOnly && IsSubTransaction())
6903         {
6904                 ereport(GUC_complaint_elevel(source),
6905                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6906                                  errmsg("cannot set transaction read-write mode inside a read-only transaction")));
6907                 /* source == PGC_S_OVERRIDE means do it anyway, eg at xact abort */
6908                 if (source != PGC_S_OVERRIDE)
6909                         return false;
6910         }
6911         return true;
6912 }
6913
6914 static const char *
6915 assign_canonical_path(const char *newval, bool doit, GucSource source)
6916 {
6917         if (doit)
6918         {
6919                 char       *canon_val = guc_strdup(ERROR, newval);
6920
6921                 canonicalize_path(canon_val);
6922                 return canon_val;
6923         }
6924         else
6925                 return newval;
6926 }
6927
6928 static const char *
6929 assign_backslash_quote(const char *newval, bool doit, GucSource source)
6930 {
6931         BackslashQuoteType bq;
6932         bool            bqbool;
6933
6934         /*
6935          * Although only "on", "off", and "safe_encoding" are documented, we use
6936          * parse_bool so we can accept all the likely variants of "on" and "off".
6937          */
6938         if (pg_strcasecmp(newval, "safe_encoding") == 0)
6939                 bq = BACKSLASH_QUOTE_SAFE_ENCODING;
6940         else if (parse_bool(newval, &bqbool))
6941         {
6942                 bq = bqbool ? BACKSLASH_QUOTE_ON : BACKSLASH_QUOTE_OFF;
6943         }
6944         else
6945                 return NULL;                    /* reject */
6946
6947         if (doit)
6948                 backslash_quote = bq;
6949
6950         return newval;
6951 }
6952
6953 static const char *
6954 assign_timezone_abbreviations(const char *newval, bool doit, GucSource source)
6955 {
6956         /*
6957          * The powerup value shown above for timezone_abbreviations is "UNKNOWN".
6958          * When we see this we just do nothing.  If this value isn't overridden
6959          * from the config file then pg_timezone_abbrev_initialize() will
6960          * eventually replace it with "Default".  This hack has two purposes: to
6961          * avoid wasting cycles loading values that might soon be overridden from
6962          * the config file, and to avoid trying to read the timezone abbrev files
6963          * during InitializeGUCOptions().  The latter doesn't work in an
6964          * EXEC_BACKEND subprocess because my_exec_path hasn't been set yet and so
6965          * we can't locate PGSHAREDIR.  (Essentially the same hack is used to
6966          * delay initializing TimeZone ... if we have any more, we should try to
6967          * clean up and centralize this mechanism ...)
6968          */
6969         if (strcmp(newval, "UNKNOWN") == 0)
6970         {
6971                 return newval;
6972         }
6973
6974         /* Loading abbrev file is expensive, so only do it when value changes */
6975         if (timezone_abbreviations_string == NULL ||
6976                 strcmp(timezone_abbreviations_string, newval) != 0)
6977         {
6978                 int                     elevel;
6979
6980                 /*
6981                  * If reading config file, only the postmaster should bleat loudly
6982                  * about problems.      Otherwise, it's just this one process doing it,
6983                  * and we use WARNING message level.
6984                  */
6985                 if (source == PGC_S_FILE)
6986                         elevel = IsUnderPostmaster ? DEBUG3 : LOG;
6987                 else
6988                         elevel = WARNING;
6989                 if (!load_tzoffsets(newval, doit, elevel))
6990                         return NULL;
6991         }
6992         return newval;
6993 }
6994
6995 /*
6996  * pg_timezone_abbrev_initialize --- set default value if not done already
6997  *
6998  * This is called after initial loading of postgresql.conf.  If no
6999  * timezone_abbreviations setting was found therein, select default.
7000  */
7001 void
7002 pg_timezone_abbrev_initialize(void)
7003 {
7004         if (strcmp(timezone_abbreviations_string, "UNKNOWN") == 0)
7005         {
7006                 SetConfigOption("timezone_abbreviations", "Default",
7007                                                 PGC_POSTMASTER, PGC_S_ARGV);
7008         }
7009 }
7010
7011 static const char *
7012 assign_xmlbinary(const char *newval, bool doit, GucSource source)
7013 {
7014         XmlBinaryType xb;
7015
7016         if (pg_strcasecmp(newval, "base64") == 0)
7017                 xb = XMLBINARY_BASE64;
7018         else if (pg_strcasecmp(newval, "hex") == 0)
7019                 xb = XMLBINARY_HEX;
7020         else
7021                 return NULL;                    /* reject */
7022
7023         if (doit)
7024                 xmlbinary = xb;
7025
7026         return newval;
7027 }
7028
7029 static const char *
7030 assign_xmloption(const char *newval, bool doit, GucSource source)
7031 {
7032         XmlOptionType xo;
7033
7034         if (pg_strcasecmp(newval, "document") == 0)
7035                 xo = XMLOPTION_DOCUMENT;
7036         else if (pg_strcasecmp(newval, "content") == 0)
7037                 xo = XMLOPTION_CONTENT;
7038         else
7039                 return NULL;                    /* reject */
7040
7041         if (doit)
7042                 xmloption = xo;
7043
7044         return newval;
7045 }
7046
7047 static const char *
7048 show_archive_command(void)
7049 {
7050         if (XLogArchiveMode)
7051                 return XLogArchiveCommand;
7052         else
7053                 return "(disabled)";
7054 }
7055
7056 static bool
7057 assign_tcp_keepalives_idle(int newval, bool doit, GucSource source)
7058 {
7059         if (doit)
7060                 return (pq_setkeepalivesidle(newval, MyProcPort) == STATUS_OK);
7061
7062         return true;
7063 }
7064
7065 static const char *
7066 show_tcp_keepalives_idle(void)
7067 {
7068         static char nbuf[16];
7069
7070         snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivesidle(MyProcPort));
7071         return nbuf;
7072 }
7073
7074 static bool
7075 assign_tcp_keepalives_interval(int newval, bool doit, GucSource source)
7076 {
7077         if (doit)
7078                 return (pq_setkeepalivesinterval(newval, MyProcPort) == STATUS_OK);
7079
7080         return true;
7081 }
7082
7083 static const char *
7084 show_tcp_keepalives_interval(void)
7085 {
7086         static char nbuf[16];
7087
7088         snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivesinterval(MyProcPort));
7089         return nbuf;
7090 }
7091
7092 static bool
7093 assign_tcp_keepalives_count(int newval, bool doit, GucSource source)
7094 {
7095         if (doit)
7096                 return (pq_setkeepalivescount(newval, MyProcPort) == STATUS_OK);
7097
7098         return true;
7099 }
7100
7101 static const char *
7102 show_tcp_keepalives_count(void)
7103 {
7104         static char nbuf[16];
7105
7106         snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivescount(MyProcPort));
7107         return nbuf;
7108 }
7109
7110 static bool
7111 assign_maxconnections(int newval, bool doit, GucSource source)
7112 {
7113         if (newval + autovacuum_max_workers > INT_MAX / 4)
7114                 return false;
7115
7116         if (doit)
7117                 MaxBackends = newval + autovacuum_max_workers;
7118
7119         return true;
7120 }
7121
7122 static bool
7123 assign_autovacuum_max_workers(int newval, bool doit, GucSource source)
7124 {
7125         if (newval + MaxConnections > INT_MAX / 4)
7126                 return false;
7127
7128         if (doit)
7129                 MaxBackends = newval + MaxConnections;
7130
7131         return true;
7132 }
7133
7134 #include "guc-file.c"