PostgreSQL Source Code  git master
tcopprot.h File Reference
#include "nodes/params.h"
#include "nodes/parsenodes.h"
#include "nodes/plannodes.h"
#include "storage/procsignal.h"
#include "utils/guc.h"
#include "utils/queryenvironment.h"
Include dependency graph for tcopprot.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Macros

#define STACK_DEPTH_SLOP   (512 * 1024L)
 

Enumerations

enum  LogStmtLevel { LOGSTMT_NONE, LOGSTMT_DDL, LOGSTMT_MOD, LOGSTMT_ALL }
 

Functions

Listpg_parse_query (const char *query_string)
 
Listpg_analyze_and_rewrite (RawStmt *parsetree, const char *query_string, Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
 
Listpg_analyze_and_rewrite_params (RawStmt *parsetree, const char *query_string, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
 
PlannedStmtpg_plan_query (Query *querytree, const char *query_string, int cursorOptions, ParamListInfo boundParams)
 
Listpg_plan_queries (List *querytrees, const char *query_string, int cursorOptions, ParamListInfo boundParams)
 
bool check_max_stack_depth (int *newval, void **extra, GucSource source)
 
void assign_max_stack_depth (int newval, void *extra)
 
void die (SIGNAL_ARGS)
 
void quickdie (SIGNAL_ARGS) pg_attribute_noreturn()
 
void StatementCancelHandler (SIGNAL_ARGS)
 
void FloatExceptionHandler (SIGNAL_ARGS) pg_attribute_noreturn()
 
void RecoveryConflictInterrupt (ProcSignalReason reason)
 
void ProcessClientReadInterrupt (bool blocked)
 
void ProcessClientWriteInterrupt (bool blocked)
 
void process_postgres_switches (int argc, char *argv[], GucContext ctx, const char **dbname)
 
void PostgresMain (int argc, char *argv[], const char *dbname, const char *username) pg_attribute_noreturn()
 
long get_stack_depth_rlimit (void)
 
void ResetUsage (void)
 
void ShowUsage (const char *title)
 
int check_log_duration (char *msec_str, bool was_logged)
 
void set_debug_options (int debug_flag, GucContext context, GucSource source)
 
bool set_plan_disabling_options (const char *arg, GucContext context, GucSource source)
 
const char * get_stats_option_name (const char *arg)
 

Variables

CommandDest whereToSendOutput
 
PGDLLIMPORT const char * debug_query_string
 
int max_stack_depth
 
int PostAuthDelay
 
PGDLLIMPORT int log_statement
 

Macro Definition Documentation

◆ STACK_DEPTH_SLOP

#define STACK_DEPTH_SLOP   (512 * 1024L)

Definition at line 26 of file tcopprot.h.

Referenced by check_max_stack_depth(), and InitializeGUCOptionsFromEnvironment().

Enumeration Type Documentation

◆ LogStmtLevel

Enumerator
LOGSTMT_NONE 
LOGSTMT_DDL 
LOGSTMT_MOD 
LOGSTMT_ALL 

Definition at line 35 of file tcopprot.h.

36 {
37  LOGSTMT_NONE, /* log no statements */
38  LOGSTMT_DDL, /* log data definition statements */
39  LOGSTMT_MOD, /* log modification statements, plus DDL */
40  LOGSTMT_ALL /* log all statements */
41 } LogStmtLevel;
LogStmtLevel
Definition: tcopprot.h:35

Function Documentation

◆ assign_max_stack_depth()

void assign_max_stack_depth ( int  newval,
void *  extra 
)

Definition at line 3392 of file postgres.c.

References max_stack_depth_bytes.

3393 {
3394  long newval_bytes = newval * 1024L;
3395 
3396  max_stack_depth_bytes = newval_bytes;
3397 }
static long max_stack_depth_bytes
Definition: postgres.c:112
#define newval

◆ check_log_duration()

int check_log_duration ( char *  msec_str,
bool  was_logged 
)

Definition at line 2322 of file postgres.c.

References GetCurrentStatementStartTimestamp(), GetCurrentTimestamp(), log_duration, log_min_duration_sample, log_min_duration_statement, log_statement_sample_rate, MAX_RANDOM_VALUE, random(), snprintf, TimestampDifference(), and xact_is_sampled.

Referenced by exec_bind_message(), exec_execute_message(), exec_parse_message(), exec_simple_query(), and HandleFunctionRequest().

2323 {
2324  if (log_duration || log_min_duration_sample >= 0 ||
2326  {
2327  long secs;
2328  int usecs;
2329  int msecs;
2330  bool exceeded_duration;
2331  bool exceeded_sample_duration;
2332  bool in_sample = false;
2333 
2336  &secs, &usecs);
2337  msecs = usecs / 1000;
2338 
2339  /*
2340  * This odd-looking test for log_min_duration_* being exceeded is
2341  * designed to avoid integer overflow with very long durations: don't
2342  * compute secs * 1000 until we've verified it will fit in int.
2343  */
2344  exceeded_duration = (log_min_duration_statement == 0 ||
2346  (secs > log_min_duration_statement / 1000 ||
2347  secs * 1000 + msecs >= log_min_duration_statement)));
2348 
2349  exceeded_sample_duration = (log_min_duration_sample == 0 ||
2350  (log_min_duration_sample > 0 &&
2351  (secs > log_min_duration_sample / 1000 ||
2352  secs * 1000 + msecs >= log_min_duration_sample)));
2353 
2354  /*
2355  * Do not log if log_statement_sample_rate = 0. Log a sample if
2356  * log_statement_sample_rate <= 1 and avoid unnecessary random() call
2357  * if log_statement_sample_rate = 1.
2358  */
2359  if (exceeded_sample_duration)
2360  in_sample = log_statement_sample_rate != 0 &&
2361  (log_statement_sample_rate == 1 ||
2363 
2364  if (exceeded_duration || in_sample || log_duration || xact_is_sampled)
2365  {
2366  snprintf(msec_str, 32, "%ld.%03d",
2367  secs * 1000 + msecs, usecs % 1000);
2368  if ((exceeded_duration || in_sample || xact_is_sampled) && !was_logged)
2369  return 2;
2370  else
2371  return 1;
2372  }
2373  }
2374 
2375  return 0;
2376 }
int log_min_duration_statement
Definition: guc.c:537
double log_statement_sample_rate
Definition: guc.c:541
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1574
long random(void)
Definition: random.c:22
int log_min_duration_sample
Definition: guc.c:536
#define MAX_RANDOM_VALUE
bool xact_is_sampled
Definition: xact.c:268
bool log_duration
Definition: guc.c:509
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1648
#define snprintf
Definition: port.h:193
TimestampTz GetCurrentStatementStartTimestamp(void)
Definition: xact.c:792

◆ check_max_stack_depth()

bool check_max_stack_depth ( int *  newval,
void **  extra,
GucSource  source 
)

Definition at line 3375 of file postgres.c.

References get_stack_depth_rlimit(), GUC_check_errdetail, GUC_check_errhint, and STACK_DEPTH_SLOP.

3376 {
3377  long newval_bytes = *newval * 1024L;
3378  long stack_rlimit = get_stack_depth_rlimit();
3379 
3380  if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3381  {
3382  GUC_check_errdetail("\"max_stack_depth\" must not exceed %ldkB.",
3383  (stack_rlimit - STACK_DEPTH_SLOP) / 1024L);
3384  GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3385  return false;
3386  }
3387  return true;
3388 }
#define GUC_check_errdetail
Definition: guc.h:415
long get_stack_depth_rlimit(void)
Definition: postgres.c:4575
#define newval
#define GUC_check_errhint
Definition: guc.h:419
#define STACK_DEPTH_SLOP
Definition: tcopprot.h:26

◆ die()

void die ( SIGNAL_ARGS  )

Definition at line 2826 of file postgres.c.

References DestRemote, DoingCommandRead, InterruptPending, MyLatch, proc_exit_inprogress, ProcDiePending, ProcessInterrupts(), SetLatch(), and whereToSendOutput.

Referenced by PostgresMain().

2827 {
2828  int save_errno = errno;
2829 
2830  /* Don't joggle the elbow of proc_exit */
2831  if (!proc_exit_inprogress)
2832  {
2833  InterruptPending = true;
2834  ProcDiePending = true;
2835  }
2836 
2837  /* If we're still here, waken anything waiting on the process latch */
2838  SetLatch(MyLatch);
2839 
2840  /*
2841  * If we're in single user mode, we want to quit immediately - we can't
2842  * rely on latches as they wouldn't work when stdin/stdout is a file.
2843  * Rather ugly, but it's unlikely to be worthwhile to invest much more
2844  * effort just for the benefit of single user mode.
2845  */
2848 
2849  errno = save_errno;
2850 }
void SetLatch(Latch *latch)
Definition: latch.c:457
void ProcessInterrupts(void)
Definition: postgres.c:3019
volatile sig_atomic_t ProcDiePending
Definition: globals.c:32
bool proc_exit_inprogress
Definition: ipc.c:40
static bool DoingCommandRead
Definition: postgres.c:140
volatile sig_atomic_t InterruptPending
Definition: globals.c:30
struct Latch * MyLatch
Definition: globals.c:54
CommandDest whereToSendOutput
Definition: postgres.c:91

◆ FloatExceptionHandler()

void FloatExceptionHandler ( SIGNAL_ARGS  )

Definition at line 2878 of file postgres.c.

References ereport, errcode(), errdetail(), errmsg(), and ERROR.

Referenced by AutoVacLauncherMain(), AutoVacWorkerMain(), plperl_init_interp(), PostgresMain(), and StartBackgroundWorker().

2879 {
2880  /* We're not returning, so no need to save errno */
2881  ereport(ERROR,
2882  (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2883  errmsg("floating-point exception"),
2884  errdetail("An invalid floating-point operation was signaled. "
2885  "This probably means an out-of-range result or an "
2886  "invalid operation, such as division by zero.")));
2887 }
int errcode(int sqlerrcode)
Definition: elog.c:610
#define ERROR
Definition: elog.h:43
int errdetail(const char *fmt,...)
Definition: elog.c:957
#define ereport(elevel,...)
Definition: elog.h:144
int errmsg(const char *fmt,...)
Definition: elog.c:824

◆ get_stack_depth_rlimit()

long get_stack_depth_rlimit ( void  )

Definition at line 4575 of file postgres.c.

References val.

Referenced by check_max_stack_depth(), and InitializeGUCOptionsFromEnvironment().

4576 {
4577 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_STACK)
4578  static long val = 0;
4579 
4580  /* This won't change after process launch, so check just once */
4581  if (val == 0)
4582  {
4583  struct rlimit rlim;
4584 
4585  if (getrlimit(RLIMIT_STACK, &rlim) < 0)
4586  val = -1;
4587  else if (rlim.rlim_cur == RLIM_INFINITY)
4588  val = LONG_MAX;
4589  /* rlim_cur is probably of an unsigned type, so check for overflow */
4590  else if (rlim.rlim_cur >= LONG_MAX)
4591  val = LONG_MAX;
4592  else
4593  val = rlim.rlim_cur;
4594  }
4595  return val;
4596 #else /* no getrlimit */
4597 #if defined(WIN32) || defined(__CYGWIN__)
4598  /* On Windows we set the backend stack size in src/backend/Makefile */
4599  return WIN32_STACK_RLIMIT;
4600 #else /* not windows ... give up */
4601  return -1;
4602 #endif
4603 #endif
4604 }
long val
Definition: informix.c:664

◆ get_stats_option_name()

const char* get_stats_option_name ( const char *  arg)

Definition at line 3478 of file postgres.c.

References optarg.

Referenced by PostmasterMain(), and process_postgres_switches().

3479 {
3480  switch (arg[0])
3481  {
3482  case 'p':
3483  if (optarg[1] == 'a') /* "parser" */
3484  return "log_parser_stats";
3485  else if (optarg[1] == 'l') /* "planner" */
3486  return "log_planner_stats";
3487  break;
3488 
3489  case 'e': /* "executor" */
3490  return "log_executor_stats";
3491  break;
3492  }
3493 
3494  return NULL;
3495 }
char * optarg
Definition: getopt.c:52
void * arg

◆ pg_analyze_and_rewrite()

List* pg_analyze_and_rewrite ( RawStmt parsetree,
const char *  query_string,
Oid paramTypes,
int  numParams,
QueryEnvironment queryEnv 
)

Definition at line 676 of file postgres.c.

References log_parser_stats, parse_analyze(), pg_rewrite_query(), ResetUsage(), and ShowUsage().

Referenced by _SPI_execute_plan(), _SPI_prepare_plan(), BeginCopy(), exec_simple_query(), execute_sql_string(), and RevalidateCachedQuery().

679 {
680  Query *query;
681  List *querytree_list;
682 
683  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
684 
685  /*
686  * (1) Perform parse analysis.
687  */
688  if (log_parser_stats)
689  ResetUsage();
690 
691  query = parse_analyze(parsetree, query_string, paramTypes, numParams,
692  queryEnv);
693 
694  if (log_parser_stats)
695  ShowUsage("PARSE ANALYSIS STATISTICS");
696 
697  /*
698  * (2) Rewrite the queries, as necessary
699  */
700  querytree_list = pg_rewrite_query(query);
701 
702  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
703 
704  return querytree_list;
705 }
bool log_parser_stats
Definition: guc.c:515
void ShowUsage(const char *title)
Definition: postgres.c:4618
void ResetUsage(void)
Definition: postgres.c:4611
static List * pg_rewrite_query(Query *query)
Definition: postgres.c:765
Query * parse_analyze(RawStmt *parseTree, const char *sourceText, Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition: analyze.c:100
Definition: pg_list.h:50

◆ pg_analyze_and_rewrite_params()

List* pg_analyze_and_rewrite_params ( RawStmt parsetree,
const char *  query_string,
ParserSetupHook  parserSetup,
void *  parserSetupArg,
QueryEnvironment queryEnv 
)

Definition at line 713 of file postgres.c.

References Assert, free_parsestate(), log_parser_stats, make_parsestate(), ParseState::p_queryEnv, ParseState::p_sourcetext, pg_rewrite_query(), post_parse_analyze_hook, ResetUsage(), ShowUsage(), and transformTopLevelStmt().

Referenced by _SPI_execute_plan(), _SPI_prepare_plan(), fmgr_sql_validator(), init_sql_fcache(), inline_set_returning_function(), and RevalidateCachedQuery().

718 {
719  ParseState *pstate;
720  Query *query;
721  List *querytree_list;
722 
723  Assert(query_string != NULL); /* required as of 8.4 */
724 
725  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
726 
727  /*
728  * (1) Perform parse analysis.
729  */
730  if (log_parser_stats)
731  ResetUsage();
732 
733  pstate = make_parsestate(NULL);
734  pstate->p_sourcetext = query_string;
735  pstate->p_queryEnv = queryEnv;
736  (*parserSetup) (pstate, parserSetupArg);
737 
738  query = transformTopLevelStmt(pstate, parsetree);
739 
741  (*post_parse_analyze_hook) (pstate, query);
742 
743  free_parsestate(pstate);
744 
745  if (log_parser_stats)
746  ShowUsage("PARSE ANALYSIS STATISTICS");
747 
748  /*
749  * (2) Rewrite the queries, as necessary
750  */
751  querytree_list = pg_rewrite_query(query);
752 
753  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
754 
755  return querytree_list;
756 }
bool log_parser_stats
Definition: guc.c:515
QueryEnvironment * p_queryEnv
Definition: parse_node.h:203
void ShowUsage(const char *title)
Definition: postgres.c:4618
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:43
void ResetUsage(void)
Definition: postgres.c:4611
const char * p_sourcetext
Definition: parse_node.h:179
static List * pg_rewrite_query(Query *query)
Definition: postgres.c:765
#define Assert(condition)
Definition: c.h:738
Query * transformTopLevelStmt(ParseState *pstate, RawStmt *parseTree)
Definition: analyze.c:191
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:76
Definition: pg_list.h:50
post_parse_analyze_hook_type post_parse_analyze_hook
Definition: analyze.c:51

◆ pg_parse_query()

List* pg_parse_query ( const char *  query_string)

Definition at line 628 of file postgres.c.

References copyObject, elog, equal(), log_parser_stats, new_list(), raw_parser(), ResetUsage(), ShowUsage(), and WARNING.

Referenced by _SPI_prepare_oneshot_plan(), _SPI_prepare_plan(), exec_parse_message(), exec_simple_query(), execute_sql_string(), fmgr_sql_validator(), ImportForeignSchema(), init_sql_fcache(), inline_function(), and inline_set_returning_function().

629 {
630  List *raw_parsetree_list;
631 
632  TRACE_POSTGRESQL_QUERY_PARSE_START(query_string);
633 
634  if (log_parser_stats)
635  ResetUsage();
636 
637  raw_parsetree_list = raw_parser(query_string);
638 
639  if (log_parser_stats)
640  ShowUsage("PARSER STATISTICS");
641 
642 #ifdef COPY_PARSE_PLAN_TREES
643  /* Optional debugging check: pass raw parsetrees through copyObject() */
644  {
645  List *new_list = copyObject(raw_parsetree_list);
646 
647  /* This checks both copyObject() and the equal() routines... */
648  if (!equal(new_list, raw_parsetree_list))
649  elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
650  else
651  raw_parsetree_list = new_list;
652  }
653 #endif
654 
655  /*
656  * Currently, outfuncs/readfuncs support is missing for many raw parse
657  * tree nodes, so we don't try to implement WRITE_READ_PARSE_PLAN_TREES
658  * here.
659  */
660 
661  TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
662 
663  return raw_parsetree_list;
664 }
List * raw_parser(const char *str)
Definition: parser.c:42
bool log_parser_stats
Definition: guc.c:515
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3033
void ShowUsage(const char *title)
Definition: postgres.c:4618
void ResetUsage(void)
Definition: postgres.c:4611
#define WARNING
Definition: elog.h:40
#define elog(elevel,...)
Definition: elog.h:214
#define copyObject(obj)
Definition: nodes.h:645
Definition: pg_list.h:50
static List * new_list(NodeTag type, int min_size)
Definition: list.c:88

◆ pg_plan_queries()

List* pg_plan_queries ( List querytrees,
const char *  query_string,
int  cursorOptions,
ParamListInfo  boundParams 
)

Definition at line 943 of file postgres.c.

References PlannedStmt::canSetTag, Query::canSetTag, CMD_UTILITY, PlannedStmt::commandType, Query::commandType, lappend(), lfirst_node, makeNode, NIL, pg_plan_query(), PlannedStmt::stmt_len, Query::stmt_len, PlannedStmt::stmt_location, Query::stmt_location, PlannedStmt::utilityStmt, and Query::utilityStmt.

Referenced by BuildCachedPlan(), exec_simple_query(), and execute_sql_string().

945 {
946  List *stmt_list = NIL;
947  ListCell *query_list;
948 
949  foreach(query_list, querytrees)
950  {
951  Query *query = lfirst_node(Query, query_list);
952  PlannedStmt *stmt;
953 
954  if (query->commandType == CMD_UTILITY)
955  {
956  /* Utility commands require no planning. */
957  stmt = makeNode(PlannedStmt);
958  stmt->commandType = CMD_UTILITY;
959  stmt->canSetTag = query->canSetTag;
960  stmt->utilityStmt = query->utilityStmt;
961  stmt->stmt_location = query->stmt_location;
962  stmt->stmt_len = query->stmt_len;
963  }
964  else
965  {
966  stmt = pg_plan_query(query, query_string, cursorOptions,
967  boundParams);
968  }
969 
970  stmt_list = lappend(stmt_list, stmt);
971  }
972 
973  return stmt_list;
974 }
#define NIL
Definition: pg_list.h:65
int stmt_location
Definition: parsenodes.h:181
Node * utilityStmt
Definition: parsenodes.h:120
int stmt_len
Definition: plannodes.h:96
#define lfirst_node(type, lc)
Definition: pg_list.h:193
int stmt_location
Definition: plannodes.h:95
Node * utilityStmt
Definition: plannodes.h:92
List * lappend(List *list, void *datum)
Definition: list.c:321
bool canSetTag
Definition: plannodes.h:54
CmdType commandType
Definition: plannodes.h:46
CmdType commandType
Definition: parsenodes.h:112
#define makeNode(_type_)
Definition: nodes.h:577
bool canSetTag
Definition: parsenodes.h:118
PlannedStmt * pg_plan_query(Query *querytree, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:857
Definition: pg_list.h:50
int stmt_len
Definition: parsenodes.h:182

◆ pg_plan_query()

PlannedStmt* pg_plan_query ( Query querytree,
const char *  query_string,
int  cursorOptions,
ParamListInfo  boundParams 
)

Definition at line 857 of file postgres.c.

References ActiveSnapshotSet(), Assert, CMD_UTILITY, Query::commandType, copyObject, Debug_pretty_print, Debug_print_plan, elog, elog_node_display(), equal(), LOG, log_planner_stats, nodeToString(), pfree(), planner(), ResetUsage(), ShowUsage(), generate_unaccent_rules::str, and WARNING.

Referenced by BeginCopy(), ExecCreateTableAs(), ExplainOneQuery(), init_execution_state(), PerformCursorOpen(), pg_plan_queries(), and refresh_matview_datafill().

859 {
860  PlannedStmt *plan;
861 
862  /* Utility commands have no plans. */
863  if (querytree->commandType == CMD_UTILITY)
864  return NULL;
865 
866  /* Planner must have a snapshot in case it calls user-defined functions. */
868 
869  TRACE_POSTGRESQL_QUERY_PLAN_START();
870 
871  if (log_planner_stats)
872  ResetUsage();
873 
874  /* call the optimizer */
875  plan = planner(querytree, query_string, cursorOptions, boundParams);
876 
877  if (log_planner_stats)
878  ShowUsage("PLANNER STATISTICS");
879 
880 #ifdef COPY_PARSE_PLAN_TREES
881  /* Optional debugging check: pass plan tree through copyObject() */
882  {
883  PlannedStmt *new_plan = copyObject(plan);
884 
885  /*
886  * equal() currently does not have routines to compare Plan nodes, so
887  * don't try to test equality here. Perhaps fix someday?
888  */
889 #ifdef NOT_USED
890  /* This checks both copyObject() and the equal() routines... */
891  if (!equal(new_plan, plan))
892  elog(WARNING, "copyObject() failed to produce an equal plan tree");
893  else
894 #endif
895  plan = new_plan;
896  }
897 #endif
898 
899 #ifdef WRITE_READ_PARSE_PLAN_TREES
900  /* Optional debugging check: pass plan tree through outfuncs/readfuncs */
901  {
902  char *str;
903  PlannedStmt *new_plan;
904 
905  str = nodeToString(plan);
906  new_plan = stringToNodeWithLocations(str);
907  pfree(str);
908 
909  /*
910  * equal() currently does not have routines to compare Plan nodes, so
911  * don't try to test equality here. Perhaps fix someday?
912  */
913 #ifdef NOT_USED
914  /* This checks both outfuncs/readfuncs and the equal() routines... */
915  if (!equal(new_plan, plan))
916  elog(WARNING, "outfuncs/readfuncs failed to produce an equal plan tree");
917  else
918 #endif
919  plan = new_plan;
920  }
921 #endif
922 
923  /*
924  * Print plan if debugging.
925  */
926  if (Debug_print_plan)
927  elog_node_display(LOG, "plan", plan, Debug_pretty_print);
928 
929  TRACE_POSTGRESQL_QUERY_PLAN_DONE();
930 
931  return plan;
932 }
void elog_node_display(int lev, const char *title, const void *obj, bool pretty)
Definition: print.c:72
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3033
void ShowUsage(const char *title)
Definition: postgres.c:4618
#define LOG
Definition: elog.h:26
void ResetUsage(void)
Definition: postgres.c:4611
bool Debug_print_plan
Definition: guc.c:510
void pfree(void *pointer)
Definition: mcxt.c:1056
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:853
#define WARNING
Definition: elog.h:40
PlannedStmt * planner(Query *parse, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: planner.c:267
CmdType commandType
Definition: parsenodes.h:112
#define Assert(condition)
Definition: c.h:738
#define elog(elevel,...)
Definition: elog.h:214
bool Debug_pretty_print
Definition: guc.c:513
char * nodeToString(const void *obj)
Definition: outfuncs.c:4360
#define copyObject(obj)
Definition: nodes.h:645
bool log_planner_stats
Definition: guc.c:516

◆ PostgresMain()

void PostgresMain ( int  argc,
char *  argv[],
const char *  dbname,
const char *  username 
)

Definition at line 3777 of file postgres.c.

References AbortCurrentTransaction(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, am_walsender, BaseInit(), BeginReportingGUCOptions(), BlockSig, buf, ChangeToDataDir(), CHECK_FOR_INTERRUPTS, checkDataDir(), ConfigReloadPending, CreateDataDirLockFile(), debug_query_string, DestDebug, DestNone, DestRemote, die(), disable_all_timeouts(), disable_timeout(), doing_extended_query_message, DoingCommandRead, drop_unnamed_stmt(), DropPreparedStatement(), EmitErrorReport(), enable_timeout_after(), ereport, errcode(), errmsg(), ERROR, error_context_stack, exec_bind_message(), exec_describe_portal_message(), exec_describe_statement_message(), exec_execute_message(), exec_parse_message(), exec_replication_command(), exec_simple_query(), FATAL, finish_xact_command(), FloatExceptionHandler(), FlushErrorState(), forbidden_in_wal_sender(), GetCurrentTimestamp(), GetPortalByName(), HandleFunctionRequest(), HOLD_INTERRUPTS, i, IDLE_IN_TRANSACTION_SESSION_TIMEOUT, IdleInTransactionSessionTimeout, ignore_till_sync, InitializeGUCOptions(), InitializeMaxBackends(), InitializeTimeouts(), InitPostgres(), InitProcess(), InitProcessing, InitStandaloneProcess(), initStringInfo(), InitWalSender(), InvalidateCatalogSnapshotConditionally(), InvalidOid, IsAbortedTransactionBlockState(), IsTransactionOrTransactionBlock(), IsUnderPostmaster, jit_reset_after_error(), LocalProcessControlFile(), Log_disconnections, log_disconnections(), MemoryContextDelete(), MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), MessageContext, MyCancelKey, MyProcPid, MyReplicationSlot, NormalProcessing, notifyInterruptPending, on_proc_exit(), palloc(), PG_exception_stack, PG_SETMASK, PGC_POSTMASTER, PGC_SIGHUP, PgStartTime, pgstat_report_activity(), pgstat_report_stat(), PortalDrop(), PortalErrorCleanup(), PortalIsValid, PostmasterContext, pq_beginmessage(), pq_comm_reset, pq_endmessage(), pq_flush, pq_getmsgbyte(), pq_getmsgend(), pq_getmsgint(), pq_getmsgstring(), pq_is_reading_msg(), pq_putemptymessage(), pq_sendint32(), pqinitmask(), pqsignal(), printf, proc_exit(), process_postgres_switches(), process_session_preload_libraries(), ProcessCompletedNotifies(), ProcessConfigFile(), ProcessNotifyInterrupt(), procsignal_sigusr1_handler(), progname, QueryCancelPending, quickdie(), ReadCommand(), ReadyForQuery(), ReplicationSlotCleanup(), ReplicationSlotRelease(), RESUME_INTERRUPTS, SelectConfigFiles(), set_ps_display(), SetCurrentStatementStartTimestamp(), SetProcessingMode, SIG_DFL, SIG_IGN, SIGCHLD, SIGHUP, SignalHandlerForConfigReload(), SIGPIPE, SIGQUIT, SIGUSR1, SIGUSR2, SPICleanup(), start_xact_command(), STATE_FASTPATH, STATE_IDLE, STATE_IDLEINTRANSACTION, STATE_IDLEINTRANSACTION_ABORTED, StatementCancelHandler(), TopMemoryContext, UnBlockSig, userDoption, username, WalSndErrorCleanup(), WalSndSignals(), whereToSendOutput, and xact_started.

Referenced by BackendRun(), and main().

3780 {
3781  int firstchar;
3782  StringInfoData input_message;
3783  sigjmp_buf local_sigjmp_buf;
3784  volatile bool send_ready_for_query = true;
3785  bool disable_idle_in_transaction_timeout = false;
3786 
3787  /* Initialize startup process environment if necessary. */
3788  if (!IsUnderPostmaster)
3789  InitStandaloneProcess(argv[0]);
3790 
3792 
3793  /*
3794  * Set default values for command-line options.
3795  */
3796  if (!IsUnderPostmaster)
3798 
3799  /*
3800  * Parse command-line options.
3801  */
3803 
3804  /* Must have gotten a database name, or have a default (the username) */
3805  if (dbname == NULL)
3806  {
3807  dbname = username;
3808  if (dbname == NULL)
3809  ereport(FATAL,
3810  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3811  errmsg("%s: no database nor user name specified",
3812  progname)));
3813  }
3814 
3815  /* Acquire configuration parameters, unless inherited from postmaster */
3816  if (!IsUnderPostmaster)
3817  {
3819  proc_exit(1);
3820  }
3821 
3822  /*
3823  * Set up signal handlers and masks.
3824  *
3825  * Note that postmaster blocked all signals before forking child process,
3826  * so there is no race condition whereby we might receive a signal before
3827  * we have set up the handler.
3828  *
3829  * Also note: it's best not to use any signals that are SIG_IGNored in the
3830  * postmaster. If such a signal arrives before we are able to change the
3831  * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
3832  * handler in the postmaster to reserve the signal. (Of course, this isn't
3833  * an issue for signals that are locally generated, such as SIGALRM and
3834  * SIGPIPE.)
3835  */
3836  if (am_walsender)
3837  WalSndSignals();
3838  else
3839  {
3841  pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
3842  pqsignal(SIGTERM, die); /* cancel current query and exit */
3843 
3844  /*
3845  * In a standalone backend, SIGQUIT can be generated from the keyboard
3846  * easily, while SIGTERM cannot, so we make both signals do die()
3847  * rather than quickdie().
3848  */
3849  if (IsUnderPostmaster)
3850  pqsignal(SIGQUIT, quickdie); /* hard crash time */
3851  else
3852  pqsignal(SIGQUIT, die); /* cancel current query and exit */
3853  InitializeTimeouts(); /* establishes SIGALRM handler */
3854 
3855  /*
3856  * Ignore failure to write to frontend. Note: if frontend closes
3857  * connection, we will notice it and exit cleanly when control next
3858  * returns to outer loop. This seems safer than forcing exit in the
3859  * midst of output during who-knows-what operation...
3860  */
3865 
3866  /*
3867  * Reset some signals that are accepted by postmaster but not by
3868  * backend
3869  */
3870  pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
3871  * platforms */
3872  }
3873 
3874  pqinitmask();
3875 
3876  if (IsUnderPostmaster)
3877  {
3878  /* We allow SIGQUIT (quickdie) at all times */
3879  sigdelset(&BlockSig, SIGQUIT);
3880  }
3881 
3882  PG_SETMASK(&BlockSig); /* block everything except SIGQUIT */
3883 
3884  if (!IsUnderPostmaster)
3885  {
3886  /*
3887  * Validate we have been given a reasonable-looking DataDir (if under
3888  * postmaster, assume postmaster did this already).
3889  */
3890  checkDataDir();
3891 
3892  /* Change into DataDir (if under postmaster, was done already) */
3893  ChangeToDataDir();
3894 
3895  /*
3896  * Create lockfile for data directory.
3897  */
3898  CreateDataDirLockFile(false);
3899 
3900  /* read control file (error checking and contains config ) */
3901  LocalProcessControlFile(false);
3902 
3903  /* Initialize MaxBackends (if under postmaster, was done already) */
3905  }
3906 
3907  /* Early initialization */
3908  BaseInit();
3909 
3910  /*
3911  * Create a per-backend PGPROC struct in shared memory, except in the
3912  * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
3913  * this before we can use LWLocks (and in the EXEC_BACKEND case we already
3914  * had to do some stuff with LWLocks).
3915  */
3916 #ifdef EXEC_BACKEND
3917  if (!IsUnderPostmaster)
3918  InitProcess();
3919 #else
3920  InitProcess();
3921 #endif
3922 
3923  /* We need to allow SIGINT, etc during the initial transaction */
3925 
3926  /*
3927  * General initialization.
3928  *
3929  * NOTE: if you are tempted to add code in this vicinity, consider putting
3930  * it inside InitPostgres() instead. In particular, anything that
3931  * involves database access should be there, not here.
3932  */
3934 
3935  /*
3936  * If the PostmasterContext is still around, recycle the space; we don't
3937  * need it anymore after InitPostgres completes. Note this does not trash
3938  * *MyProcPort, because ConnCreate() allocated that space with malloc()
3939  * ... else we'd need to copy the Port data first. Also, subsidiary data
3940  * such as the username isn't lost either; see ProcessStartupPacket().
3941  */
3942  if (PostmasterContext)
3943  {
3945  PostmasterContext = NULL;
3946  }
3947 
3949 
3950  /*
3951  * Now all GUC states are fully set up. Report them to client if
3952  * appropriate.
3953  */
3955 
3956  /*
3957  * Also set up handler to log session end; we have to wait till now to be
3958  * sure Log_disconnections has its final value.
3959  */
3962 
3963  /* Perform initialization specific to a WAL sender process. */
3964  if (am_walsender)
3965  InitWalSender();
3966 
3967  /*
3968  * process any libraries that should be preloaded at backend start (this
3969  * likewise can't be done until GUC settings are complete)
3970  */
3972 
3973  /*
3974  * Send this backend's cancellation info to the frontend.
3975  */
3977  {
3979 
3980  pq_beginmessage(&buf, 'K');
3981  pq_sendint32(&buf, (int32) MyProcPid);
3982  pq_sendint32(&buf, (int32) MyCancelKey);
3983  pq_endmessage(&buf);
3984  /* Need not flush since ReadyForQuery will do it. */
3985  }
3986 
3987  /* Welcome banner for standalone case */
3989  printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
3990 
3991  /*
3992  * Create the memory context we will use in the main loop.
3993  *
3994  * MessageContext is reset once per iteration of the main loop, ie, upon
3995  * completion of processing of each command message from the client.
3996  */
3998  "MessageContext",
4000 
4001  /*
4002  * Create memory context and buffer used for RowDescription messages. As
4003  * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
4004  * frequently executed for ever single statement, we don't want to
4005  * allocate a separate buffer every time.
4006  */
4008  "RowDescriptionContext",
4013 
4014  /*
4015  * Remember stand-alone backend startup time
4016  */
4017  if (!IsUnderPostmaster)
4019 
4020  /*
4021  * POSTGRES main processing loop begins here
4022  *
4023  * If an exception is encountered, processing resumes here so we abort the
4024  * current transaction and start a new one.
4025  *
4026  * You might wonder why this isn't coded as an infinite loop around a
4027  * PG_TRY construct. The reason is that this is the bottom of the
4028  * exception stack, and so with PG_TRY there would be no exception handler
4029  * in force at all during the CATCH part. By leaving the outermost setjmp
4030  * always active, we have at least some chance of recovering from an error
4031  * during error recovery. (If we get into an infinite loop thereby, it
4032  * will soon be stopped by overflow of elog.c's internal state stack.)
4033  *
4034  * Note that we use sigsetjmp(..., 1), so that this function's signal mask
4035  * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
4036  * is essential in case we longjmp'd out of a signal handler on a platform
4037  * where that leaves the signal blocked. It's not redundant with the
4038  * unblock in AbortTransaction() because the latter is only called if we
4039  * were inside a transaction.
4040  */
4041 
4042  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
4043  {
4044  /*
4045  * NOTE: if you are tempted to add more code in this if-block,
4046  * consider the high probability that it should be in
4047  * AbortTransaction() instead. The only stuff done directly here
4048  * should be stuff that is guaranteed to apply *only* for outer-level
4049  * error recovery, such as adjusting the FE/BE protocol status.
4050  */
4051 
4052  /* Since not using PG_TRY, must reset error stack by hand */
4053  error_context_stack = NULL;
4054 
4055  /* Prevent interrupts while cleaning up */
4056  HOLD_INTERRUPTS();
4057 
4058  /*
4059  * Forget any pending QueryCancel request, since we're returning to
4060  * the idle loop anyway, and cancel any active timeout requests. (In
4061  * future we might want to allow some timeout requests to survive, but
4062  * at minimum it'd be necessary to do reschedule_timeouts(), in case
4063  * we got here because of a query cancel interrupting the SIGALRM
4064  * interrupt handler.) Note in particular that we must clear the
4065  * statement and lock timeout indicators, to prevent any future plain
4066  * query cancels from being misreported as timeouts in case we're
4067  * forgetting a timeout cancel.
4068  */
4069  disable_all_timeouts(false);
4070  QueryCancelPending = false; /* second to avoid race condition */
4071 
4072  /* Not reading from the client anymore. */
4073  DoingCommandRead = false;
4074 
4075  /* Make sure libpq is in a good state */
4076  pq_comm_reset();
4077 
4078  /* Report the error to the client and/or server log */
4079  EmitErrorReport();
4080 
4081  /*
4082  * Make sure debug_query_string gets reset before we possibly clobber
4083  * the storage it points at.
4084  */
4085  debug_query_string = NULL;
4086 
4087  /*
4088  * Abort the current transaction in order to recover.
4089  */
4091 
4092  if (am_walsender)
4094 
4096  SPICleanup();
4097 
4098  /*
4099  * We can't release replication slots inside AbortTransaction() as we
4100  * need to be able to start and abort transactions while having a slot
4101  * acquired. But we never need to hold them across top level errors,
4102  * so releasing here is fine. There's another cleanup in ProcKill()
4103  * ensuring we'll correctly cleanup on FATAL errors as well.
4104  */
4105  if (MyReplicationSlot != NULL)
4107 
4108  /* We also want to cleanup temporary slots on error. */
4110 
4112 
4113  /*
4114  * Now return to normal top-level context and clear ErrorContext for
4115  * next time.
4116  */
4118  FlushErrorState();
4119 
4120  /*
4121  * If we were handling an extended-query-protocol message, initiate
4122  * skip till next Sync. This also causes us not to issue
4123  * ReadyForQuery (until we get Sync).
4124  */
4126  ignore_till_sync = true;
4127 
4128  /* We don't have a transaction command open anymore */
4129  xact_started = false;
4130 
4131  /*
4132  * If an error occurred while we were reading a message from the
4133  * client, we have potentially lost track of where the previous
4134  * message ends and the next one begins. Even though we have
4135  * otherwise recovered from the error, we cannot safely read any more
4136  * messages from the client, so there isn't much we can do with the
4137  * connection anymore.
4138  */
4139  if (pq_is_reading_msg())
4140  ereport(FATAL,
4141  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4142  errmsg("terminating connection because protocol synchronization was lost")));
4143 
4144  /* Now we can allow interrupts again */
4146  }
4147 
4148  /* We can now handle ereport(ERROR) */
4149  PG_exception_stack = &local_sigjmp_buf;
4150 
4151  if (!ignore_till_sync)
4152  send_ready_for_query = true; /* initially, or after error */
4153 
4154  /*
4155  * Non-error queries loop here.
4156  */
4157 
4158  for (;;)
4159  {
4160  /*
4161  * At top of loop, reset extended-query-message flag, so that any
4162  * errors encountered in "idle" state don't provoke skip.
4163  */
4165 
4166  /*
4167  * Release storage left over from prior query cycle, and create a new
4168  * query input buffer in the cleared MessageContext.
4169  */
4172 
4173  initStringInfo(&input_message);
4174 
4175  /*
4176  * Also consider releasing our catalog snapshot if any, so that it's
4177  * not preventing advance of global xmin while we wait for the client.
4178  */
4180 
4181  /*
4182  * (1) If we've reached idle state, tell the frontend we're ready for
4183  * a new query.
4184  *
4185  * Note: this includes fflush()'ing the last of the prior output.
4186  *
4187  * This is also a good time to send collected statistics to the
4188  * collector, and to update the PS stats display. We avoid doing
4189  * those every time through the message loop because it'd slow down
4190  * processing of batched messages, and because we don't want to report
4191  * uncommitted updates (that confuses autovacuum). The notification
4192  * processor wants a call too, if we are not in a transaction block.
4193  */
4194  if (send_ready_for_query)
4195  {
4197  {
4198  set_ps_display("idle in transaction (aborted)");
4200 
4201  /* Start the idle-in-transaction timer */
4203  {
4204  disable_idle_in_transaction_timeout = true;
4207  }
4208  }
4210  {
4211  set_ps_display("idle in transaction");
4213 
4214  /* Start the idle-in-transaction timer */
4216  {
4217  disable_idle_in_transaction_timeout = true;
4220  }
4221  }
4222  else
4223  {
4224  /* Send out notify signals and transmit self-notifies */
4226 
4227  /*
4228  * Also process incoming notifies, if any. This is mostly to
4229  * ensure stable behavior in tests: if any notifies were
4230  * received during the just-finished transaction, they'll be
4231  * seen by the client before ReadyForQuery is.
4232  */
4235 
4236  pgstat_report_stat(false);
4237 
4238  set_ps_display("idle");
4240  }
4241 
4243  send_ready_for_query = false;
4244  }
4245 
4246  /*
4247  * (2) Allow asynchronous signals to be executed immediately if they
4248  * come in while we are waiting for client input. (This must be
4249  * conditional since we don't want, say, reads on behalf of COPY FROM
4250  * STDIN doing the same thing.)
4251  */
4252  DoingCommandRead = true;
4253 
4254  /*
4255  * (3) read a command (loop blocks here)
4256  */
4257  firstchar = ReadCommand(&input_message);
4258 
4259  /*
4260  * (4) disable async signal conditions again.
4261  *
4262  * Query cancel is supposed to be a no-op when there is no query in
4263  * progress, so if a query cancel arrived while we were idle, just
4264  * reset QueryCancelPending. ProcessInterrupts() has that effect when
4265  * it's called when DoingCommandRead is set, so check for interrupts
4266  * before resetting DoingCommandRead.
4267  */
4269  DoingCommandRead = false;
4270 
4271  /*
4272  * (5) turn off the idle-in-transaction timeout
4273  */
4274  if (disable_idle_in_transaction_timeout)
4275  {
4277  disable_idle_in_transaction_timeout = false;
4278  }
4279 
4280  /*
4281  * (6) check for any other interesting events that happened while we
4282  * slept.
4283  */
4284  if (ConfigReloadPending)
4285  {
4286  ConfigReloadPending = false;
4288  }
4289 
4290  /*
4291  * (7) process the command. But ignore it if we're skipping till
4292  * Sync.
4293  */
4294  if (ignore_till_sync && firstchar != EOF)
4295  continue;
4296 
4297  switch (firstchar)
4298  {
4299  case 'Q': /* simple query */
4300  {
4301  const char *query_string;
4302 
4303  /* Set statement_timestamp() */
4305 
4306  query_string = pq_getmsgstring(&input_message);
4307  pq_getmsgend(&input_message);
4308 
4309  if (am_walsender)
4310  {
4311  if (!exec_replication_command(query_string))
4312  exec_simple_query(query_string);
4313  }
4314  else
4315  exec_simple_query(query_string);
4316 
4317  send_ready_for_query = true;
4318  }
4319  break;
4320 
4321  case 'P': /* parse */
4322  {
4323  const char *stmt_name;
4324  const char *query_string;
4325  int numParams;
4326  Oid *paramTypes = NULL;
4327 
4328  forbidden_in_wal_sender(firstchar);
4329 
4330  /* Set statement_timestamp() */
4332 
4333  stmt_name = pq_getmsgstring(&input_message);
4334  query_string = pq_getmsgstring(&input_message);
4335  numParams = pq_getmsgint(&input_message, 2);
4336  if (numParams > 0)
4337  {
4338  paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
4339  for (int i = 0; i < numParams; i++)
4340  paramTypes[i] = pq_getmsgint(&input_message, 4);
4341  }
4342  pq_getmsgend(&input_message);
4343 
4344  exec_parse_message(query_string, stmt_name,
4345  paramTypes, numParams);
4346  }
4347  break;
4348 
4349  case 'B': /* bind */
4350  forbidden_in_wal_sender(firstchar);
4351 
4352  /* Set statement_timestamp() */
4354 
4355  /*
4356  * this message is complex enough that it seems best to put
4357  * the field extraction out-of-line
4358  */
4359  exec_bind_message(&input_message);
4360  break;
4361 
4362  case 'E': /* execute */
4363  {
4364  const char *portal_name;
4365  int max_rows;
4366 
4367  forbidden_in_wal_sender(firstchar);
4368 
4369  /* Set statement_timestamp() */
4371 
4372  portal_name = pq_getmsgstring(&input_message);
4373  max_rows = pq_getmsgint(&input_message, 4);
4374  pq_getmsgend(&input_message);
4375 
4376  exec_execute_message(portal_name, max_rows);
4377  }
4378  break;
4379 
4380  case 'F': /* fastpath function call */
4381  forbidden_in_wal_sender(firstchar);
4382 
4383  /* Set statement_timestamp() */
4385 
4386  /* Report query to various monitoring facilities. */
4388  set_ps_display("<FASTPATH>");
4389 
4390  /* start an xact for this function invocation */
4392 
4393  /*
4394  * Note: we may at this point be inside an aborted
4395  * transaction. We can't throw error for that until we've
4396  * finished reading the function-call message, so
4397  * HandleFunctionRequest() must check for it after doing so.
4398  * Be careful not to do anything that assumes we're inside a
4399  * valid transaction here.
4400  */
4401 
4402  /* switch back to message context */
4404 
4405  HandleFunctionRequest(&input_message);
4406 
4407  /* commit the function-invocation transaction */
4409 
4410  send_ready_for_query = true;
4411  break;
4412 
4413  case 'C': /* close */
4414  {
4415  int close_type;
4416  const char *close_target;
4417 
4418  forbidden_in_wal_sender(firstchar);
4419 
4420  close_type = pq_getmsgbyte(&input_message);
4421  close_target = pq_getmsgstring(&input_message);
4422  pq_getmsgend(&input_message);
4423 
4424  switch (close_type)
4425  {
4426  case 'S':
4427  if (close_target[0] != '\0')
4428  DropPreparedStatement(close_target, false);
4429  else
4430  {
4431  /* special-case the unnamed statement */
4433  }
4434  break;
4435  case 'P':
4436  {
4437  Portal portal;
4438 
4439  portal = GetPortalByName(close_target);
4440  if (PortalIsValid(portal))
4441  PortalDrop(portal, false);
4442  }
4443  break;
4444  default:
4445  ereport(ERROR,
4446  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4447  errmsg("invalid CLOSE message subtype %d",
4448  close_type)));
4449  break;
4450  }
4451 
4453  pq_putemptymessage('3'); /* CloseComplete */
4454  }
4455  break;
4456 
4457  case 'D': /* describe */
4458  {
4459  int describe_type;
4460  const char *describe_target;
4461 
4462  forbidden_in_wal_sender(firstchar);
4463 
4464  /* Set statement_timestamp() (needed for xact) */
4466 
4467  describe_type = pq_getmsgbyte(&input_message);
4468  describe_target = pq_getmsgstring(&input_message);
4469  pq_getmsgend(&input_message);
4470 
4471  switch (describe_type)
4472  {
4473  case 'S':
4474  exec_describe_statement_message(describe_target);
4475  break;
4476  case 'P':
4477  exec_describe_portal_message(describe_target);
4478  break;
4479  default:
4480  ereport(ERROR,
4481  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4482  errmsg("invalid DESCRIBE message subtype %d",
4483  describe_type)));
4484  break;
4485  }
4486  }
4487  break;
4488 
4489  case 'H': /* flush */
4490  pq_getmsgend(&input_message);
4492  pq_flush();
4493  break;
4494 
4495  case 'S': /* sync */
4496  pq_getmsgend(&input_message);
4498  send_ready_for_query = true;
4499  break;
4500 
4501  /*
4502  * 'X' means that the frontend is closing down the socket. EOF
4503  * means unexpected loss of frontend connection. Either way,
4504  * perform normal shutdown.
4505  */
4506  case 'X':
4507  case EOF:
4508 
4509  /*
4510  * Reset whereToSendOutput to prevent ereport from attempting
4511  * to send any more messages to client.
4512  */
4515 
4516  /*
4517  * NOTE: if you are tempted to add more code here, DON'T!
4518  * Whatever you had in mind to do should be set up as an
4519  * on_proc_exit or on_shmem_exit callback, instead. Otherwise
4520  * it will fail to be called during other backend-shutdown
4521  * scenarios.
4522  */
4523  proc_exit(0);
4524 
4525  case 'd': /* copy data */
4526  case 'c': /* copy done */
4527  case 'f': /* copy fail */
4528 
4529  /*
4530  * Accept but ignore these messages, per protocol spec; we
4531  * probably got here because a COPY failed, and the frontend
4532  * is still sending data.
4533  */
4534  break;
4535 
4536  default:
4537  ereport(FATAL,
4538  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4539  errmsg("invalid frontend message type %d",
4540  firstchar)));
4541  }
4542  } /* end of input-reading loop */
4543 }
void InitializeTimeouts(void)
Definition: timeout.c:346
void AbortCurrentTransaction(void)
Definition: xact.c:3183
static void exec_describe_portal_message(const char *portal_name)
Definition: postgres.c:2583
#define SIGQUIT
Definition: win32_port.h:154
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define AllocSetContextCreate
Definition: memutils.h:170
volatile sig_atomic_t QueryCancelPending
Definition: globals.c:31
void BeginReportingGUCOptions(void)
Definition: guc.c:6209
int MyProcPid
Definition: globals.c:40
#define pq_flush()
Definition: libpq.h:39
static int ReadCommand(StringInfo inBuf)
Definition: postgres.c:505
static void finish_xact_command(void)
Definition: postgres.c:2655
void ProcessConfigFile(GucContext context)
bool exec_replication_command(const char *cmd_string)
Definition: walsender.c:1526
#define SIGUSR1
Definition: win32_port.h:165
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1574
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:305
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:3132
#define SIGCHLD
Definition: win32_port.h:163
const char * pq_getmsgstring(StringInfo msg)
Definition: pqformat.c:581
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition: interrupt.c:56
void InitStandaloneProcess(const char *argv0)
Definition: miscinit.c:145
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:376
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void SPICleanup(void)
Definition: spi.c:350
static void forbidden_in_wal_sender(char firstchar)
Definition: postgres.c:4553
void proc_exit(int code)
Definition: ipc.c:104
int errcode(int sqlerrcode)
Definition: elog.c:610
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4674
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:390
#define SetProcessingMode(mode)
Definition: miscadmin.h:398
void BaseInit(void)
Definition: postinit.c:548
#define printf(...)
Definition: port.h:199
void checkDataDir(void)
Definition: miscinit.c:274
#define SIGPIPE
Definition: win32_port.h:158
#define SIGUSR2
Definition: win32_port.h:166
unsigned int Oid
Definition: postgres_ext.h:31
const char * progname
Definition: pg_standby.c:36
void FlushErrorState(void)
Definition: elog.c:1568
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
void pq_beginmessage(StringInfo buf, char msgtype)
Definition: pqformat.c:87
void StatementCancelHandler(SIGNAL_ARGS)
Definition: postgres.c:2857
signed int int32
Definition: c.h:355
static void exec_execute_message(const char *portal_name, long max_rows)
Definition: postgres.c:2041
static void log_disconnections(int code, Datum arg)
Definition: postgres.c:4720
void jit_reset_after_error(void)
Definition: jit.c:128
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:118
ErrorContextCallback * error_context_stack
Definition: elog.c:92
void set_ps_display(const char *activity)
Definition: ps_status.c:349
static void pq_sendint32(StringInfo buf, uint32 i)
Definition: pqformat.h:145
void pqinitmask(void)
Definition: pqsignal.c:41
bool am_walsender
Definition: walsender.c:115
void disable_all_timeouts(bool keep_indicators)
Definition: timeout.c:598
#define ERROR
Definition: elog.h:43
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1245
void ProcessNotifyInterrupt(void)
Definition: async.c:1902
bool pq_is_reading_msg(void)
Definition: pqcomm.c:1237
int IdleInTransactionSessionTimeout
Definition: proc.c:63
int32 MyCancelKey
Definition: globals.c:44
void WalSndSignals(void)
Definition: walsender.c:3047
#define FATAL
Definition: elog.h:52
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
void InitProcess(void)
Definition: proc.c:304
Definition: dest.h:89
static char * buf
Definition: pg_test_fsync.c:67
bool IsUnderPostmaster
Definition: globals.c:109
static void exec_bind_message(StringInfo input_message)
Definition: postgres.c:1606
Definition: dest.h:90
#define SIGHUP
Definition: win32_port.h:153
void LocalProcessControlFile(bool reset)
Definition: xlog.c:5033
void ChangeToDataDir(void)
Definition: miscinit.c:388
void ReplicationSlotRelease(void)
Definition: slot.c:476
sigset_t UnBlockSig
Definition: pqsignal.c:22
void PortalErrorCleanup(void)
Definition: portalmem.c:910
static bool xact_started
Definition: postgres.c:133
void InitWalSender(void)
MemoryContext TopMemoryContext
Definition: mcxt.c:44
Definition: guc.h:72
#define SIG_IGN
Definition: win32_port.h:150
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
const char * debug_query_string
Definition: postgres.c:88
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
static void exec_parse_message(const char *query_string, const char *stmt_name, Oid *paramTypes, int numParams)
Definition: postgres.c:1349
#define PortalIsValid(p)
Definition: portal.h:203
static void start_xact_command(void)
Definition: postgres.c:2635
static bool doing_extended_query_message
Definition: postgres.c:146
sigset_t BlockSig
Definition: pqsignal.c:22
void process_session_preload_libraries(void)
Definition: miscinit.c:1642
void WalSndErrorCleanup(void)
Definition: walsender.c:296
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:5537
void EmitErrorReport(void)
Definition: elog.c:1423
static StringInfoData row_description_buf
Definition: postgres.c:168
TimestampTz PgStartTime
Definition: timestamp.c:50
static char * username
Definition: initdb.c:133
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:144
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname, bool override_allow_connections)
Definition: postinit.c:590
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
int pq_getmsgbyte(StringInfo msg)
Definition: pqformat.c:401
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:435
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
#define pq_comm_reset()
Definition: libpq.h:38
#define SIG_DFL
Definition: win32_port.h:148
void ProcessCompletedNotifies(void)
Definition: async.c:1218
void HandleFunctionRequest(StringInfo msgBuf)
Definition: fastpath.c:259
void InvalidateCatalogSnapshotConditionally(void)
Definition: snapmgr.c:533
static bool DoingCommandRead
Definition: postgres.c:140
void InitializeMaxBackends(void)
Definition: postinit.c:526
char * dbname
Definition: streamutil.c:50
MemoryContext MessageContext
Definition: mcxt.c:48
sigjmp_buf * PG_exception_stack
Definition: elog.c:94
static const char * userDoption
Definition: postgres.c:157
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:818
void * palloc(Size size)
Definition: mcxt.c:949
int errmsg(const char *fmt,...)
Definition: elog.c:824
void PortalDrop(Portal portal, bool isTopCommit)
Definition: portalmem.c:467
void ReadyForQuery(CommandDest dest)
Definition: dest.c:270
void pq_endmessage(StringInfo buf)
Definition: pqformat.c:298
void die(SIGNAL_ARGS)
Definition: postgres.c:2826
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:116
volatile sig_atomic_t ConfigReloadPending
Definition: interrupt.c:26
int i
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:2878
static void drop_unnamed_stmt(void)
Definition: postgres.c:2734
void ReplicationSlotCleanup(void)
Definition: slot.c:531
volatile sig_atomic_t notifyInterruptPending
Definition: async.c:418
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition: pqformat.c:417
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
bool Log_disconnections
Definition: postgres.c:94
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition: postgres.c:3518
void pq_getmsgend(StringInfo msg)
Definition: pqformat.c:637
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:532
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:551
CommandDest whereToSendOutput
Definition: postgres.c:91
static bool ignore_till_sync
Definition: postgres.c:147
static MemoryContext row_description_context
Definition: postgres.c:167
void quickdie(SIGNAL_ARGS)
Definition: postgres.c:2759
MemoryContext PostmasterContext
Definition: mcxt.c:46
static void exec_simple_query(const char *query_string)
Definition: postgres.c:983
void InitializeGUCOptions(void)
Definition: guc.c:5315
void pgstat_report_stat(bool force)
Definition: pgstat.c:839
void DropPreparedStatement(const char *stmt_name, bool showError)
Definition: prepare.c:554
static void exec_describe_statement_message(const char *stmt_name)
Definition: postgres.c:2488

