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 31 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 40 of file tcopprot.h.

41 {
42  LOGSTMT_NONE, /* log no statements */
43  LOGSTMT_DDL, /* log data definition statements */
44  LOGSTMT_MOD, /* log modification statements, plus DDL */
45  LOGSTMT_ALL /* log all statements */
46 } LogStmtLevel;
LogStmtLevel
Definition: tcopprot.h:40

Function Documentation

◆ assign_max_stack_depth()

void assign_max_stack_depth ( int  newval,
void *  extra 
)

Definition at line 3239 of file postgres.c.

References max_stack_depth_bytes.

3240 {
3241  long newval_bytes = newval * 1024L;
3242 
3243  max_stack_depth_bytes = newval_bytes;
3244 }
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 2132 of file postgres.c.

References GetCurrentStatementStartTimestamp(), GetCurrentTimestamp(), log_duration, log_min_duration_statement, snprintf(), and TimestampDifference().

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

2133 {
2135  {
2136  long secs;
2137  int usecs;
2138  int msecs;
2139  bool exceeded;
2140 
2143  &secs, &usecs);
2144  msecs = usecs / 1000;
2145 
2146  /*
2147  * This odd-looking test for log_min_duration_statement being exceeded
2148  * is designed to avoid integer overflow with very long durations:
2149  * don't compute secs * 1000 until we've verified it will fit in int.
2150  */
2151  exceeded = (log_min_duration_statement == 0 ||
2153  (secs > log_min_duration_statement / 1000 ||
2154  secs * 1000 + msecs >= log_min_duration_statement)));
2155 
2156  if (exceeded || log_duration)
2157  {
2158  snprintf(msec_str, 32, "%ld.%03d",
2159  secs * 1000 + msecs, usecs % 1000);
2160  if (exceeded && !was_logged)
2161  return 2;
2162  else
2163  return 1;
2164  }
2165  }
2166 
2167  return 0;
2168 }
int log_min_duration_statement
Definition: guc.c:456
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
bool log_duration
Definition: guc.c:434
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1624
TimestampTz GetCurrentStatementStartTimestamp(void)
Definition: xact.c:709

◆ check_max_stack_depth()

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

Definition at line 3222 of file postgres.c.

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

3223 {
3224  long newval_bytes = *newval * 1024L;
3225  long stack_rlimit = get_stack_depth_rlimit();
3226 
3227  if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3228  {
3229  GUC_check_errdetail("\"max_stack_depth\" must not exceed %ldkB.",
3230  (stack_rlimit - STACK_DEPTH_SLOP) / 1024L);
3231  GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3232  return false;
3233  }
3234  return true;
3235 }
#define GUC_check_errdetail
Definition: guc.h:410
long get_stack_depth_rlimit(void)
Definition: postgres.c:4415
#define newval
#define GUC_check_errhint
Definition: guc.h:414
#define STACK_DEPTH_SLOP
Definition: tcopprot.h:31

◆ die()

void die ( SIGNAL_ARGS  )

Definition at line 2658 of file postgres.c.

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

Referenced by ApplyLauncherMain(), ApplyWorkerMain(), autoprewarm_database_main(), AutoVacWorkerMain(), bootstrap_signals(), ParallelWorkerMain(), PostgresMain(), and WalSndSignals().

2659 {
2660  int save_errno = errno;
2661 
2662  /* Don't joggle the elbow of proc_exit */
2663  if (!proc_exit_inprogress)
2664  {
2665  InterruptPending = true;
2666  ProcDiePending = true;
2667  }
2668 
2669  /* If we're still here, waken anything waiting on the process latch */
2670  SetLatch(MyLatch);
2671 
2672  /*
2673  * If we're in single user mode, we want to quit immediately - we can't
2674  * rely on latches as they wouldn't work when stdin/stdout is a file.
2675  * Rather ugly, but it's unlikely to be worthwhile to invest much more
2676  * effort just for the benefit of single user mode.
2677  */
2680 
2681  errno = save_errno;
2682 }
void ProcessInterrupts(void)
Definition: postgres.c:2869
volatile bool InterruptPending
Definition: globals.c:30
void SetLatch(volatile Latch *latch)
Definition: latch.c:414
bool proc_exit_inprogress
Definition: ipc.c:40
static bool DoingCommandRead
Definition: postgres.c:139
volatile bool ProcDiePending
Definition: globals.c:32
struct Latch * MyLatch
Definition: globals.c:53
CommandDest whereToSendOutput
Definition: postgres.c:90

◆ FloatExceptionHandler()

void FloatExceptionHandler ( SIGNAL_ARGS  )

Definition at line 2710 of file postgres.c.

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

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

2711 {
2712  /* We're not returning, so no need to save errno */
2713  ereport(ERROR,
2714  (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2715  errmsg("floating-point exception"),
2716  errdetail("An invalid floating-point operation was signaled. "
2717  "This probably means an out-of-range result or an "
2718  "invalid operation, such as division by zero.")));
2719 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define ereport(elevel, rest)
Definition: elog.h:122
int errmsg(const char *fmt,...)
Definition: elog.c:797

◆ get_stack_depth_rlimit()

long get_stack_depth_rlimit ( void  )

Definition at line 4415 of file postgres.c.

References val.

Referenced by check_max_stack_depth(), and InitializeGUCOptionsFromEnvironment().

4416 {
4417 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_STACK)
4418  static long val = 0;
4419 
4420  /* This won't change after process launch, so check just once */
4421  if (val == 0)
4422  {
4423  struct rlimit rlim;
4424 
4425  if (getrlimit(RLIMIT_STACK, &rlim) < 0)
4426  val = -1;
4427  else if (rlim.rlim_cur == RLIM_INFINITY)
4428  val = LONG_MAX;
4429  /* rlim_cur is probably of an unsigned type, so check for overflow */
4430  else if (rlim.rlim_cur >= LONG_MAX)
4431  val = LONG_MAX;
4432  else
4433  val = rlim.rlim_cur;
4434  }
4435  return val;
4436 #else /* no getrlimit */
4437 #if defined(WIN32) || defined(__CYGWIN__)
4438  /* On Windows we set the backend stack size in src/backend/Makefile */
4439  return WIN32_STACK_RLIMIT;
4440 #else /* not windows ... give up */
4441  return -1;
4442 #endif
4443 #endif
4444 }
long val
Definition: informix.c:689

◆ get_stats_option_name()

const char* get_stats_option_name ( const char *  arg)

Definition at line 3325 of file postgres.c.

References optarg.

Referenced by PostmasterMain(), and process_postgres_switches().

3326 {
3327  switch (arg[0])
3328  {
3329  case 'p':
3330  if (optarg[1] == 'a') /* "parser" */
3331  return "log_parser_stats";
3332  else if (optarg[1] == 'l') /* "planner" */
3333  return "log_planner_stats";
3334  break;
3335 
3336  case 'e': /* "executor" */
3337  return "log_executor_stats";
3338  break;
3339  }
3340 
3341  return NULL;
3342 }
char * optarg
Definition: getopt.c:53
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 651 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().

