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, int cursorOptions, ParamListInfo boundParams)
 
Listpg_plan_queries (List *querytrees, 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 3382 of file postgres.c.

References max_stack_depth_bytes.

3383 {
3384  long newval_bytes = newval * 1024L;
3385 
3386  max_stack_depth_bytes = newval_bytes;
3387 }
static long max_stack_depth_bytes
Definition: postgres.c:111
#define newval

◆ check_log_duration()

int check_log_duration ( char *  msec_str,
bool  was_logged 
)

Definition at line 2299 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().

2300 {
2301  if (log_duration || log_min_duration_sample >= 0 ||
2303  {
2304  long secs;
2305  int usecs;
2306  int msecs;
2307  bool exceeded_duration;
2308  bool exceeded_sample_duration;
2309  bool in_sample = false;
2310 
2313  &secs, &usecs);
2314  msecs = usecs / 1000;
2315 
2316  /*
2317  * This odd-looking test for log_min_duration_* being exceeded is
2318  * designed to avoid integer overflow with very long durations: don't
2319  * compute secs * 1000 until we've verified it will fit in int.
2320  */
2321  exceeded_duration = (log_min_duration_statement == 0 ||
2323  (secs > log_min_duration_statement / 1000 ||
2324  secs * 1000 + msecs >= log_min_duration_statement)));
2325 
2326  exceeded_sample_duration = (log_min_duration_sample == 0 ||
2327  (log_min_duration_sample > 0 &&
2328  (secs > log_min_duration_sample / 1000 ||
2329  secs * 1000 + msecs >= log_min_duration_sample)));
2330 
2331  /*
2332  * Do not log if log_statement_sample_rate = 0. Log a sample if
2333  * log_statement_sample_rate <= 1 and avoid unecessary random() call
2334  * if log_statement_sample_rate = 1.
2335  */
2336  if (exceeded_sample_duration)
2337  in_sample = log_statement_sample_rate != 0 &&
2338  (log_statement_sample_rate == 1 ||
2340 
2341  if (exceeded_duration || in_sample || log_duration || xact_is_sampled)
2342  {
2343  snprintf(msec_str, 32, "%ld.%03d",
2344  secs * 1000 + msecs, usecs % 1000);
2345  if ((exceeded_duration || in_sample || xact_is_sampled) && !was_logged)
2346  return 2;
2347  else
2348  return 1;
2349  }
2350  }
2351 
2352  return 0;
2353 }
int log_min_duration_statement
Definition: guc.c:517
double log_statement_sample_rate
Definition: guc.c:519
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1583
long random(void)
Definition: random.c:22
int log_min_duration_sample
Definition: guc.c:516
#define MAX_RANDOM_VALUE
bool xact_is_sampled
Definition: xact.c:267
bool log_duration
Definition: guc.c:488
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1657
#define snprintf
Definition: port.h:192
TimestampTz GetCurrentStatementStartTimestamp(void)
Definition: xact.c:791

◆ check_max_stack_depth()

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

Definition at line 3365 of file postgres.c.

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

3366 {
3367  long newval_bytes = *newval * 1024L;
3368  long stack_rlimit = get_stack_depth_rlimit();
3369 
3370  if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3371  {
3372  GUC_check_errdetail("\"max_stack_depth\" must not exceed %ldkB.",
3373  (stack_rlimit - STACK_DEPTH_SLOP) / 1024L);
3374  GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3375  return false;
3376  }
3377  return true;
3378 }
#define GUC_check_errdetail
Definition: guc.h:414
long get_stack_depth_rlimit(void)
Definition: postgres.c:4566
#define newval
#define GUC_check_errhint
Definition: guc.h:418
#define STACK_DEPTH_SLOP
Definition: tcopprot.h:26

◆ die()

void die ( SIGNAL_ARGS  )

Definition at line 2801 of file postgres.c.

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

Referenced by PostgresMain().

2802 {
2803  int save_errno = errno;
2804 
2805  /* Don't joggle the elbow of proc_exit */
2806  if (!proc_exit_inprogress)
2807  {
2808  InterruptPending = true;
2809  ProcDiePending = true;
2810  }
2811 
2812  /* If we're still here, waken anything waiting on the process latch */
2813  SetLatch(MyLatch);
2814 
2815  /*
2816  * If we're in single user mode, we want to quit immediately - we can't
2817  * rely on latches as they wouldn't work when stdin/stdout is a file.
2818  * Rather ugly, but it's unlikely to be worthwhile to invest much more
2819  * effort just for the benefit of single user mode.
2820  */
2823 
2824  errno = save_errno;
2825 }
void SetLatch(Latch *latch)
Definition: latch.c:436
void ProcessInterrupts(void)
Definition: postgres.c:3012
volatile sig_atomic_t ProcDiePending
Definition: globals.c:32
bool proc_exit_inprogress
Definition: ipc.c:40
static bool DoingCommandRead
Definition: postgres.c:139
volatile sig_atomic_t InterruptPending
Definition: globals.c:30
struct Latch * MyLatch
Definition: globals.c:54
CommandDest whereToSendOutput
Definition: postgres.c:90

◆ FloatExceptionHandler()

void FloatExceptionHandler ( SIGNAL_ARGS  )

Definition at line 2853 of file postgres.c.

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

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

2854 {
2855  /* We're not returning, so no need to save errno */
2856  ereport(ERROR,
2857  (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2858  errmsg("floating-point exception"),
2859  errdetail("An invalid floating-point operation was signaled. "
2860  "This probably means an out-of-range result or an "
2861  "invalid operation, such as division by zero.")));
2862 }
int errcode(int sqlerrcode)
Definition: elog.c:608
#define ERROR
Definition: elog.h:43
int errdetail(const char *fmt,...)
Definition: elog.c:955
#define ereport(elevel, rest)
Definition: elog.h:141
int errmsg(const char *fmt,...)
Definition: elog.c:822

◆ get_stack_depth_rlimit()

long get_stack_depth_rlimit ( void  )

Definition at line 4566 of file postgres.c.

References val.

Referenced by check_max_stack_depth(), and InitializeGUCOptionsFromEnvironment().

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

◆ get_stats_option_name()

const char* get_stats_option_name ( const char *  arg)

Definition at line 3468 of file postgres.c.

References optarg.

Referenced by PostmasterMain(), and process_postgres_switches().

3469 {
3470  switch (arg[0])
3471  {
3472  case 'p':
3473  if (optarg[1] == 'a') /* "parser" */
3474  return "log_parser_stats";
3475  else if (optarg[1] == 'l') /* "planner" */
3476  return "log_planner_stats";
3477  break;
3478 
3479  case 'e': /* "executor" */
3480  return "log_executor_stats";
3481  break;
3482  }
3483 
3484  return NULL;
3485 }
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 675 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().

678 {
679  Query *query;
680  List *querytree_list;
681 
682  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
683 
684  /*
685  * (1) Perform parse analysis.
686  */
687  if (log_parser_stats)
688  ResetUsage();
689 
690  query = parse_analyze(parsetree, query_string, paramTypes, numParams,
691  queryEnv);
692 
693  if (log_parser_stats)
694  ShowUsage("PARSE ANALYSIS STATISTICS");
695 
696  /*
697  * (2) Rewrite the queries, as necessary
698  */
699  querytree_list = pg_rewrite_query(query);
700 
701  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
702 
703  return querytree_list;
704 }
bool log_parser_stats
Definition: guc.c:495
void ShowUsage(const char *title)
Definition: postgres.c:4609
void ResetUsage(void)
Definition: postgres.c:4602
static List * pg_rewrite_query(Query *query)
Definition: postgres.c:764
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 712 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().

717 {
718  ParseState *pstate;
719  Query *query;
720  List *querytree_list;
721 
722  Assert(query_string != NULL); /* required as of 8.4 */
723 
724  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
725 
726  /*
727  * (1) Perform parse analysis.
728  */
729  if (log_parser_stats)
730  ResetUsage();
731 
732  pstate = make_parsestate(NULL);
733  pstate->p_sourcetext = query_string;
734  pstate->p_queryEnv = queryEnv;
735  (*parserSetup) (pstate, parserSetupArg);
736 
737  query = transformTopLevelStmt(pstate, parsetree);
738 
740  (*post_parse_analyze_hook) (pstate, query);
741 
742  free_parsestate(pstate);
743 
744  if (log_parser_stats)
745  ShowUsage("PARSE ANALYSIS STATISTICS");
746 
747  /*
748  * (2) Rewrite the queries, as necessary
749  */
750  querytree_list = pg_rewrite_query(query);
751 
752  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
753 
754  return querytree_list;
755 }
bool log_parser_stats
Definition: guc.c:495
QueryEnvironment * p_queryEnv
Definition: parse_node.h:200
void ShowUsage(const char *title)
Definition: postgres.c:4609
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:43
void ResetUsage(void)
Definition: postgres.c:4602
const char * p_sourcetext
Definition: parse_node.h:176
static List * pg_rewrite_query(Query *query)
Definition: postgres.c:764
#define Assert(condition)
Definition: c.h:739
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 627 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().

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

◆ pg_plan_queries()

List* pg_plan_queries ( List querytrees,
int  cursorOptions,
ParamListInfo  boundParams 
)

Definition at line 941 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().

942 {
943  List *stmt_list = NIL;
944  ListCell *query_list;
945 
946  foreach(query_list, querytrees)
947  {
948  Query *query = lfirst_node(Query, query_list);
949  PlannedStmt *stmt;
950 
951  if (query->commandType == CMD_UTILITY)
952  {
953  /* Utility commands require no planning. */
954  stmt = makeNode(PlannedStmt);
955  stmt->commandType = CMD_UTILITY;
956  stmt->canSetTag = query->canSetTag;
957  stmt->utilityStmt = query->utilityStmt;
958  stmt->stmt_location = query->stmt_location;
959  stmt->stmt_len = query->stmt_len;
960  }
961  else
962  {
963  stmt = pg_plan_query(query, cursorOptions, boundParams);
964  }
965 
966  stmt_list = lappend(stmt_list, stmt);
967  }
968 
969  return stmt_list;
970 }
#define NIL
Definition: pg_list.h:65
int stmt_location
Definition: parsenodes.h:180
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:322
bool canSetTag
Definition: plannodes.h:54
CmdType commandType
Definition: plannodes.h:46
CmdType commandType
Definition: parsenodes.h:112
#define makeNode(_type_)
Definition: nodes.h:573
bool canSetTag
Definition: parsenodes.h:118
Definition: pg_list.h:50
int stmt_len
Definition: parsenodes.h:181
PlannedStmt * pg_plan_query(Query *querytree, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:856

◆ pg_plan_query()

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

Definition at line 856 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().

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

◆ PostgresMain()

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

Definition at line 3767 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, PostgresSigHupHandler(), 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, 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().

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

◆ process_postgres_switches()

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

Definition at line 3508 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().

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

◆ ProcessClientReadInterrupt()

void ProcessClientReadInterrupt ( bool  blocked)

Definition at line 525 of file postgres.c.

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

Referenced by interactive_getc(), and secure_read().

526 {
527  int save_errno = errno;
528 
529  if (DoingCommandRead)
530  {
531  /* Check for general interrupts that arrived before/while reading */
533 
534  /* Process sinval catchup interrupts, if any */
537 
538  /* Process notify interrupts, if any */
541  }
542  else if (ProcDiePending)
543  {
544  /*
545  * We're dying. If there is no data available to read, then it's safe
546  * (and sane) to handle that now. If we haven't tried to read yet,
547  * make sure the process latch is set, so that if there is no data
548  * then we'll come back here and die. If we're done reading, also
549  * make sure the process latch is set, as we might've undesirably
550  * cleared it while reading.
551  */
552  if (blocked)
554  else
555  SetLatch(MyLatch);
556  }
557 
558  errno = save_errno;
559 }
void ProcessCatchupInterrupt(void)
Definition: sinval.c:176
void SetLatch(Latch *latch)
Definition: latch.c:436
void ProcessNotifyInterrupt(void)
Definition: async.c:1895
volatile sig_atomic_t ProcDiePending
Definition: globals.c:32
static bool DoingCommandRead
Definition: postgres.c:139
struct Latch * MyLatch
Definition: globals.c:54
volatile sig_atomic_t notifyInterruptPending
Definition: async.c:415
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 571 of file postgres.c.

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

Referenced by secure_write().

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

◆ quickdie()

void quickdie ( SIGNAL_ARGS  )

Definition at line 2734 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().

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

◆ RecoveryConflictInterrupt()

void RecoveryConflictInterrupt ( ProcSignalReason  reason)

Definition at line 2889 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().

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

◆ ResetUsage()

void ResetUsage ( void  )

Definition at line 4602 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().

4603 {
4605  gettimeofday(&Save_t, NULL);
4606 }
int gettimeofday(struct timeval *tp, struct timezone *tzp)
Definition: gettimeofday.c:105
static struct rusage Save_r
Definition: postgres.c:4598
int getrusage(int who, struct rusage *rusage)
Definition: getrusage.c:31
static struct timeval Save_t
Definition: postgres.c:4599
#define RUSAGE_SELF
Definition: rusagestub.h:23

◆ set_debug_options()

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

Definition at line 3397 of file postgres.c.

References PGC_POSTMASTER, SetConfigOption(), and sprintf.

Referenced by PostmasterMain(), and process_postgres_switches().

3398 {
3399  if (debug_flag > 0)
3400  {
3401  char debugstr[64];
3402 
3403  sprintf(debugstr, "debug%d", debug_flag);
3404  SetConfigOption("log_min_messages", debugstr, context, source);
3405  }
3406  else
3407  SetConfigOption("log_min_messages", "notice", context, source);
3408 
3409  if (debug_flag >= 1 && context == PGC_POSTMASTER)
3410  {
3411  SetConfigOption("log_connections", "true", context, source);
3412  SetConfigOption("log_disconnections", "true", context, source);
3413  }
3414  if (debug_flag >= 2)
3415  SetConfigOption("log_statement", "all", context, source);
3416  if (debug_flag >= 3)
3417  SetConfigOption("debug_print_parse", "true", context, source);
3418  if (debug_flag >= 4)
3419  SetConfigOption("debug_print_plan", "true", context, source);
3420  if (debug_flag >= 5)
3421  SetConfigOption("debug_print_rewritten", "true", context, source);
3422 }
#define sprintf
Definition: port.h:194
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:7550

◆ set_plan_disabling_options()

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

Definition at line 3426 of file postgres.c.

References SetConfigOption().

Referenced by PostmasterMain(), and process_postgres_switches().

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

◆ ShowUsage()

void ShowUsage ( const char *  title)

Definition at line 4609 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().

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

◆ StatementCancelHandler()

void StatementCancelHandler ( SIGNAL_ARGS  )

Definition at line 2832 of file postgres.c.

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

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

2833 {
2834  int save_errno = errno;
2835 
2836  /*
2837  * Don't joggle the elbow of proc_exit
2838  */
2839  if (!proc_exit_inprogress)
2840  {
2841  InterruptPending = true;
2842  QueryCancelPending = true;
2843  }
2844 
2845  /* If we're still here, waken anything waiting on the process latch */
2846  SetLatch(MyLatch);
2847 
2848  errno = save_errno;
2849 }
volatile sig_atomic_t QueryCancelPending
Definition: globals.c:31
void SetLatch(Latch *latch)
Definition: latch.c:436
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 95 of file postgres.c.

Referenced by check_log_statement(), and HandleFunctionRequest().

◆ max_stack_depth

int max_stack_depth

Definition at line 98 of file postgres.c.

Referenced by check_stack_depth().

◆ PostAuthDelay

int PostAuthDelay

◆ whereToSendOutput