◆ process_postgres_switches()

void process_postgres_switches ( int  argc,
char *  argv[],
GucContext  ctx,
const char **  dbname 
)

Definition at line 3518 of file postgres.c.

References EchoQuery, ereport, errcode(), errhint(), errmsg(), ERROR, FATAL, flag(), free, FrontendProtocol, get_stats_option_name(), getopt(), IsBinaryUpgrade, IsUnderPostmaster, MAXPGPATH, name, optarg, opterr, optind, OutputFileName, ParseLongOption(), PGC_POSTMASTER, PGC_S_ARGV, PGC_S_CLIENT, progname, set_debug_options(), set_plan_disabling_options(), SetConfigOption(), strlcpy(), userDoption, UseSemiNewlineNewline, and value.

Referenced by PostgresMain(), and process_startup_options().

3520 {
3521  bool secure = (ctx == PGC_POSTMASTER);
3522  int errs = 0;
3523  GucSource gucsource;
3524  int flag;
3525 
3526  if (secure)
3527  {
3528  gucsource = PGC_S_ARGV; /* switches came from command line */
3529 
3530  /* Ignore the initial --single argument, if present */
3531  if (argc > 1 && strcmp(argv[1], "--single") == 0)
3532  {
3533  argv++;
3534  argc--;
3535  }
3536  }
3537  else
3538  {
3539  gucsource = PGC_S_CLIENT; /* switches came from client */
3540  }
3541 
3542 #ifdef HAVE_INT_OPTERR
3543 
3544  /*
3545  * Turn this off because it's either printed to stderr and not the log
3546  * where we'd want it, or argv[0] is now "--single", which would make for
3547  * a weird error message. We print our own error message below.
3548  */
3549  opterr = 0;
3550 #endif
3551 
3552  /*
3553  * Parse command-line options. CAUTION: keep this in sync with
3554  * postmaster/postmaster.c (the option sets should not conflict) and with
3555  * the common help() function in main/main.c.
3556  */
3557  while ((flag = getopt(argc, argv, "B:bc:C:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:v:W:-:")) != -1)
3558  {
3559  switch (flag)
3560  {
3561  case 'B':
3562  SetConfigOption("shared_buffers", optarg, ctx, gucsource);
3563  break;
3564 
3565  case 'b':
3566  /* Undocumented flag used for binary upgrades */
3567  if (secure)
3568  IsBinaryUpgrade = true;
3569  break;
3570 
3571  case 'C':
3572  /* ignored for consistency with the postmaster */
3573  break;
3574 
3575  case 'D':
3576  if (secure)
3577  userDoption = strdup(optarg);
3578  break;
3579 
3580  case 'd':
3581  set_debug_options(atoi(optarg), ctx, gucsource);
3582  break;
3583 
3584  case 'E':
3585  if (secure)
3586  EchoQuery = true;
3587  break;
3588 
3589  case 'e':
3590  SetConfigOption("datestyle", "euro", ctx, gucsource);
3591  break;
3592 
3593  case 'F':
3594  SetConfigOption("fsync", "false", ctx, gucsource);
3595  break;
3596 
3597  case 'f':
3598  if (!set_plan_disabling_options(optarg, ctx, gucsource))
3599  errs++;
3600  break;
3601 
3602  case 'h':
3603  SetConfigOption("listen_addresses", optarg, ctx, gucsource);
3604  break;
3605 
3606  case 'i':
3607  SetConfigOption("listen_addresses", "*", ctx, gucsource);
3608  break;
3609 
3610  case 'j':
3611  if (secure)
3612  UseSemiNewlineNewline = true;
3613  break;
3614 
3615  case 'k':
3616  SetConfigOption("unix_socket_directories", optarg, ctx, gucsource);
3617  break;
3618 
3619  case 'l':
3620  SetConfigOption("ssl", "true", ctx, gucsource);
3621  break;
3622 
3623  case 'N':
3624  SetConfigOption("max_connections", optarg, ctx, gucsource);
3625  break;
3626 
3627  case 'n':
3628  /* ignored for consistency with postmaster */
3629  break;
3630 
3631  case 'O':
3632  SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
3633  break;
3634 
3635  case 'o':
3636  errs++;
3637  break;
3638 
3639  case 'P':
3640  SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
3641  break;
3642 
3643  case 'p':
3644  SetConfigOption("port", optarg, ctx, gucsource);
3645  break;
3646 
3647  case 'r':
3648  /* send output (stdout and stderr) to the given file */
3649  if (secure)
3651  break;
3652 
3653  case 'S':
3654  SetConfigOption("work_mem", optarg, ctx, gucsource);
3655  break;
3656 
3657  case 's':
3658  SetConfigOption("log_statement_stats", "true", ctx, gucsource);
3659  break;
3660 
3661  case 'T':
3662  /* ignored for consistency with the postmaster */
3663  break;
3664 
3665  case 't':
3666  {
3667  const char *tmp = get_stats_option_name(optarg);
3668 
3669  if (tmp)
3670  SetConfigOption(tmp, "true", ctx, gucsource);
3671  else
3672  errs++;
3673  break;
3674  }
3675 
3676  case 'v':
3677 
3678  /*
3679  * -v is no longer used in normal operation, since
3680  * FrontendProtocol is already set before we get here. We keep
3681  * the switch only for possible use in standalone operation,
3682  * in case we ever support using normal FE/BE protocol with a
3683  * standalone backend.
3684  */
3685  if (secure)
3687  break;
3688 
3689  case 'W':
3690  SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
3691  break;
3692 
3693  case 'c':
3694  case '-':
3695  {
3696  char *name,
3697  *value;
3698 
3699  ParseLongOption(optarg, &name, &value);
3700  if (!value)
3701  {
3702  if (flag == '-')
3703  ereport(ERROR,
3704  (errcode(ERRCODE_SYNTAX_ERROR),
3705  errmsg("--%s requires a value",
3706  optarg)));
3707  else
3708  ereport(ERROR,
3709  (errcode(ERRCODE_SYNTAX_ERROR),
3710  errmsg("-c %s requires a value",
3711  optarg)));
3712  }
3713  SetConfigOption(name, value, ctx, gucsource);
3714  free(name);
3715  if (value)
3716  free(value);
3717  break;
3718  }
3719 
3720  default:
3721  errs++;
3722  break;
3723  }
3724 
3725  if (errs)
3726  break;
3727  }
3728 
3729  /*
3730  * Optional database name should be there only if *dbname is NULL.
3731  */
3732  if (!errs && dbname && *dbname == NULL && argc - optind >= 1)
3733  *dbname = strdup(argv[optind++]);
3734 
3735  if (errs || argc != optind)
3736  {
3737  if (errs)
3738  optind--; /* complain about the previous argument */
3739 
3740  /* spell the error message a bit differently depending on context */
3741  if (IsUnderPostmaster)
3742  ereport(FATAL,
3743  errcode(ERRCODE_SYNTAX_ERROR),
3744  errmsg("invalid command-line argument for server process: %s", argv[optind]),
3745  errhint("Try \"%s --help\" for more information.", progname));
3746  else
3747  ereport(FATAL,
3748  errcode(ERRCODE_SYNTAX_ERROR),
3749  errmsg("%s: invalid command-line argument: %s",
3750  progname, argv[optind]),
3751  errhint("Try \"%s --help\" for more information.", progname));
3752  }
3753 
3754  /*
3755  * Reset getopt(3) library so that it will work correctly in subprocesses
3756  * or when this function is called a second time with another array.
3757  */
3758  optind = 1;
3759 #ifdef HAVE_INT_OPTRESET
3760  optreset = 1; /* some systems need this too */
3761 #endif
3762 }
int errhint(const char *fmt,...)
Definition: elog.c:1071
void ParseLongOption(const char *string, char **name, char **value)
Definition: guc.c:10500
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition: postgres.c:3436
int errcode(int sqlerrcode)
Definition: elog.c:610
const char * get_stats_option_name(const char *arg)
Definition: postgres.c:3478
void set_debug_options(int debug_flag, GucContext context, GucSource source)
Definition: postgres.c:3407
const char * progname
Definition: pg_standby.c:36
bool IsBinaryUpgrade
Definition: globals.c:110
int getopt(int nargc, char *const *nargv, const char *ostr)
Definition: getopt.c:71
GucSource
Definition: guc.h:105
int optind
Definition: getopt.c:50
#define ERROR
Definition: elog.h:43
#define FATAL
Definition: elog.h:52
#define MAXPGPATH
char OutputFileName[MAXPGPATH]
Definition: globals.c:70
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:7685
bool IsUnderPostmaster
Definition: globals.c:109
char * flag(int b)
Definition: test-ctype.c:33
int opterr
Definition: getopt.c:49
uint32 ProtocolVersion
Definition: pqcomm.h:113
static struct @143 value
#define ereport(elevel,...)
Definition: elog.h:144
#define free(a)
Definition: header.h:65
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
char * dbname
Definition: streamutil.c:50
const char * name
Definition: encode.c:561
static bool EchoQuery
Definition: postgres.c:158
static const char * userDoption
Definition: postgres.c:157
static bool UseSemiNewlineNewline
Definition: postgres.c:159
int errmsg(const char *fmt,...)
Definition: elog.c:824
char * optarg
Definition: getopt.c:52
ProtocolVersion FrontendProtocol
Definition: globals.c:28