654 {
655  Query *query;
656  List *querytree_list;
657 
658  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
659 
660  /*
661  * (1) Perform parse analysis.
662  */
663  if (log_parser_stats)
664  ResetUsage();
665 
666  query = parse_analyze(parsetree, query_string, paramTypes, numParams,
667  queryEnv);
668 
669  if (log_parser_stats)
670  ShowUsage("PARSE ANALYSIS STATISTICS");
671 
672  /*
673  * (2) Rewrite the queries, as necessary
674  */
675  querytree_list = pg_rewrite_query(query);
676 
677  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
678 
679  return querytree_list;
680 }
bool log_parser_stats
Definition: guc.c:440
void ShowUsage(const char *title)
Definition: postgres.c:4458
void ResetUsage(void)
Definition: postgres.c:4451
static List * pg_rewrite_query(Query *query)
Definition: postgres.c:740
Query * parse_analyze(RawStmt *parseTree, const char *sourceText, Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition: analyze.c:100
Definition: pg_list.h:45

◆ 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 688 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().

693 {
694  ParseState *pstate;
695  Query *query;
696  List *querytree_list;
697 
698  Assert(query_string != NULL); /* required as of 8.4 */
699 
700  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
701 
702  /*
703  * (1) Perform parse analysis.
704  */
705  if (log_parser_stats)
706  ResetUsage();
707 
708  pstate = make_parsestate(NULL);
709  pstate->p_sourcetext = query_string;
710  pstate->p_queryEnv = queryEnv;
711  (*parserSetup) (pstate, parserSetupArg);
712 
713  query = transformTopLevelStmt(pstate, parsetree);
714 
716  (*post_parse_analyze_hook) (pstate, query);
717 
718  free_parsestate(pstate);
719 
720  if (log_parser_stats)
721  ShowUsage("PARSE ANALYSIS STATISTICS");
722 
723  /*
724  * (2) Rewrite the queries, as necessary
725  */
726  querytree_list = pg_rewrite_query(query);
727 
728  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
729 
730  return querytree_list;
731 }
bool log_parser_stats
Definition: guc.c:440
QueryEnvironment * p_queryEnv
Definition: parse_node.h:197
void ShowUsage(const char *title)
Definition: postgres.c:4458
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
void ResetUsage(void)
Definition: postgres.c:4451
const char * p_sourcetext
Definition: parse_node.h:173
static List * pg_rewrite_query(Query *query)
Definition: postgres.c:740
#define Assert(condition)
Definition: c.h:699
Query * transformTopLevelStmt(ParseState *pstate, RawStmt *parseTree)
Definition: analyze.c:191
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:77
Definition: pg_list.h:45
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 609 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().

610 {
611  List *raw_parsetree_list;
612 
613  TRACE_POSTGRESQL_QUERY_PARSE_START(query_string);
614 
615  if (log_parser_stats)
616  ResetUsage();
617 
618  raw_parsetree_list = raw_parser(query_string);
619 
620  if (log_parser_stats)
621  ShowUsage("PARSER STATISTICS");
622 
623 #ifdef COPY_PARSE_PLAN_TREES
624  /* Optional debugging check: pass raw parsetrees through copyObject() */
625  {
626  List *new_list = copyObject(raw_parsetree_list);
627 
628  /* This checks both copyObject() and the equal() routines... */
629  if (!equal(new_list, raw_parsetree_list))
630  elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
631  else
632  raw_parsetree_list = new_list;
633  }
634 #endif
635 
636  TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
637 
638  return raw_parsetree_list;
639 }
List * raw_parser(const char *str)
Definition: parser.c:36
bool log_parser_stats
Definition: guc.c:440
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2986
void ShowUsage(const char *title)
Definition: postgres.c:4458
static List * new_list(NodeTag type)
Definition: list.c:63
void ResetUsage(void)
Definition: postgres.c:4451
#define WARNING
Definition: elog.h:40
#define elog
Definition: elog.h:219
#define copyObject(obj)
Definition: nodes.h:630
Definition: pg_list.h:45

◆ pg_plan_queries()

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

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

854 {
855  List *stmt_list = NIL;
856  ListCell *query_list;
857 
858  foreach(query_list, querytrees)
859  {
860  Query *query = lfirst_node(Query, query_list);
861  PlannedStmt *stmt;
862 
863  if (query->commandType == CMD_UTILITY)
864  {
865  /* Utility commands require no planning. */
866  stmt = makeNode(PlannedStmt);
867  stmt->commandType = CMD_UTILITY;
868  stmt->canSetTag = query->canSetTag;
869  stmt->utilityStmt = query->utilityStmt;
870  stmt->stmt_location = query->stmt_location;
871  stmt->stmt_len = query->stmt_len;
872  }
873  else
874  {
875  stmt = pg_plan_query(query, cursorOptions, boundParams);
876  }
877 
878  stmt_list = lappend(stmt_list, stmt);
879  }
880 
881  return stmt_list;
882 }
#define NIL
Definition: pg_list.h:69
int stmt_location
Definition: parsenodes.h:181
Node * utilityStmt
Definition: parsenodes.h:120
int stmt_len
Definition: plannodes.h:100
#define lfirst_node(type, lc)
Definition: pg_list.h:109
int stmt_location
Definition: plannodes.h:99
Node * utilityStmt
Definition: plannodes.h:96
List * lappend(List *list, void *datum)
Definition: list.c:128
bool canSetTag
Definition: plannodes.h:53
CmdType commandType
Definition: plannodes.h:45
CmdType commandType
Definition: parsenodes.h:112
#define makeNode(_type_)
Definition: nodes.h:565
bool canSetTag
Definition: parsenodes.h:118
Definition: pg_list.h:45
int stmt_len
Definition: parsenodes.h:182
PlannedStmt * pg_plan_query(Query *querytree, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:792

◆ pg_plan_query()

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

Definition at line 792 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, planner(), ResetUsage(), ShowUsage(), and WARNING.

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

793 {
794  PlannedStmt *plan;
795 
796  /* Utility commands have no plans. */
797  if (querytree->commandType == CMD_UTILITY)
798  return NULL;
799 
800  /* Planner must have a snapshot in case it calls user-defined functions. */
802 
803  TRACE_POSTGRESQL_QUERY_PLAN_START();
804 
805  if (log_planner_stats)
806  ResetUsage();
807 
808  /* call the optimizer */
809  plan = planner(querytree, cursorOptions, boundParams);
810 
811  if (log_planner_stats)
812  ShowUsage("PLANNER STATISTICS");
813 
814 #ifdef COPY_PARSE_PLAN_TREES
815  /* Optional debugging check: pass plan output through copyObject() */
816  {
817  PlannedStmt *new_plan = copyObject(plan);
818 
819  /*
820  * equal() currently does not have routines to compare Plan nodes, so
821  * don't try to test equality here. Perhaps fix someday?
822  */
823 #ifdef NOT_USED
824  /* This checks both copyObject() and the equal() routines... */
825  if (!equal(new_plan, plan))
826  elog(WARNING, "copyObject() failed to produce an equal plan tree");
827  else
828 #endif
829  plan = new_plan;
830  }
831 #endif
832 
833  /*
834  * Print plan if debugging.
835  */
836  if (Debug_print_plan)
837  elog_node_display(LOG, "plan", plan, Debug_pretty_print);
838 
839  TRACE_POSTGRESQL_QUERY_PLAN_DONE();
840 
841  return plan;
842 }
void elog_node_display(int lev, const char *title, const void *obj, bool pretty)
Definition: print.c:71
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2986
void ShowUsage(const char *title)
Definition: postgres.c:4458
#define LOG
Definition: elog.h:26
PlannedStmt * planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
Definition: planner.c:256
void ResetUsage(void)
Definition: postgres.c:4451
bool Debug_print_plan
Definition: guc.c:435
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:851
#define WARNING
Definition: elog.h:40
CmdType commandType
Definition: parsenodes.h:112
#define Assert(condition)
Definition: c.h:699
bool Debug_pretty_print
Definition: guc.c:438
#define elog
Definition: elog.h:219
#define copyObject(obj)
Definition: nodes.h:630
bool log_planner_stats
Definition: guc.c:441

◆ PostgresMain()

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

Definition at line 3624 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, 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(), proc_exit(), process_postgres_switches(), process_session_preload_libraries(), ProcessCompletedNotifies(), ProcessConfigFile(), 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(), stmt_timeout_active, TopMemoryContext, UnBlockSig, userDoption, username, WalSndErrorCleanup(), WalSndSignals(), whereToSendOutput, and xact_started.

Referenced by BackendRun(), and main().

3627 {
3628  int firstchar;
3629  StringInfoData input_message;
3630  sigjmp_buf local_sigjmp_buf;
3631  volatile bool send_ready_for_query = true;
3632  bool disable_idle_in_transaction_timeout = false;
3633 
3634  /* Initialize startup process environment if necessary. */
3635  if (!IsUnderPostmaster)
3636  InitStandaloneProcess(argv[0]);
3637 
3639 
3640  /*
3641  * Set default values for command-line options.
3642  */
3643  if (!IsUnderPostmaster)
3645 
3646  /*
3647  * Parse command-line options.
3648  */
3650 
3651  /* Must have gotten a database name, or have a default (the username) */
3652  if (dbname == NULL)
3653  {
3654  dbname = username;
3655  if (dbname == NULL)
3656  ereport(FATAL,
3657  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3658  errmsg("%s: no database nor user name specified",
3659  progname)));
3660  }
3661 
3662  /* Acquire configuration parameters, unless inherited from postmaster */
3663  if (!IsUnderPostmaster)
3664  {
3666  proc_exit(1);
3667  }
3668 
3669  /*
3670  * Set up signal handlers and masks.
3671  *
3672  * Note that postmaster blocked all signals before forking child process,
3673  * so there is no race condition whereby we might receive a signal before
3674  * we have set up the handler.
3675  *
3676  * Also note: it's best not to use any signals that are SIG_IGNored in the
3677  * postmaster. If such a signal arrives before we are able to change the
3678  * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
3679  * handler in the postmaster to reserve the signal. (Of course, this isn't
3680  * an issue for signals that are locally generated, such as SIGALRM and
3681  * SIGPIPE.)
3682  */
3683  if (am_walsender)
3684  WalSndSignals();
3685  else
3686  {
3687  pqsignal(SIGHUP, PostgresSigHupHandler); /* set flag to read config
3688  * file */
3689  pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
3690  pqsignal(SIGTERM, die); /* cancel current query and exit */
3691 
3692  /*
3693  * In a standalone backend, SIGQUIT can be generated from the keyboard
3694  * easily, while SIGTERM cannot, so we make both signals do die()
3695  * rather than quickdie().
3696  */
3697  if (IsUnderPostmaster)
3698  pqsignal(SIGQUIT, quickdie); /* hard crash time */
3699  else
3700  pqsignal(SIGQUIT, die); /* cancel current query and exit */
3701  InitializeTimeouts(); /* establishes SIGALRM handler */
3702 
3703  /*
3704  * Ignore failure to write to frontend. Note: if frontend closes
3705  * connection, we will notice it and exit cleanly when control next
3706  * returns to outer loop. This seems safer than forcing exit in the
3707  * midst of output during who-knows-what operation...
3708  */
3713 
3714  /*
3715  * Reset some signals that are accepted by postmaster but not by
3716  * backend
3717  */
3718  pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
3719  * platforms */
3720  }
3721 
3722  pqinitmask();
3723 
3724  if (IsUnderPostmaster)
3725  {
3726  /* We allow SIGQUIT (quickdie) at all times */
3727  sigdelset(&BlockSig, SIGQUIT);
3728  }
3729 
3730  PG_SETMASK(&BlockSig); /* block everything except SIGQUIT */
3731 
3732  if (!IsUnderPostmaster)
3733  {
3734  /*
3735  * Validate we have been given a reasonable-looking DataDir (if under
3736  * postmaster, assume postmaster did this already).
3737  */
3738  checkDataDir();
3739 
3740  /* Change into DataDir (if under postmaster, was done already) */
3741  ChangeToDataDir();
3742 
3743  /*
3744  * Create lockfile for data directory.
3745  */
3746  CreateDataDirLockFile(false);
3747 
3748  /* read control file (error checking and contains config ) */
3749  LocalProcessControlFile(false);
3750 
3751  /* Initialize MaxBackends (if under postmaster, was done already) */
3753  }
3754 
3755  /* Early initialization */
3756  BaseInit();
3757 
3758  /*
3759  * Create a per-backend PGPROC struct in shared memory, except in the
3760  * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
3761  * this before we can use LWLocks (and in the EXEC_BACKEND case we already
3762  * had to do some stuff with LWLocks).
3763  */
3764 #ifdef EXEC_BACKEND
3765  if (!IsUnderPostmaster)
3766  InitProcess();
3767 #else
3768  InitProcess();
3769 #endif
3770 
3771  /* We need to allow SIGINT, etc during the initial transaction */
3773 
3774  /*
3775  * General initialization.
3776  *
3777  * NOTE: if you are tempted to add code in this vicinity, consider putting
3778  * it inside InitPostgres() instead. In particular, anything that
3779  * involves database access should be there, not here.
3780  */
3782 
3783  /*
3784  * If the PostmasterContext is still around, recycle the space; we don't
3785  * need it anymore after InitPostgres completes. Note this does not trash
3786  * *MyProcPort, because ConnCreate() allocated that space with malloc()
3787  * ... else we'd need to copy the Port data first. Also, subsidiary data
3788  * such as the username isn't lost either; see ProcessStartupPacket().
3789  */
3790  if (PostmasterContext)
3791  {
3793  PostmasterContext = NULL;
3794  }
3795 
3797 
3798  /*
3799  * Now all GUC states are fully set up. Report them to client if
3800  * appropriate.
3801  */
3803 
3804  /*
3805  * Also set up handler to log session end; we have to wait till now to be
3806  * sure Log_disconnections has its final value.
3807  */
3810 
3811  /* Perform initialization specific to a WAL sender process. */
3812  if (am_walsender)
3813  InitWalSender();
3814 
3815  /*
3816  * process any libraries that should be preloaded at backend start (this
3817  * likewise can't be done until GUC settings are complete)
3818  */
3820 
3821  /*
3822  * Send this backend's cancellation info to the frontend.
3823  */
3825  {
3827 
3828  pq_beginmessage(&buf, 'K');
3829  pq_sendint32(&buf, (int32) MyProcPid);
3830  pq_sendint32(&buf, (int32) MyCancelKey);
3831  pq_endmessage(&buf);
3832  /* Need not flush since ReadyForQuery will do it. */
3833  }
3834 
3835  /* Welcome banner for standalone case */
3837  printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
3838 
3839  /*
3840  * Create the memory context we will use in the main loop.
3841  *
3842  * MessageContext is reset once per iteration of the main loop, ie, upon
3843  * completion of processing of each command message from the client.
3844  */
3846  "MessageContext",
3848 
3849  /*
3850  * Create memory context and buffer used for RowDescription messages. As
3851  * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
3852  * frequently executed for ever single statement, we don't want to
3853  * allocate a separate buffer every time.
3854  */
3856  "RowDescriptionContext",
3861 
3862  /*
3863  * Remember stand-alone backend startup time
3864  */
3865  if (!IsUnderPostmaster)
3867 
3868  /*
3869  * POSTGRES main processing loop begins here
3870  *
3871  * If an exception is encountered, processing resumes here so we abort the
3872  * current transaction and start a new one.
3873  *
3874  * You might wonder why this isn't coded as an infinite loop around a
3875  * PG_TRY construct. The reason is that this is the bottom of the
3876  * exception stack, and so with PG_TRY there would be no exception handler
3877  * in force at all during the CATCH part. By leaving the outermost setjmp
3878  * always active, we have at least some chance of recovering from an error
3879  * during error recovery. (If we get into an infinite loop thereby, it
3880  * will soon be stopped by overflow of elog.c's internal state stack.)
3881  *
3882  * Note that we use sigsetjmp(..., 1), so that this function's signal mask
3883  * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
3884  * is essential in case we longjmp'd out of a signal handler on a platform
3885  * where that leaves the signal blocked. It's not redundant with the
3886  * unblock in AbortTransaction() because the latter is only called if we
3887  * were inside a transaction.
3888  */
3889 
3890  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
3891  {
3892  /*
3893  * NOTE: if you are tempted to add more code in this if-block,
3894  * consider the high probability that it should be in
3895  * AbortTransaction() instead. The only stuff done directly here
3896  * should be stuff that is guaranteed to apply *only* for outer-level
3897  * error recovery, such as adjusting the FE/BE protocol status.
3898  */
3899 
3900  /* Since not using PG_TRY, must reset error stack by hand */
3901  error_context_stack = NULL;
3902 
3903  /* Prevent interrupts while cleaning up */
3904  HOLD_INTERRUPTS();
3905 
3906  /*
3907  * Forget any pending QueryCancel request, since we're returning to
3908  * the idle loop anyway, and cancel any active timeout requests. (In
3909  * future we might want to allow some timeout requests to survive, but
3910  * at minimum it'd be necessary to do reschedule_timeouts(), in case
3911  * we got here because of a query cancel interrupting the SIGALRM
3912  * interrupt handler.) Note in particular that we must clear the
3913  * statement and lock timeout indicators, to prevent any future plain
3914  * query cancels from being misreported as timeouts in case we're
3915  * forgetting a timeout cancel.
3916  */
3917  disable_all_timeouts(false);
3918  QueryCancelPending = false; /* second to avoid race condition */
3919  stmt_timeout_active = false;
3920 
3921  /* Not reading from the client anymore. */
3922  DoingCommandRead = false;
3923 
3924  /* Make sure libpq is in a good state */
3925  pq_comm_reset();
3926 
3927  /* Report the error to the client and/or server log */
3928  EmitErrorReport();
3929 
3930  /*
3931  * Make sure debug_query_string gets reset before we possibly clobber
3932  * the storage it points at.
3933  */
3934  debug_query_string = NULL;
3935 
3936  /*
3937  * Abort the current transaction in order to recover.
3938  */
3940 
3941  if (am_walsender)
3943 
3945  SPICleanup();
3946 
3947  /*
3948  * We can't release replication slots inside AbortTransaction() as we
3949  * need to be able to start and abort transactions while having a slot
3950  * acquired. But we never need to hold them across top level errors,
3951  * so releasing here is fine. There's another cleanup in ProcKill()
3952  * ensuring we'll correctly cleanup on FATAL errors as well.
3953  */
3954  if (MyReplicationSlot != NULL)
3956 
3957  /* We also want to cleanup temporary slots on error. */
3959 
3961 
3962  /*
3963  * Now return to normal top-level context and clear ErrorContext for
3964  * next time.
3965  */
3967  FlushErrorState();
3968 
3969  /*
3970  * If we were handling an extended-query-protocol message, initiate
3971  * skip till next Sync. This also causes us not to issue
3972  * ReadyForQuery (until we get Sync).
3973  */
3975  ignore_till_sync = true;
3976 
3977  /* We don't have a transaction command open anymore */
3978  xact_started = false;
3979 
3980  /*
3981  * If an error occurred while we were reading a message from the
3982  * client, we have potentially lost track of where the previous
3983  * message ends and the next one begins. Even though we have
3984  * otherwise recovered from the error, we cannot safely read any more
3985  * messages from the client, so there isn't much we can do with the
3986  * connection anymore.
3987  */
3988  if (pq_is_reading_msg())
3989  ereport(FATAL,
3990  (errcode(ERRCODE_PROTOCOL_VIOLATION),
3991  errmsg("terminating connection because protocol synchronization was lost")));
3992 
3993  /* Now we can allow interrupts again */
3995  }
3996 
3997  /* We can now handle ereport(ERROR) */
3998  PG_exception_stack = &local_sigjmp_buf;
3999 
4000  if (!ignore_till_sync)
4001  send_ready_for_query = true; /* initially, or after error */
4002 
4003  /*
4004  * Non-error queries loop here.
4005  */
4006 
4007  for (;;)
4008  {
4009  /*
4010  * At top of loop, reset extended-query-message flag, so that any
4011  * errors encountered in "idle" state don't provoke skip.
4012  */
4014 
4015  /*
4016  * Release storage left over from prior query cycle, and create a new
4017  * query input buffer in the cleared MessageContext.
4018  */
4021 
4022  initStringInfo(&input_message);
4023 
4024  /*
4025  * Also consider releasing our catalog snapshot if any, so that it's
4026  * not preventing advance of global xmin while we wait for the client.
4027  */
4029 
4030  /*
4031  * (1) If we've reached idle state, tell the frontend we're ready for
4032  * a new query.
4033  *
4034  * Note: this includes fflush()'ing the last of the prior output.
4035  *
4036  * This is also a good time to send collected statistics to the
4037  * collector, and to update the PS stats display. We avoid doing
4038  * those every time through the message loop because it'd slow down
4039  * processing of batched messages, and because we don't want to report
4040  * uncommitted updates (that confuses autovacuum). The notification
4041  * processor wants a call too, if we are not in a transaction block.
4042  */
4043  if (send_ready_for_query)
4044  {
4046  {
4047  set_ps_display("idle in transaction (aborted)", false);
4049 
4050  /* Start the idle-in-transaction timer */
4052  {
4053  disable_idle_in_transaction_timeout = true;
4056  }
4057  }
4059  {
4060  set_ps_display("idle in transaction", false);
4062 
4063  /* Start the idle-in-transaction timer */
4065  {
4066  disable_idle_in_transaction_timeout = true;
4069  }
4070  }
4071  else
4072  {
4074  pgstat_report_stat(false);
4075 
4076  set_ps_display("idle", false);
4078  }
4079 
4081  send_ready_for_query = false;
4082  }
4083 
4084  /*
4085  * (2) Allow asynchronous signals to be executed immediately if they
4086  * come in while we are waiting for client input. (This must be
4087  * conditional since we don't want, say, reads on behalf of COPY FROM
4088  * STDIN doing the same thing.)
4089  */
4090  DoingCommandRead = true;
4091 
4092  /*
4093  * (3) read a command (loop blocks here)
4094  */
4095  firstchar = ReadCommand(&input_message);
4096 
4097  /*
4098  * (4) disable async signal conditions again.
4099  *
4100  * Query cancel is supposed to be a no-op when there is no query in
4101  * progress, so if a query cancel arrived while we were idle, just
4102  * reset QueryCancelPending. ProcessInterrupts() has that effect when
4103  * it's called when DoingCommandRead is set, so check for interrupts
4104  * before resetting DoingCommandRead.
4105  */
4107  DoingCommandRead = false;
4108 
4109  /*
4110  * (5) turn off the idle-in-transaction timeout
4111  */
4112  if (disable_idle_in_transaction_timeout)
4113  {
4115  disable_idle_in_transaction_timeout = false;
4116  }
4117 
4118  /*
4119  * (6) check for any other interesting events that happened while we
4120  * slept.
4121  */
4122  if (ConfigReloadPending)
4123  {
4124  ConfigReloadPending = false;
4126  }
4127 
4128  /*
4129  * (7) process the command. But ignore it if we're skipping till
4130  * Sync.
4131  */
4132  if (ignore_till_sync && firstchar != EOF)
4133  continue;
4134 
4135  switch (firstchar)
4136  {
4137  case 'Q': /* simple query */
4138  {
4139  const char *query_string;
4140 
4141  /* Set statement_timestamp() */
4143 
4144  query_string = pq_getmsgstring(&input_message);
4145  pq_getmsgend(&input_message);
4146 
4147  if (am_walsender)
4148  {
4149  if (!exec_replication_command(query_string))
4150  exec_simple_query(query_string);
4151  }
4152  else
4153  exec_simple_query(query_string);
4154 
4155  send_ready_for_query = true;
4156  }
4157  break;
4158 
4159  case 'P': /* parse */
4160  {
4161  const char *stmt_name;
4162  const char *query_string;
4163  int numParams;
4164  Oid *paramTypes = NULL;
4165 
4166  forbidden_in_wal_sender(firstchar);
4167 
4168  /* Set statement_timestamp() */
4170 
4171  stmt_name = pq_getmsgstring(&input_message);
4172  query_string = pq_getmsgstring(&input_message);
4173  numParams = pq_getmsgint(&input_message, 2);
4174  if (numParams > 0)
4175  {
4176  int i;
4177 
4178  paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
4179  for (i = 0; i < numParams; i++)
4180  paramTypes[i] = pq_getmsgint(&input_message, 4);
4181  }
4182  pq_getmsgend(&input_message);
4183 
4184  exec_parse_message(query_string, stmt_name,
4185  paramTypes, numParams);
4186  }
4187  break;
4188 
4189  case 'B': /* bind */
4190  forbidden_in_wal_sender(firstchar);
4191 
4192  /* Set statement_timestamp() */
4194 
4195  /*
4196  * this message is complex enough that it seems best to put
4197  * the field extraction out-of-line
4198  */
4199  exec_bind_message(&input_message);
4200  break;
4201 
4202  case 'E': /* execute */
4203  {
4204  const char *portal_name;
4205  int max_rows;
4206 
4207  forbidden_in_wal_sender(firstchar);
4208 
4209  /* Set statement_timestamp() */
4211 
4212  portal_name = pq_getmsgstring(&input_message);
4213  max_rows = pq_getmsgint(&input_message, 4);
4214  pq_getmsgend(&input_message);
4215 
4216  exec_execute_message(portal_name, max_rows);
4217  }
4218  break;
4219 
4220  case 'F': /* fastpath function call */
4221  forbidden_in_wal_sender(firstchar);
4222 
4223  /* Set statement_timestamp() */
4225 
4226  /* Report query to various monitoring facilities. */
4228  set_ps_display("<FASTPATH>", false);
4229 
4230  /* start an xact for this function invocation */
4232 
4233  /*
4234  * Note: we may at this point be inside an aborted
4235  * transaction. We can't throw error for that until we've
4236  * finished reading the function-call message, so
4237  * HandleFunctionRequest() must check for it after doing so.
4238  * Be careful not to do anything that assumes we're inside a
4239  * valid transaction here.
4240  */
4241 
4242  /* switch back to message context */
4244 
4245  HandleFunctionRequest(&input_message);
4246 
4247  /* commit the function-invocation transaction */
4249 
4250  send_ready_for_query = true;
4251  break;
4252 
4253  case 'C': /* close */
4254  {
4255  int close_type;
4256  const char *close_target;
4257 
4258  forbidden_in_wal_sender(firstchar);
4259 
4260  close_type = pq_getmsgbyte(&input_message);
4261  close_target = pq_getmsgstring(&input_message);
4262  pq_getmsgend(&input_message);
4263 
4264  switch (close_type)
4265  {
4266  case 'S':
4267  if (close_target[0] != '\0')
4268  DropPreparedStatement(close_target, false);
4269  else
4270  {
4271  /* special-case the unnamed statement */
4273  }
4274  break;
4275  case 'P':
4276  {
4277  Portal portal;
4278 
4279  portal = GetPortalByName(close_target);
4280  if (PortalIsValid(portal))
4281  PortalDrop(portal, false);
4282  }
4283  break;
4284  default:
4285  ereport(ERROR,
4286  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4287  errmsg("invalid CLOSE message subtype %d",
4288  close_type)));
4289  break;
4290  }
4291 
4293  pq_putemptymessage('3'); /* CloseComplete */
4294  }
4295  break;
4296 
4297  case 'D': /* describe */
4298  {
4299  int describe_type;
4300  const char *describe_target;
4301 
4302  forbidden_in_wal_sender(firstchar);
4303 
4304  /* Set statement_timestamp() (needed for xact) */
4306 
4307  describe_type = pq_getmsgbyte(&input_message);
4308  describe_target = pq_getmsgstring(&input_message);
4309  pq_getmsgend(&input_message);
4310 
4311  switch (describe_type)
4312  {
4313  case 'S':
4314  exec_describe_statement_message(describe_target);
4315  break;
4316  case 'P':
4317  exec_describe_portal_message(describe_target);
4318  break;
4319  default:
4320  ereport(ERROR,
4321  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4322  errmsg("invalid DESCRIBE message subtype %d",
4323  describe_type)));
4324  break;
4325  }
4326  }
4327  break;
4328 
4329  case 'H': /* flush */
4330  pq_getmsgend(&input_message);
4332  pq_flush();
4333  break;
4334 
4335  case 'S': /* sync */
4336  pq_getmsgend(&input_message);
4338  send_ready_for_query = true;
4339  break;
4340 
4341  /*
4342  * 'X' means that the frontend is closing down the socket. EOF
4343  * means unexpected loss of frontend connection. Either way,
4344  * perform normal shutdown.
4345  */
4346  case 'X':
4347  case EOF:
4348 
4349  /*
4350  * Reset whereToSendOutput to prevent ereport from attempting
4351  * to send any more messages to client.
4352  */
4355 
4356  /*
4357  * NOTE: if you are tempted to add more code here, DON'T!
4358  * Whatever you had in mind to do should be set up as an
4359  * on_proc_exit or on_shmem_exit callback, instead. Otherwise
4360  * it will fail to be called during other backend-shutdown
4361  * scenarios.
4362  */
4363  proc_exit(0);
4364 
4365  case 'd': /* copy data */
4366  case 'c': /* copy done */
4367  case 'f': /* copy fail */
4368 
4369  /*
4370  * Accept but ignore these messages, per protocol spec; we
4371  * probably got here because a COPY failed, and the frontend
4372  * is still sending data.
4373  */
4374  break;
4375 
4376  default:
4377  ereport(FATAL,
4378  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4379  errmsg("invalid frontend message type %d",
4380  firstchar)));
4381  }
4382  } /* end of input-reading loop */
4383 }
void InitializeTimeouts(void)
Definition: timeout.c:340
void AbortCurrentTransaction(void)
Definition: xact.c:2984
static void exec_describe_portal_message(const char *portal_name)
Definition: postgres.c:2421
#define SIGQUIT
Definition: win32_port.h:164
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
void BeginReportingGUCOptions(void)
Definition: guc.c:5604
int MyProcPid
Definition: globals.c:40
#define pq_flush()
Definition: libpq.h:39
static int ReadCommand(StringInfo inBuf)
Definition: postgres.c:509
static void finish_xact_command(void)
Definition: postgres.c:2493
void ProcessConfigFile(GucContext context)
bool exec_replication_command(const char *cmd_string)
Definition: walsender.c:1426
#define SIGUSR1
Definition: win32_port.h:177
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:303
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:2994
#define SIGCHLD
Definition: win32_port.h:173
const char * pq_getmsgstring(StringInfo msg)
Definition: pqformat.c:581
static void pq_sendint32(StringInfo buf, int32 i)
Definition: pqformat.h:148
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130
void InitStandaloneProcess(const char *argv0)
Definition: miscinit.c:315
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:370
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void SPICleanup(void)
Definition: spi.c:268
void set_ps_display(const char *activity, bool force)
Definition: ps_status.c:326
static void forbidden_in_wal_sender(char firstchar)
Definition: postgres.c:4393
void proc_exit(int code)
Definition: ipc.c:104
int errcode(int sqlerrcode)
Definition: elog.c:575
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4440
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:390
#define SetProcessingMode(mode)
Definition: miscadmin.h:378
void BaseInit(void)
Definition: postinit.c:524
void checkDataDir(void)
Definition: miscinit.c:97
#define SIGPIPE
Definition: win32_port.h:168
#define SIGUSR2
Definition: win32_port.h:178
unsigned int Oid
Definition: postgres_ext.h:31
volatile bool QueryCancelPending
Definition: globals.c:31
const char * progname
Definition: pg_standby.c:37
void FlushErrorState(void)
Definition: elog.c:1587
#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:2689
signed int int32
Definition: c.h:313
static void exec_execute_message(const char *portal_name, long max_rows)
Definition: postgres.c:1869
static void log_disconnections(int code, Datum arg)
Definition: postgres.c:4560
void jit_reset_after_error(void)
Definition: jit.c:131
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:117
ErrorContextCallback * error_context_stack
Definition: elog.c:88
void pqinitmask(void)
Definition: pqsignal.c:41
bool am_walsender
Definition: walsender.c:115
void disable_all_timeouts(bool keep_indicators)
Definition: timeout.c:596
#define ERROR
Definition: elog.h:43
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1173
bool pq_is_reading_msg(void)
Definition: pqcomm.c:1250
int IdleInTransactionSessionTimeout
Definition: proc.c:63
int32 MyCancelKey
Definition: globals.c:43
void WalSndSignals(void)
Definition: walsender.c:2952
#define FATAL
Definition: elog.h:52
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
void InitProcess(void)
Definition: proc.c:288
Definition: dest.h:88
static char * buf
Definition: pg_test_fsync.c:67
bool IsUnderPostmaster
Definition: globals.c:108
static void exec_bind_message(StringInfo input_message)
Definition: postgres.c:1484
Definition: dest.h:89
#define SIGHUP
Definition: win32_port.h:163
void PostgresSigHupHandler(SIGNAL_ARGS)
Definition: postgres.c:2729
void LocalProcessControlFile(bool reset)
Definition: xlog.c:4861
void ChangeToDataDir(void)
Definition: miscinit.c:211
void ReplicationSlotRelease(void)
Definition: slot.c:416
sigset_t UnBlockSig
Definition: pqsignal.c:22
void PortalErrorCleanup(void)
Definition: portalmem.c:898
static bool stmt_timeout_active
Definition: postgres.c:151
static bool xact_started
Definition: postgres.c:132
void InitWalSender(void)
#define ereport(elevel, rest)
Definition: elog.h:122
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:160
#define AllocSetContextCreate(parent, name, allocparams)
Definition: memutils.h:170
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
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:1221
#define PortalIsValid(p)
Definition: portal.h:201
static void start_xact_command(void)
Definition: postgres.c:2473
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:1592
void WalSndErrorCleanup(void)
Definition: walsender.c:292
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:4932
void EmitErrorReport(void)
Definition: elog.c:1446
static StringInfoData row_description_buf
Definition: postgres.c:172
TimestampTz PgStartTime
Definition: timestamp.c:49
static char * username
Definition: initdb.c:132
#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:565
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:168
int pq_getmsgbyte(StringInfo msg)
Definition: pqformat.c:401
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:428
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
#define pq_comm_reset()
Definition: libpq.h:38
#define SIG_DFL
Definition: win32_port.h:158
void ProcessCompletedNotifies(void)
Definition: async.c:1101
void HandleFunctionRequest(StringInfo msgBuf)
Definition: fastpath.c:259
void InvalidateCatalogSnapshotConditionally(void)
Definition: snapmgr.c:531
static bool DoingCommandRead
Definition: postgres.c:139
void InitializeMaxBackends(void)
Definition: postinit.c:502
char * dbname
Definition: streamutil.c:51
MemoryContext MessageContext
Definition: mcxt.c:48
sigjmp_buf * PG_exception_stack
Definition: elog.c:90
static const char * userDoption
Definition: postgres.c:161
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:732
void * palloc(Size size)
Definition: mcxt.c:924
int errmsg(const char *fmt,...)
Definition: elog.c:797
void PortalDrop(Portal portal, bool isTopCommit)
Definition: portalmem.c:465
void ReadyForQuery(CommandDest dest)
Definition: dest.c:241
void pq_endmessage(StringInfo buf)
Definition: pqformat.c:298
void die(SIGNAL_ARGS)
Definition: postgres.c:2658
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:115
int i
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:2710
static void drop_unnamed_stmt(void)
Definition: postgres.c:2572
void ReplicationSlotCleanup(void)
Definition: slot.c:471
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition: pqformat.c:417
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
bool Log_disconnections
Definition: postgres.c:93
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition: postgres.c:3365
void pq_getmsgend(StringInfo msg)
Definition: pqformat.c:637
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:525
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:261
CommandDest whereToSendOutput
Definition: postgres.c:90
static bool ignore_till_sync
Definition: postgres.c:146
static MemoryContext row_description_context
Definition: postgres.c:171
void quickdie(SIGNAL_ARGS)
Definition: postgres.c:2597
MemoryContext PostmasterContext
Definition: mcxt.c:46
static void exec_simple_query(const char *query_string)
Definition: postgres.c:891
void InitializeGUCOptions(void)
Definition: guc.c:4710
void pgstat_report_stat(bool force)
Definition: pgstat.c:812
void DropPreparedStatement(const char *stmt_name, bool showError)
Definition: prepare.c:580
static void exec_describe_statement_message(const char *stmt_name)
Definition: postgres.c:2325

