OSDN Git Service

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