◆ ProcessClientReadInterrupt()

void ProcessClientReadInterrupt ( bool  blocked)

Definition at line 526 of file postgres.c.

References catchupInterruptPending, CHECK_FOR_INTERRUPTS, DoingCommandRead, MyLatch, notifyInterruptPending, ProcDiePending, ProcessCatchupInterrupt(), ProcessNotifyInterrupt(), and SetLatch().

Referenced by interactive_getc(), and secure_read().

527 {
528  int save_errno = errno;
529 
530  if (DoingCommandRead)
531  {
532  /* Check for general interrupts that arrived before/while reading */
534 
535  /* Process sinval catchup interrupts, if any */
538 
539  /* Process notify interrupts, if any */
542  }
543  else if (ProcDiePending)
544  {
545  /*
546  * We're dying. If there is no data available to read, then it's safe
547  * (and sane) to handle that now. If we haven't tried to read yet,
548  * make sure the process latch is set, so that if there is no data
549  * then we'll come back here and die. If we're done reading, also
550  * make sure the process latch is set, as we might've undesirably
551  * cleared it while reading.
552  */
553  if (blocked)
555  else
556  SetLatch(MyLatch);
557  }
558 
559  errno = save_errno;
560 }
void ProcessCatchupInterrupt(void)
Definition: sinval.c:176
void SetLatch(Latch *latch)
Definition: latch.c:457
void ProcessNotifyInterrupt(void)
Definition: async.c:1902
volatile sig_atomic_t ProcDiePending
Definition: globals.c:32
static bool DoingCommandRead
Definition: postgres.c:140
struct Latch * MyLatch
Definition: globals.c:54
volatile sig_atomic_t notifyInterruptPending
Definition: async.c:418
volatile sig_atomic_t catchupInterruptPending
Definition: sinval.c:41
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99