◆ process_postgres_switches()

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

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

3367 {
3368  bool secure = (ctx == PGC_POSTMASTER);
3369  int errs = 0;
3370  GucSource gucsource;
3371  int flag;
3372 
3373  if (secure)
3374  {
3375  gucsource = PGC_S_ARGV; /* switches came from command line */
3376 
3377  /* Ignore the initial --single argument, if present */
3378  if (argc > 1 && strcmp(argv[1], "--single") == 0)
3379  {
3380  argv++;
3381  argc--;
3382  }
3383  }
3384  else
3385  {
3386  gucsource = PGC_S_CLIENT; /* switches came from client */
3387  }
3388 
3389 #ifdef HAVE_INT_OPTERR
3390 
3391  /*
3392  * Turn this off because it's either printed to stderr and not the log
3393  * where we'd want it, or argv[0] is now "--single", which would make for
3394  * a weird error message. We print our own error message below.
3395  */
3396  opterr = 0;
3397 #endif
3398 
3399  /*
3400  * Parse command-line options. CAUTION: keep this in sync with
3401  * postmaster/postmaster.c (the option sets should not conflict) and with
3402  * the common help() function in main/main.c.
3403  */
3404  while ((flag = getopt(argc, argv, "B:bc:C:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:v:W:-:")) != -1)
3405  {
3406  switch (flag)
3407  {
3408  case 'B':
3409  SetConfigOption("shared_buffers", optarg, ctx, gucsource);
3410  break;
3411 
3412  case 'b':
3413  /* Undocumented flag used for binary upgrades */
3414  if (secure)
3415  IsBinaryUpgrade = true;
3416  break;
3417 
3418  case 'C':
3419  /* ignored for consistency with the postmaster */
3420  break;
3421 
3422  case 'D':
3423  if (secure)
3424  userDoption = strdup(optarg);
3425  break;
3426 
3427  case 'd':
3428  set_debug_options(atoi(optarg), ctx, gucsource);
3429  break;
3430 
3431  case 'E':
3432  if (secure)
3433  EchoQuery = true;
3434  break;
3435 
3436  case 'e':
3437  SetConfigOption("datestyle", "euro", ctx, gucsource);
3438  break;
3439 
3440  case 'F':
3441  SetConfigOption("fsync", "false", ctx, gucsource);
3442  break;
3443 
3444  case 'f':
3445  if (!set_plan_disabling_options(optarg, ctx, gucsource))
3446  errs++;
3447  break;
3448 
3449  case 'h':
3450  SetConfigOption("listen_addresses", optarg, ctx, gucsource);
3451  break;
3452 
3453  case 'i':
3454  SetConfigOption("listen_addresses", "*", ctx, gucsource);
3455  break;
3456 
3457  case 'j':
3458  if (secure)
3459  UseSemiNewlineNewline = true;
3460  break;
3461 
3462  case 'k':
3463  SetConfigOption("unix_socket_directories", optarg, ctx, gucsource);
3464  break;
3465 
3466  case 'l':
3467  SetConfigOption("ssl", "true", ctx, gucsource);
3468  break;
3469 
3470  case 'N':
3471  SetConfigOption("max_connections", optarg, ctx, gucsource);
3472  break;
3473 
3474  case 'n':
3475  /* ignored for consistency with postmaster */
3476  break;
3477 
3478  case 'O':
3479  SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
3480  break;
3481 
3482  case 'o':
3483  errs++;
3484  break;
3485 
3486  case 'P':
3487  SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
3488  break;
3489 
3490  case 'p':
3491  SetConfigOption("port", optarg, ctx, gucsource);
3492  break;
3493 
3494  case 'r':
3495  /* send output (stdout and stderr) to the given file */
3496  if (secure)
3498  break;
3499 
3500  case 'S':
3501  SetConfigOption("work_mem", optarg, ctx, gucsource);
3502  break;
3503 
3504  case 's':
3505  SetConfigOption("log_statement_stats", "true", ctx, gucsource);
3506  break;
3507 
3508  case 'T':
3509  /* ignored for consistency with the postmaster */
3510  break;
3511 
3512  case 't':
3513  {
3514  const char *tmp = get_stats_option_name(optarg);
3515 
3516  if (tmp)
3517  SetConfigOption(tmp, "true", ctx, gucsource);
3518  else
3519  errs++;
3520  break;
3521  }
3522 
3523  case 'v':
3524 
3525  /*
3526  * -v is no longer used in normal operation, since
3527  * FrontendProtocol is already set before we get here. We keep
3528  * the switch only for possible use in standalone operation,
3529  * in case we ever support using normal FE/BE protocol with a
3530  * standalone backend.
3531  */
3532  if (secure)
3534  break;
3535 
3536  case 'W':
3537  SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
3538  break;
3539 
3540  case 'c':
3541  case '-':
3542  {
3543  char *name,
3544  *value;
3545 
3546  ParseLongOption(optarg, &name, &value);
3547  if (!value)
3548  {
3549  if (flag == '-')
3550  ereport(ERROR,
3551  (errcode(ERRCODE_SYNTAX_ERROR),
3552  errmsg("--%s requires a value",
3553  optarg)));
3554  else
3555  ereport(ERROR,
3556  (errcode(ERRCODE_SYNTAX_ERROR),
3557  errmsg("-c %s requires a value",
3558  optarg)));
3559  }
3560  SetConfigOption(name, value, ctx, gucsource);
3561  free(name);
3562  if (value)
3563  free(value);
3564  break;
3565  }
3566 
3567  default:
3568  errs++;
3569  break;
3570  }
3571 
3572  if (errs)
3573  break;
3574  }
3575 
3576  /*
3577  * Optional database name should be there only if *dbname is NULL.
3578  */
3579  if (!errs && dbname && *dbname == NULL && argc - optind >= 1)
3580  *dbname = strdup(argv[optind++]);
3581 
3582  if (errs || argc != optind)
3583  {
3584  if (errs)
3585  optind--; /* complain about the previous argument */
3586 
3587  /* spell the error message a bit differently depending on context */
3588  if (IsUnderPostmaster)
3589  ereport(FATAL,
3590  (errcode(ERRCODE_SYNTAX_ERROR),
3591  errmsg("invalid command-line argument for server process: %s", argv[optind]),
3592  errhint("Try \"%s --help\" for more information.", progname)));
3593  else
3594  ereport(FATAL,
3595  (errcode(ERRCODE_SYNTAX_ERROR),
3596  errmsg("%s: invalid command-line argument: %s",
3597  progname, argv[optind]),
3598  errhint("Try \"%s --help\" for more information.", progname)));
3599  }
3600 
3601  /*
3602  * Reset getopt(3) library so that it will work correctly in subprocesses
3603  * or when this function is called a second time with another array.
3604  */
3605  optind = 1;
3606 #ifdef HAVE_INT_OPTRESET
3607  optreset = 1; /* some systems need this too */
3608 #endif
3609 }
int errhint(const char *fmt,...)
Definition: elog.c:987
void ParseLongOption(const char *string, char **name, char **value)
Definition: guc.c:9649
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition: postgres.c:3283
int errcode(int sqlerrcode)
Definition: elog.c:575
const char * get_stats_option_name(const char *arg)
Definition: postgres.c:3325
void set_debug_options(int debug_flag, GucContext context, GucSource source)
Definition: postgres.c:3254
const char * progname
Definition: pg_standby.c:37
bool IsBinaryUpgrade
Definition: globals.c:109
int getopt(int nargc, char *const *nargv, const char *ostr)
Definition: getopt.c:72
GucSource
Definition: guc.h:105
int optind
Definition: getopt.c:51
#define ERROR
Definition: elog.h:43
#define FATAL
Definition: elog.h:52
#define MAXPGPATH
char OutputFileName[MAXPGPATH]
Definition: globals.c:69
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6917
bool IsUnderPostmaster
Definition: globals.c:108
char * flag(int b)
Definition: test-ctype.c:33
int opterr
Definition: getopt.c:50
#define ereport(elevel, rest)
Definition: elog.h:122
uint32 ProtocolVersion
Definition: pqcomm.h:113
static struct @131 value
#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:51
const char * name
Definition: encode.c:521
static bool EchoQuery
Definition: postgres.c:162
static const char * userDoption
Definition: postgres.c:161
static bool UseSemiNewlineNewline
Definition: postgres.c:163
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * optarg
Definition: getopt.c:53
ProtocolVersion FrontendProtocol
Definition: globals.c:28

◆ ProcessClientReadInterrupt()

void ProcessClientReadInterrupt ( bool  blocked)

Definition at line 529 of file postgres.c.

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

Referenced by interactive_getc(), and secure_read().

530 {
531  int save_errno = errno;
532 
533  if (DoingCommandRead)
534  {
535  /* Check for general interrupts that arrived while reading */
537 
538  /* Process sinval catchup interrupts that happened while reading */
541 
542  /* Process sinval catchup interrupts that happened while reading */
545  }
546  else if (ProcDiePending && blocked)
547  {
548  /*
549  * We're dying. It's safe (and sane) to handle that now.
550  */
552  }
553 
554  errno = save_errno;
555 }
void ProcessCatchupInterrupt(void)
Definition: sinval.c:177
void ProcessNotifyInterrupt(void)
Definition: async.c:1731
static bool DoingCommandRead
Definition: postgres.c:139
volatile bool ProcDiePending
Definition: globals.c:32
volatile sig_atomic_t notifyInterruptPending
Definition: async.c:358
volatile sig_atomic_t catchupInterruptPending
Definition: sinval.c:41
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98

◆ ProcessClientWriteInterrupt()

void ProcessClientWriteInterrupt ( bool  blocked)

Definition at line 567 of file postgres.c.

References CHECK_FOR_INTERRUPTS, DestNone, DestRemote, ProcDiePending, and whereToSendOutput.