◆ ProcessClientWriteInterrupt()

void ProcessClientWriteInterrupt ( bool  blocked)

Definition at line 572 of file postgres.c.

References CHECK_FOR_INTERRUPTS, CritSectionCount, DestNone, DestRemote, InterruptHoldoffCount, MyLatch, ProcDiePending, SetLatch(), and whereToSendOutput.

Referenced by secure_write().

573 {
574  int save_errno = errno;
575 
576  if (ProcDiePending)
577  {
578  /*
579  * We're dying. If it's not possible to write, then we should handle
580  * that immediately, else a stuck client could indefinitely delay our
581  * response to the signal. If we haven't tried to write yet, make
582  * sure the process latch is set, so that if the write would block
583  * then we'll come back here and die. If we're done writing, also
584  * make sure the process latch is set, as we might've undesirably
585  * cleared it while writing.
586  */
587  if (blocked)
588  {
589  /*
590  * Don't mess with whereToSendOutput if ProcessInterrupts wouldn't
591  * do anything.
592  */
593  if (InterruptHoldoffCount == 0 && CritSectionCount == 0)
594  {
595  /*
596  * We don't want to send the client the error message, as a)
597  * that would possibly block again, and b) it would likely
598  * lead to loss of protocol sync because we may have already
599  * sent a partial protocol message.
600  */
603 
605  }
606  }
607  else
608  SetLatch(MyLatch);
609  }
610 
611  errno = save_errno;
612 }
volatile uint32 InterruptHoldoffCount
Definition: globals.c:36
void SetLatch(Latch *latch)
Definition: latch.c:457
Definition: dest.h:89
volatile uint32 CritSectionCount
Definition: globals.c:38
volatile sig_atomic_t ProcDiePending
Definition: globals.c:32
struct Latch * MyLatch
Definition: globals.c:54
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
CommandDest whereToSendOutput
Definition: postgres.c:91