Referenced by secure_write().

568 {
569  int save_errno = errno;
570 
571  /*
572  * We only want to process the interrupt here if socket writes are
573  * blocking to increase the chance to get an error message to the client.
574  * If we're not blocked there'll soon be a CHECK_FOR_INTERRUPTS(). But if
575  * we're blocked we'll never get out of that situation if the client has
576  * died.
577  */
578  if (ProcDiePending && blocked)
579  {
580  /*
581  * We're dying. It's safe (and sane) to handle that now. But we don't
582  * want to send the client the error message as that a) would possibly
583  * block again b) would possibly lead to sending an error message to
584  * the client, while we already started to send something else.
585  */
588 
590  }
591 
592  errno = save_errno;
593 }
Definition: dest.h:88
volatile bool ProcDiePending
Definition: globals.c:32
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
CommandDest whereToSendOutput
Definition: postgres.c:90

◆ quickdie()

void quickdie ( SIGNAL_ARGS  )

Definition at line 2597 of file postgres.c.

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

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

2598 {
2599  sigaddset(&BlockSig, SIGQUIT); /* prevent nested calls */
2600  PG_SETMASK(&BlockSig);
2601 
2602  /*
2603  * Prevent interrupts while exiting; though we just blocked signals that
2604  * would queue new interrupts, one may have been pending. We don't want a
2605  * quickdie() downgraded to a mere query cancel.
2606  */
2607  HOLD_INTERRUPTS();
2608 
2609  /*
2610  * If we're aborting out of client auth, don't risk trying to send
2611  * anything to the client; we will likely violate the protocol, not to
2612  * mention that we may have interrupted the guts of OpenSSL or some
2613  * authentication library.
2614  */
2617 
2618  /*
2619  * Ideally this should be ereport(FATAL), but then we'd not get control
2620  * back...
2621  */
2622  ereport(WARNING,
2623  (errcode(ERRCODE_CRASH_SHUTDOWN),
2624  errmsg("terminating connection because of crash of another server process"),
2625  errdetail("The postmaster has commanded this server process to roll back"
2626  " the current transaction and exit, because another"
2627  " server process exited abnormally and possibly corrupted"
2628  " shared memory."),
2629  errhint("In a moment you should be able to reconnect to the"
2630  " database and repeat your command.")));
2631 
2632  /*
2633  * We DO NOT want to run proc_exit() callbacks -- we're here because
2634  * shared memory may be corrupted, so we don't want to try to clean up our
2635  * transaction. Just nail the windows shut and get out of town. Now that
2636  * there's an atexit callback to prevent third-party code from breaking
2637  * things by calling exit() directly, we have to reset the callbacks
2638  * explicitly to make this work as intended.
2639  */
2640  on_exit_reset();
2641 
2642  /*
2643  * Note we do exit(2) not exit(0). This is to force the postmaster into a
2644  * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
2645  * backend. This is necessary precisely because we don't clean up our
2646  * shared memory state. (The "dead man switch" mechanism in pmsignal.c
2647  * should ensure the postmaster sees this as a crash, too, but no harm in
2648  * being doubly sure.)
2649  */
2650  exit(2);
2651 }
#define SIGQUIT
Definition: win32_port.h:164
int errhint(const char *fmt,...)
Definition: elog.c:987
int errcode(int sqlerrcode)
Definition: elog.c:575
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
bool ClientAuthInProgress
Definition: postmaster.c:351
void on_exit_reset(void)
Definition: ipc.c:407
Definition: dest.h:88
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define ereport(elevel, rest)
Definition: elog.h:122
#define WARNING
Definition: elog.h:40
sigset_t BlockSig
Definition: pqsignal.c:22
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:115
CommandDest whereToSendOutput
Definition: postgres.c:90

◆ RecoveryConflictInterrupt()

void RecoveryConflictInterrupt ( ProcSignalReason  reason)

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

2747 {
2748  int save_errno = errno;
2749 
2750  /*
2751  * Don't joggle the elbow of proc_exit
2752  */
2753  if (!proc_exit_inprogress)
2754  {
2755  RecoveryConflictReason = reason;
2756  switch (reason)
2757  {
2759 
2760  /*
2761  * If we aren't waiting for a lock we can never deadlock.
2762  */
2763  if (!IsWaitingForLock())
2764  return;
2765 
2766  /* Intentional fall through to check wait for pin */
2767  /* FALLTHROUGH */
2768 
2770 
2771  /*
2772  * If we aren't blocking the Startup process there is nothing
2773  * more to do.
2774  */
2776  return;
2777 
2779 
2780  /* Intentional fall through to error handling */
2781  /* FALLTHROUGH */
2782 
2786 
2787  /*
2788  * If we aren't in a transaction any longer then ignore.
2789  */
2791  return;
2792 
2793  /*
2794  * If we can abort just the current subtransaction then we are
2795  * OK to throw an ERROR to resolve the conflict. Otherwise
2796  * drop through to the FATAL case.
2797  *
2798  * XXX other times that we can throw just an ERROR *may* be
2799  * PROCSIG_RECOVERY_CONFLICT_LOCK if no locks are held in
2800  * parent transactions
2801  *
2802  * PROCSIG_RECOVERY_CONFLICT_SNAPSHOT if no snapshots are held
2803  * by parent transactions and the transaction is not
2804  * transaction-snapshot mode
2805  *
2806  * PROCSIG_RECOVERY_CONFLICT_TABLESPACE if no temp files or
2807  * cursors open in parent transactions
2808  */
2809  if (!IsSubTransaction())
2810  {
2811  /*
2812  * If we already aborted then we no longer need to cancel.
2813  * We do this here since we do not wish to ignore aborted
2814  * subtransactions, which must cause FATAL, currently.
2815  */
2817  return;
2818 
2819  RecoveryConflictPending = true;
2820  QueryCancelPending = true;
2821  InterruptPending = true;
2822  break;
2823  }
2824 
2825  /* Intentional fall through to session cancel */
2826  /* FALLTHROUGH */
2827 
2829  RecoveryConflictPending = true;
2830  ProcDiePending = true;
2831  InterruptPending = true;
2832  break;
2833 
2834  default:
2835  elog(FATAL, "unrecognized conflict mode: %d",
2836  (int) reason);
2837  }
2838 
2840 
2841  /*
2842  * All conflicts apart from database cause dynamic errors where the
2843  * command or transaction can be retried at a later point with some
2844  * potential for success. No need to reset this, since non-retryable
2845  * conflict errors are currently FATAL.
2846  */
2847  if (reason == PROCSIG_RECOVERY_CONFLICT_DATABASE)
2848  RecoveryConflictRetryable = false;
2849  }
2850 
2851  /*
2852  * Set the process latch. This function essentially emulates signal
2853  * handlers like die() and StatementCancelHandler() and it seems prudent
2854  * to behave similarly as they do.
2855  */
2856  SetLatch(MyLatch);
2857 
2858  errno = save_errno;
2859 }
bool IsWaitingForLock(void)
Definition: proc.c:669
PGPROC * MyProc
Definition: proc.c:67
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:370
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4440
volatile bool QueryCancelPending
Definition: globals.c:31
#define FATAL
Definition: elog.h:52
bool recoveryConflictPending
Definition: proc.h:124
static ProcSignalReason RecoveryConflictReason
Definition: postgres.c:168
static bool RecoveryConflictPending
Definition: postgres.c:166
static bool RecoveryConflictRetryable
Definition: postgres.c:167
volatile bool InterruptPending
Definition: globals.c:30
void SetLatch(volatile Latch *latch)
Definition: latch.c:414
#define Assert(condition)
Definition: c.h:699
bool proc_exit_inprogress
Definition: ipc.c:40
bool HoldingBufferPinThatDelaysRecovery(void)
Definition: bufmgr.c:3692
bool IsSubTransaction(void)
Definition: xact.c:4495
volatile bool ProcDiePending
Definition: globals.c:32
struct Latch * MyLatch
Definition: globals.c:53
#define elog
Definition: elog.h:219