◆ quickdie()

void quickdie ( SIGNAL_ARGS  )

Definition at line 2759 of file postgres.c.

References BlockSig, ClientAuthInProgress, DestNone, DestRemote, ereport, errcode(), errdetail(), errhint(), errmsg(), HOLD_INTERRUPTS, PG_SETMASK, SIGQUIT, WARNING, and whereToSendOutput.

Referenced by AutoVacLauncherMain(), AutoVacWorkerMain(), PostgresMain(), and WalSndSignals().

2760 {
2761  sigaddset(&BlockSig, SIGQUIT); /* prevent nested calls */
2762  PG_SETMASK(&BlockSig);
2763 
2764  /*
2765  * Prevent interrupts while exiting; though we just blocked signals that
2766  * would queue new interrupts, one may have been pending. We don't want a
2767  * quickdie() downgraded to a mere query cancel.
2768  */
2769  HOLD_INTERRUPTS();
2770 
2771  /*
2772  * If we're aborting out of client auth, don't risk trying to send
2773  * anything to the client; we will likely violate the protocol, not to
2774  * mention that we may have interrupted the guts of OpenSSL or some
2775  * authentication library.
2776  */
2779 
2780  /*
2781  * Notify the client before exiting, to give a clue on what happened.
2782  *
2783  * It's dubious to call ereport() from a signal handler. It is certainly
2784  * not async-signal safe. But it seems better to try, than to disconnect
2785  * abruptly and leave the client wondering what happened. It's remotely
2786  * possible that we crash or hang while trying to send the message, but
2787  * receiving a SIGQUIT is a sign that something has already gone badly
2788  * wrong, so there's not much to lose. Assuming the postmaster is still
2789  * running, it will SIGKILL us soon if we get stuck for some reason.
2790  *
2791  * Ideally this should be ereport(FATAL), but then we'd not get control
2792  * back...
2793  */
2794  ereport(WARNING,
2795  (errcode(ERRCODE_CRASH_SHUTDOWN),
2796  errmsg("terminating connection because of crash of another server process"),
2797  errdetail("The postmaster has commanded this server process to roll back"
2798  " the current transaction and exit, because another"
2799  " server process exited abnormally and possibly corrupted"
2800  " shared memory."),
2801  errhint("In a moment you should be able to reconnect to the"
2802  " database and repeat your command.")));
2803 
2804  /*
2805  * We DO NOT want to run proc_exit() or atexit() callbacks -- we're here
2806  * because shared memory may be corrupted, so we don't want to try to
2807  * clean up our transaction. Just nail the windows shut and get out of
2808  * town. The callbacks wouldn't be safe to run from a signal handler,
2809  * anyway.
2810  *
2811  * Note we do _exit(2) not _exit(0). This is to force the postmaster into
2812  * a system reset cycle if someone sends a manual SIGQUIT to a random
2813  * backend. This is necessary precisely because we don't clean up our
2814  * shared memory state. (The "dead man switch" mechanism in pmsignal.c
2815  * should ensure the postmaster sees this as a crash, too, but no harm in
2816  * being doubly sure.)
2817  */
2818  _exit(2);
2819 }
#define SIGQUIT
Definition: win32_port.h:154
int errhint(const char *fmt,...)
Definition: elog.c:1071
int errcode(int sqlerrcode)
Definition: elog.c:610
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
bool ClientAuthInProgress
Definition: postmaster.c:352
Definition: dest.h:89
int errdetail(const char *fmt,...)
Definition: elog.c:957
#define WARNING
Definition: elog.h:40
sigset_t BlockSig
Definition: pqsignal.c:22
#define ereport(elevel,...)
Definition: elog.h:144
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:116
CommandDest whereToSendOutput
Definition: postgres.c:91

◆ RecoveryConflictInterrupt()

void RecoveryConflictInterrupt ( ProcSignalReason  reason)

Definition at line 2896 of file postgres.c.

References Assert, elog, FATAL, HoldingBufferPinThatDelaysRecovery(), InterruptPending, IsAbortedTransactionBlockState(), IsSubTransaction(), IsTransactionOrTransactionBlock(), IsWaitingForLock(), MyLatch, MyProc, proc_exit_inprogress, ProcDiePending, PROCSIG_RECOVERY_CONFLICT_BUFFERPIN, PROCSIG_RECOVERY_CONFLICT_DATABASE, PROCSIG_RECOVERY_CONFLICT_LOCK, PROCSIG_RECOVERY_CONFLICT_SNAPSHOT, PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK, PROCSIG_RECOVERY_CONFLICT_TABLESPACE, QueryCancelPending, PGPROC::recoveryConflictPending, RecoveryConflictPending, RecoveryConflictReason, RecoveryConflictRetryable, and SetLatch().

Referenced by procsignal_sigusr1_handler().

2897 {
2898  int save_errno = errno;
2899 
2900  /*
2901  * Don't joggle the elbow of proc_exit
2902  */
2903  if (!proc_exit_inprogress)
2904  {
2905  RecoveryConflictReason = reason;
2906  switch (reason)
2907  {
2909 
2910  /*
2911  * If we aren't waiting for a lock we can never deadlock.
2912  */
2913  if (!IsWaitingForLock())
2914  return;
2915 
2916  /* Intentional fall through to check wait for pin */
2917  /* FALLTHROUGH */
2918 
2920 
2921  /*
2922  * If we aren't blocking the Startup process there is nothing
2923  * more to do.
2924  */
2926  return;
2927 
2929 
2930  /* Intentional fall through to error handling */
2931  /* FALLTHROUGH */
2932 
2936 
2937  /*
2938  * If we aren't in a transaction any longer then ignore.
2939  */
2941  return;
2942 
2943  /*
2944  * If we can abort just the current subtransaction then we are
2945  * OK to throw an ERROR to resolve the conflict. Otherwise
2946  * drop through to the FATAL case.
2947  *
2948  * XXX other times that we can throw just an ERROR *may* be
2949  * PROCSIG_RECOVERY_CONFLICT_LOCK if no locks are held in
2950  * parent transactions
2951  *
2952  * PROCSIG_RECOVERY_CONFLICT_SNAPSHOT if no snapshots are held
2953  * by parent transactions and the transaction is not
2954  * transaction-snapshot mode
2955  *
2956  * PROCSIG_RECOVERY_CONFLICT_TABLESPACE if no temp files or
2957  * cursors open in parent transactions
2958  */
2959  if (!IsSubTransaction())
2960  {
2961  /*
2962  * If we already aborted then we no longer need to cancel.
2963  * We do this here since we do not wish to ignore aborted
2964  * subtransactions, which must cause FATAL, currently.
2965  */
2967  return;
2968 
2969  RecoveryConflictPending = true;
2970  QueryCancelPending = true;
2971  InterruptPending = true;
2972  break;
2973  }
2974 
2975  /* Intentional fall through to session cancel */
2976  /* FALLTHROUGH */
2977 
2979  RecoveryConflictPending = true;
2980  ProcDiePending = true;
2981  InterruptPending = true;
2982  break;
2983 
2984  default:
2985  elog(FATAL, "unrecognized conflict mode: %d",
2986  (int) reason);
2987  }
2988 
2990 
2991  /*
2992  * All conflicts apart from database cause dynamic errors where the
2993  * command or transaction can be retried at a later point with some
2994  * potential for success. No need to reset this, since non-retryable
2995  * conflict errors are currently FATAL.
2996  */
2997  if (reason == PROCSIG_RECOVERY_CONFLICT_DATABASE)
2998  RecoveryConflictRetryable = false;
2999  }
3000 
3001  /*
3002  * Set the process latch. This function essentially emulates signal
3003  * handlers like die() and StatementCancelHandler() and it seems prudent
3004  * to behave similarly as they do.
3005  */
3006  SetLatch(MyLatch);
3007 
3008  errno = save_errno;
3009 }
bool IsWaitingForLock(void)
Definition: proc.c:694
volatile sig_atomic_t QueryCancelPending
Definition: globals.c:31
PGPROC * MyProc
Definition: proc.c:67
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:376
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4674
void SetLatch(Latch *latch)
Definition: latch.c:457
#define FATAL
Definition: elog.h:52
bool recoveryConflictPending
Definition: proc.h:134
static ProcSignalReason RecoveryConflictReason
Definition: postgres.c:164
static bool RecoveryConflictPending
Definition: postgres.c:162
static bool RecoveryConflictRetryable
Definition: postgres.c:163
#define Assert(condition)
Definition: c.h:738
volatile sig_atomic_t ProcDiePending
Definition: globals.c:32
bool proc_exit_inprogress
Definition: ipc.c:40
bool HoldingBufferPinThatDelaysRecovery(void)
Definition: bufmgr.c:3890
volatile sig_atomic_t InterruptPending
Definition: globals.c:30
bool IsSubTransaction(void)
Definition: xact.c:4729
#define elog(elevel,...)
Definition: elog.h:214
struct Latch * MyLatch
Definition: globals.c:54