◆ ResetUsage()

void ResetUsage ( void  )

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

4452 {
4454  gettimeofday(&Save_t, NULL);
4455 }
int gettimeofday(struct timeval *tp, struct timezone *tzp)
Definition: gettimeofday.c:105
static struct rusage Save_r
Definition: postgres.c:4447
int getrusage(int who, struct rusage *rusage)
Definition: getrusage.c:31
static struct timeval Save_t
Definition: postgres.c:4448
#define RUSAGE_SELF
Definition: rusagestub.h:23

◆ set_debug_options()

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

Definition at line 3254 of file postgres.c.

References PGC_POSTMASTER, and SetConfigOption().

Referenced by PostmasterMain(), and process_postgres_switches().

3255 {
3256  if (debug_flag > 0)
3257  {
3258  char debugstr[64];
3259 
3260  sprintf(debugstr, "debug%d", debug_flag);
3261  SetConfigOption("log_min_messages", debugstr, context, source);
3262  }
3263  else
3264  SetConfigOption("log_min_messages", "notice", context, source);
3265 
3266  if (debug_flag >= 1 && context == PGC_POSTMASTER)
3267  {
3268  SetConfigOption("log_connections", "true", context, source);
3269  SetConfigOption("log_disconnections", "true", context, source);
3270  }
3271  if (debug_flag >= 2)
3272  SetConfigOption("log_statement", "all", context, source);
3273  if (debug_flag >= 3)
3274  SetConfigOption("debug_print_parse", "true", context, source);
3275  if (debug_flag >= 4)
3276  SetConfigOption("debug_print_plan", "true", context, source);
3277  if (debug_flag >= 5)
3278  SetConfigOption("debug_print_rewritten", "true", context, source);
3279 }
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6917