◆ ResetUsage()

void ResetUsage ( void  )

Definition at line 4611 of file postgres.c.

References getrusage(), gettimeofday(), RUSAGE_SELF, Save_r, and Save_t.

Referenced by _bt_leader_participate_as_worker(), _bt_leafbuild(), _bt_parallel_build_main(), _SPI_pquery(), btbuild(), exec_bind_message(), exec_execute_message(), exec_parse_message(), exec_simple_query(), pg_analyze_and_rewrite(), pg_analyze_and_rewrite_params(), pg_parse_query(), pg_plan_query(), pg_rewrite_query(), PortalRun(), and PortalRunMulti().

4612 {
4614  gettimeofday(&Save_t, NULL);
4615 }
int gettimeofday(struct timeval *tp, struct timezone *tzp)
Definition: gettimeofday.c:104
static struct rusage Save_r
Definition: postgres.c:4607
int getrusage(int who, struct rusage *rusage)
Definition: getrusage.c:31
static struct timeval Save_t
Definition: postgres.c:4608
#define RUSAGE_SELF
Definition: rusagestub.h:23

◆ set_debug_options()

void set_debug_options ( int  debug_flag,
GucContext  context,
GucSource  source 
)

Definition at line 3407 of file postgres.c.

References PGC_POSTMASTER, SetConfigOption(), and sprintf.