◆ set_plan_disabling_options()

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

Definition at line 3283 of file postgres.c.

References SetConfigOption().

Referenced by PostmasterMain(), and process_postgres_switches().

3284 {
3285  const char *tmp = NULL;
3286 
3287  switch (arg[0])
3288  {
3289  case 's': /* seqscan */
3290  tmp = "enable_seqscan";
3291  break;
3292  case 'i': /* indexscan */
3293  tmp = "enable_indexscan";
3294  break;
3295  case 'o': /* indexonlyscan */
3296  tmp = "enable_indexonlyscan";
3297  break;
3298  case 'b': /* bitmapscan */
3299  tmp = "enable_bitmapscan";
3300  break;
3301  case 't': /* tidscan */
3302  tmp = "enable_tidscan";
3303  break;
3304  case 'n': /* nestloop */
3305  tmp = "enable_nestloop";
3306  break;
3307  case 'm': /* mergejoin */
3308  tmp = "enable_mergejoin";
3309  break;
3310  case 'h': /* hashjoin */
3311  tmp = "enable_hashjoin";
3312  break;
3313  }
3314  if (tmp)
3315  {
3316  SetConfigOption(tmp, "false", context, source);
3317  return true;
3318  }
3319  else
3320  return false;
3321 }
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6917
void * arg

◆ ShowUsage()

void ShowUsage ( const char *  title)

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

4459 {
4461  struct timeval user,
4462  sys;
4463  struct timeval elapse_t;
4464  struct rusage r;
4465 
4466  getrusage(RUSAGE_SELF, &r);
4467  gettimeofday(&elapse_t, NULL);
4468  memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
4469  memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
4470  if (elapse_t.tv_usec < Save_t.tv_usec)
4471  {
4472  elapse_t.tv_sec--;
4473  elapse_t.tv_usec += 1000000;
4474  }
4475  if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
4476  {
4477  r.ru_utime.tv_sec--;
4478  r.ru_utime.tv_usec += 1000000;
4479  }
4480  if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
4481  {
4482  r.ru_stime.tv_sec--;
4483  r.ru_stime.tv_usec += 1000000;
4484  }
4485 
4486  /*
4487  * The only stats we don't show here are ixrss, idrss, isrss. It takes
4488  * some work to interpret them, and most platforms don't fill them in.
4489  */
4490  initStringInfo(&str);
4491 
4492  appendStringInfoString(&str, "! system usage stats:\n");
4493  appendStringInfo(&str,
4494  "!\t%ld.%06ld s user, %ld.%06ld s system, %ld.%06ld s elapsed\n",
4495  (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
4496  (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
4497  (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
4498  (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec),
4499  (long) (elapse_t.tv_sec - Save_t.tv_sec),
4500  (long) (elapse_t.tv_usec - Save_t.tv_usec));
4501  appendStringInfo(&str,
4502  "!\t[%ld.%06ld s user, %ld.%06ld s system total]\n",
4503  (long) user.tv_sec,
4504  (long) user.tv_usec,
4505  (long) sys.tv_sec,
4506  (long) sys.tv_usec);
4507 #if defined(HAVE_GETRUSAGE)
4508  appendStringInfo(&str,
4509  "!\t%ld kB max resident size\n",
4510 #if defined(__darwin__)
4511  /* in bytes on macOS */
4512  r.ru_maxrss / 1024
4513 #else
4514  /* in kilobytes on most other platforms */
4515  r.ru_maxrss
4516 #endif
4517  );
4518  appendStringInfo(&str,
4519  "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
4520  r.ru_inblock - Save_r.ru_inblock,
4521  /* they only drink coffee at dec */
4522  r.ru_oublock - Save_r.ru_oublock,
4523  r.ru_inblock, r.ru_oublock);
4524  appendStringInfo(&str,
4525  "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
4526  r.ru_majflt - Save_r.ru_majflt,
4527  r.ru_minflt - Save_r.ru_minflt,
4528  r.ru_majflt, r.ru_minflt,
4529  r.ru_nswap - Save_r.ru_nswap,
4530  r.ru_nswap);
4531  appendStringInfo(&str,
4532  "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
4533  r.ru_nsignals - Save_r.ru_nsignals,
4534  r.ru_nsignals,
4535  r.ru_msgrcv - Save_r.ru_msgrcv,
4536  r.ru_msgsnd - Save_r.ru_msgsnd,
4537  r.ru_msgrcv, r.ru_msgsnd);
4538  appendStringInfo(&str,
4539  "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
4540  r.ru_nvcsw - Save_r.ru_nvcsw,
4541  r.ru_nivcsw - Save_r.ru_nivcsw,
4542  r.ru_nvcsw, r.ru_nivcsw);
4543 #endif /* HAVE_GETRUSAGE */
4544 
4545  /* remove trailing newline */
4546  if (str.data[str.len - 1] == '\n')
4547  str.data[--str.len] = '\0';
4548 
4549  ereport(LOG,
4550  (errmsg_internal("%s", title),
4551  errdetail_internal("%s", str.data)));
4552 
4553  pfree(str.data);
4554 }
int gettimeofday(struct timeval *tp, struct timezone *tzp)
Definition: gettimeofday.c:105
static struct rusage Save_r
Definition: postgres.c:4447
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
#define __darwin__
Definition: darwin.h:3
int errdetail_internal(const char *fmt,...)
Definition: elog.c:900
void pfree(void *pointer)
Definition: mcxt.c:1031
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
static struct timeval Save_t
Definition: postgres.c:4448
#define ereport(elevel, rest)
Definition: elog.h:122
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
struct timeval ru_utime
Definition: rusagestub.h:28
#define RUSAGE_SELF
Definition: rusagestub.h:23
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
static char * user
Definition: pg_regress.c:93

◆ StatementCancelHandler()

void StatementCancelHandler ( SIGNAL_ARGS  )

Definition at line 2689 of file postgres.c.

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

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

2690 {
2691  int save_errno = errno;
2692 
2693  /*
2694  * Don't joggle the elbow of proc_exit
2695  */
2696  if (!proc_exit_inprogress)
2697  {
2698  InterruptPending = true;
2699  QueryCancelPending = true;
2700  }
2701 
2702  /* If we're still here, waken anything waiting on the process latch */
2703  SetLatch(MyLatch);
2704 
2705  errno = save_errno;
2706 }
volatile bool QueryCancelPending
Definition: globals.c:31
volatile bool InterruptPending
Definition: globals.c:30
void SetLatch(volatile Latch *latch)
Definition: latch.c:414
bool proc_exit_inprogress
Definition: ipc.c:40
struct Latch * MyLatch
Definition: globals.c:53

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