Referenced by PostmasterMain(), and process_postgres_switches().

3408 {
3409  if (debug_flag > 0)
3410  {
3411  char debugstr[64];
3412 
3413  sprintf(debugstr, "debug%d", debug_flag);
3414  SetConfigOption("log_min_messages", debugstr, context, source);
3415  }
3416  else
3417  SetConfigOption("log_min_messages", "notice", context, source);
3418 
3419  if (debug_flag >= 1 && context == PGC_POSTMASTER)
3420  {
3421  SetConfigOption("log_connections", "true", context, source);
3422  SetConfigOption("log_disconnections", "true", context, source);
3423  }
3424  if (debug_flag >= 2)
3425  SetConfigOption("log_statement", "all", context, source);
3426  if (debug_flag >= 3)
3427  SetConfigOption("debug_print_parse", "true", context, source);
3428  if (debug_flag >= 4)
3429  SetConfigOption("debug_print_plan", "true", context, source);
3430  if (debug_flag >= 5)
3431  SetConfigOption("debug_print_rewritten", "true", context, source);
3432 }
#define sprintf
Definition: port.h:195
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:7685

◆ set_plan_disabling_options()

bool set_plan_disabling_options ( const char *  arg,
GucContext  context,
GucSource  source 
)

Definition at line 3436 of file postgres.c.

References SetConfigOption().

Referenced by PostmasterMain(), and process_postgres_switches().

3437 {
3438  const char *tmp = NULL;
3439 
3440  switch (arg[0])
3441  {
3442  case 's': /* seqscan */
3443  tmp = "enable_seqscan";
3444  break;
3445  case 'i': /* indexscan */
3446  tmp = "enable_indexscan";
3447  break;
3448  case 'o': /* indexonlyscan */
3449  tmp = "enable_indexonlyscan";
3450  break;
3451  case 'b': /* bitmapscan */
3452  tmp = "enable_bitmapscan";
3453  break;
3454  case 't': /* tidscan */
3455  tmp = "enable_tidscan";
3456  break;
3457  case 'n': /* nestloop */
3458  tmp = "enable_nestloop";
3459  break;
3460  case 'm': /* mergejoin */
3461  tmp = "enable_mergejoin";
3462  break;
3463  case 'h': /* hashjoin */
3464  tmp = "enable_hashjoin";
3465  break;
3466  }
3467  if (tmp)
3468  {
3469  SetConfigOption(tmp, "false", context, source);
3470  return true;
3471  }
3472  else
3473  return false;
3474 }
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:7685
void * arg

◆ ShowUsage()

void ShowUsage ( const char *  title)

Definition at line 4618 of file postgres.c.

References __darwin__, appendStringInfo(), appendStringInfoString(), StringInfoData::data, ereport, errdetail_internal(), errmsg_internal(), getrusage(), gettimeofday(), initStringInfo(), StringInfoData::len, LOG, pfree(), rusage::ru_stime, rusage::ru_utime, RUSAGE_SELF, Save_r, Save_t, and generate_unaccent_rules::str.

Referenced by _bt_leader_participate_as_worker(), _bt_leafbuild(), _bt_parallel_build_main(), _SPI_pquery(), btbuild(), exec_bind_message(), exec_execute_message(), exec_parse_message(), exec_simple_query(), pg_analyze_and_rewrite(), pg_analyze_and_rewrite_params(), pg_parse_query(), pg_plan_query(), pg_rewrite_query(), PortalRun(), and PortalRunMulti().

4619 {
4621  struct timeval user,
4622  sys;
4623  struct timeval elapse_t;
4624  struct rusage r;
4625 
4626  getrusage(RUSAGE_SELF, &r);
4627  gettimeofday(&elapse_t, NULL);
4628  memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
4629  memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
4630  if (elapse_t.tv_usec < Save_t.tv_usec)
4631  {
4632  elapse_t.tv_sec--;
4633  elapse_t.tv_usec += 1000000;
4634  }
4635  if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
4636  {
4637  r.ru_utime.tv_sec--;
4638  r.ru_utime.tv_usec += 1000000;
4639  }
4640  if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
4641  {
4642  r.ru_stime.tv_sec--;
4643  r.ru_stime.tv_usec += 1000000;
4644  }
4645 
4646  /*
4647  * The only stats we don't show here are ixrss, idrss, isrss. It takes
4648  * some work to interpret them, and most platforms don't fill them in.
4649  */
4650  initStringInfo(&str);
4651 
4652  appendStringInfoString(&str, "! system usage stats:\n");
4653  appendStringInfo(&str,
4654  "!\t%ld.%06ld s user, %ld.%06ld s system, %ld.%06ld s elapsed\n",
4655  (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
4656  (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
4657  (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
4658  (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec),
4659  (long) (elapse_t.tv_sec - Save_t.tv_sec),
4660  (long) (elapse_t.tv_usec - Save_t.tv_usec));
4661  appendStringInfo(&str,
4662  "!\t[%ld.%06ld s user, %ld.%06ld s system total]\n",
4663  (long) user.tv_sec,
4664  (long) user.tv_usec,
4665  (long) sys.tv_sec,
4666  (long) sys.tv_usec);
4667 #if defined(HAVE_GETRUSAGE)
4668  appendStringInfo(&str,
4669  "!\t%ld kB max resident size\n",
4670 #if defined(__darwin__)
4671  /* in bytes on macOS */
4672  r.ru_maxrss / 1024
4673 #else
4674  /* in kilobytes on most other platforms */
4675  r.ru_maxrss
4676 #endif
4677  );
4678  appendStringInfo(&str,
4679  "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
4680  r.ru_inblock - Save_r.ru_inblock,
4681  /* they only drink coffee at dec */
4682  r.ru_oublock - Save_r.ru_oublock,
4683  r.ru_inblock, r.ru_oublock);
4684  appendStringInfo(&str,
4685  "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
4686  r.ru_majflt - Save_r.ru_majflt,
4687  r.ru_minflt - Save_r.ru_minflt,
4688  r.ru_majflt, r.ru_minflt,
4689  r.ru_nswap - Save_r.ru_nswap,
4690  r.ru_nswap);
4691  appendStringInfo(&str,
4692  "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
4693  r.ru_nsignals - Save_r.ru_nsignals,
4694  r.ru_nsignals,
4695  r.ru_msgrcv - Save_r.ru_msgrcv,
4696  r.ru_msgsnd - Save_r.ru_msgsnd,
4697  r.ru_msgrcv, r.ru_msgsnd);
4698  appendStringInfo(&str,
4699  "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
4700  r.ru_nvcsw - Save_r.ru_nvcsw,
4701  r.ru_nivcsw - Save_r.ru_nivcsw,
4702  r.ru_nvcsw, r.ru_nivcsw);
4703 #endif /* HAVE_GETRUSAGE */
4704 
4705  /* remove trailing newline */
4706  if (str.data[str.len - 1] == '\n')
4707  str.data[--str.len] = '\0';
4708 
4709  ereport(LOG,
4710  (errmsg_internal("%s", title),
4711  errdetail_internal("%s", str.data)));
4712 
4713  pfree(str.data);
4714 }
int gettimeofday(struct timeval *tp, struct timezone *tzp)
Definition: gettimeofday.c:104
static struct rusage Save_r
Definition: postgres.c:4607
struct timeval ru_stime
Definition: rusagestub.h:29
int getrusage(int who, struct rusage *rusage)
Definition: getrusage.c:31
#define LOG
Definition: elog.h:26
int errdetail_internal(const char *fmt,...)
Definition: elog.c:984
void pfree(void *pointer)
Definition: mcxt.c:1056
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static struct timeval Save_t
Definition: postgres.c:4608
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
struct timeval ru_utime
Definition: rusagestub.h:28
#define RUSAGE_SELF
Definition: rusagestub.h:23
#define ereport(elevel,...)
Definition: elog.h:144
int errmsg_internal(const char *fmt,...)
Definition: elog.c:911
static char * user
Definition: pg_regress.c:93
#define __darwin__
Definition: darwin.h:3

◆ StatementCancelHandler()

void StatementCancelHandler ( SIGNAL_ARGS  )

Definition at line 2857 of file postgres.c.

References InterruptPending, MyLatch, proc_exit_inprogress, QueryCancelPending, and SetLatch().

Referenced by AutoVacLauncherMain(), AutoVacWorkerMain(), PostgresMain(), StartBackgroundWorker(), and WalSndSignals().

2858 {
2859  int save_errno = errno;
2860 
2861  /*
2862  * Don't joggle the elbow of proc_exit
2863  */
2864  if (!proc_exit_inprogress)
2865  {
2866  InterruptPending = true;
2867  QueryCancelPending = true;
2868  }
2869 
2870  /* If we're still here, waken anything waiting on the process latch */
2871  SetLatch(MyLatch);
2872 
2873  errno = save_errno;
2874 }
volatile sig_atomic_t QueryCancelPending
Definition: globals.c:31
void SetLatch(Latch *latch)
Definition: latch.c:457
bool proc_exit_inprogress
Definition: ipc.c:40
volatile sig_atomic_t InterruptPending
Definition: globals.c:30
struct Latch * MyLatch
Definition: globals.c:54

Variable Documentation

◆ debug_query_string

◆ log_statement

PGDLLIMPORT int log_statement

Definition at line 96 of file postgres.c.

Referenced by check_log_statement(), and HandleFunctionRequest().

◆ max_stack_depth

int max_stack_depth

Definition at line 99 of file postgres.c.

Referenced by check_stack_depth().

◆ PostAuthDelay

int PostAuthDelay

◆ whereToSendOutput