PostgreSQL Source Code  git master
miscadmin.h File Reference
#include <signal.h>
#include "datatype/timestamp.h"
#include "pgtime.h"
Include dependency graph for miscadmin.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Macros

#define InvalidPid   (-1)
 
#define INTERRUPTS_PENDING_CONDITION()    (unlikely(InterruptPending))
 
#define CHECK_FOR_INTERRUPTS()
 
#define INTERRUPTS_CAN_BE_PROCESSED()
 
#define HOLD_INTERRUPTS()   (InterruptHoldoffCount++)
 
#define RESUME_INTERRUPTS()
 
#define HOLD_CANCEL_INTERRUPTS()   (QueryCancelHoldoffCount++)
 
#define RESUME_CANCEL_INTERRUPTS()
 
#define START_CRIT_SECTION()   (CritSectionCount++)
 
#define END_CRIT_SECTION()
 
#define USE_POSTGRES_DATES   0
 
#define USE_ISO_DATES   1
 
#define USE_SQL_DATES   2
 
#define USE_GERMAN_DATES   3
 
#define USE_XSD_DATES   4
 
#define DATEORDER_YMD   0
 
#define DATEORDER_DMY   1
 
#define DATEORDER_MDY   2
 
#define INTSTYLE_POSTGRES   0
 
#define INTSTYLE_POSTGRES_VERBOSE   1
 
#define INTSTYLE_SQL_STANDARD   2
 
#define INTSTYLE_ISO_8601   3
 
#define MAXTZLEN   10 /* max TZ name len, not counting tr. null */
 
#define SECURITY_LOCAL_USERID_CHANGE   0x0001
 
#define SECURITY_RESTRICTED_OPERATION   0x0002
 
#define SECURITY_NOFORCE_RLS   0x0004
 
#define BACKEND_NUM_TYPES   (B_WAL_WRITER + 1)
 
#define IsBootstrapProcessingMode()   (Mode == BootstrapProcessing)
 
#define IsInitProcessingMode()   (Mode == InitProcessing)
 
#define IsNormalProcessingMode()   (Mode == NormalProcessing)
 
#define GetProcessingMode()   Mode
 
#define SetProcessingMode(mode)
 
#define AmStartupProcess()   (MyAuxProcType == StartupProcess)
 
#define AmBackgroundWriterProcess()   (MyAuxProcType == BgWriterProcess)
 
#define AmArchiverProcess()   (MyAuxProcType == ArchiverProcess)
 
#define AmCheckpointerProcess()   (MyAuxProcType == CheckpointerProcess)
 
#define AmWalWriterProcess()   (MyAuxProcType == WalWriterProcess)
 
#define AmWalReceiverProcess()   (MyAuxProcType == WalReceiverProcess)
 

Typedefs

typedef char * pg_stack_base_t
 
typedef enum BackendType BackendType
 
typedef enum ProcessingMode ProcessingMode
 
typedef void(* shmem_request_hook_type) (void)
 

Enumerations

enum  BackendType {
  B_INVALID = 0 , B_ARCHIVER , B_AUTOVAC_LAUNCHER , B_AUTOVAC_WORKER ,
  B_BACKEND , B_BG_WORKER , B_BG_WRITER , B_CHECKPOINTER ,
  B_LOGGER , B_STANDALONE_BACKEND , B_STARTUP , B_WAL_RECEIVER ,
  B_WAL_SENDER , B_WAL_WRITER
}
 
enum  ProcessingMode { BootstrapProcessing , InitProcessing , NormalProcessing }
 
enum  AuxProcType {
  NotAnAuxProcess = -1 , StartupProcess = 0 , BgWriterProcess , ArchiverProcess ,
  CheckpointerProcess , WalWriterProcess , WalReceiverProcess , NUM_AUXPROCTYPES
}
 

Functions

void ProcessInterrupts (void)
 
pg_stack_base_t set_stack_base (void)
 
void restore_stack_base (pg_stack_base_t base)
 
void check_stack_depth (void)
 
bool stack_is_too_deep (void)
 
void PreventCommandIfReadOnly (const char *cmdname)
 
void PreventCommandIfParallelMode (const char *cmdname)
 
void PreventCommandDuringRecovery (const char *cmdname)
 
int trace_recovery (int trace_level)
 
void InitPostmasterChild (void)
 
void InitStandaloneProcess (const char *argv0)
 
void InitProcessLocalLatch (void)
 
void SwitchToSharedLatch (void)
 
void SwitchBackToLocalLatch (void)
 
const char * GetBackendTypeDesc (BackendType backendType)
 
void SetDatabasePath (const char *path)
 
void checkDataDir (void)
 
void SetDataDir (const char *dir)
 
void ChangeToDataDir (void)
 
char * GetUserNameFromId (Oid roleid, bool noerr)
 
Oid GetUserId (void)
 
Oid GetOuterUserId (void)
 
Oid GetSessionUserId (void)
 
Oid GetAuthenticatedUserId (void)
 
void GetUserIdAndSecContext (Oid *userid, int *sec_context)
 
void SetUserIdAndSecContext (Oid userid, int sec_context)
 
bool InLocalUserIdChange (void)
 
bool InSecurityRestrictedOperation (void)
 
bool InNoForceRLSOperation (void)
 
void GetUserIdAndContext (Oid *userid, bool *sec_def_context)
 
void SetUserIdAndContext (Oid userid, bool sec_def_context)
 
void InitializeSessionUserId (const char *rolename, Oid roleid)
 
void InitializeSessionUserIdStandalone (void)
 
void SetSessionAuthorization (Oid userid, bool is_superuser)
 
Oid GetCurrentRoleId (void)
 
void SetCurrentRoleId (Oid roleid, bool is_superuser)
 
void InitializeSystemUser (const char *authn_id, const char *auth_method)
 
const char * GetSystemUser (void)
 
bool superuser (void)
 
bool superuser_arg (Oid roleid)
 
void pg_split_opts (char **argv, int *argcp, const char *optstr)
 
void InitializeMaxBackends (void)
 
void InitPostgres (const char *in_dbname, Oid dboid, const char *username, Oid useroid, bool load_session_libraries, bool override_allow_connections, char *out_dbname)
 
void BaseInit (void)
 
void CreateDataDirLockFile (bool amPostmaster)
 
void CreateSocketLockFile (const char *socketfile, bool amPostmaster, const char *socketDir)
 
void TouchSocketLockFiles (void)
 
void AddToDataDirLockFile (int target_line, const char *str)
 
bool RecheckDataDirLockFile (void)
 
void ValidatePgVersion (const char *path)
 
void process_shared_preload_libraries (void)
 
void process_session_preload_libraries (void)
 
void process_shmem_requests (void)
 
void pg_bindtextdomain (const char *domain)
 
bool has_rolreplication (Oid roleid)
 
Size EstimateClientConnectionInfoSpace (void)
 
void SerializeClientConnectionInfo (Size maxsize, char *start_address)
 
void RestoreClientConnectionInfo (char *conninfo)
 
size_t get_hash_memory_limit (void)
 

Variables

PGDLLIMPORT volatile sig_atomic_t InterruptPending
 
PGDLLIMPORT volatile sig_atomic_t QueryCancelPending
 
PGDLLIMPORT volatile sig_atomic_t ProcDiePending
 
PGDLLIMPORT volatile sig_atomic_t IdleInTransactionSessionTimeoutPending
 
PGDLLIMPORT volatile sig_atomic_t IdleSessionTimeoutPending
 
PGDLLIMPORT volatile sig_atomic_t ProcSignalBarrierPending
 
PGDLLIMPORT volatile sig_atomic_t LogMemoryContextPending
 
PGDLLIMPORT volatile sig_atomic_t IdleStatsUpdateTimeoutPending
 
PGDLLIMPORT volatile sig_atomic_t CheckClientConnectionPending
 
PGDLLIMPORT volatile sig_atomic_t ClientConnectionLost
 
PGDLLIMPORT volatile uint32 InterruptHoldoffCount
 
PGDLLIMPORT volatile uint32 QueryCancelHoldoffCount
 
PGDLLIMPORT volatile uint32 CritSectionCount
 
PGDLLIMPORT pid_t PostmasterPid
 
PGDLLIMPORT bool IsPostmasterEnvironment
 
PGDLLIMPORT bool IsUnderPostmaster
 
PGDLLIMPORT bool IsBackgroundWorker
 
PGDLLIMPORT bool IsBinaryUpgrade
 
PGDLLIMPORT bool ExitOnAnyError
 
PGDLLIMPORT char * DataDir
 
PGDLLIMPORT int data_directory_mode
 
PGDLLIMPORT int NBuffers
 
PGDLLIMPORT int MaxBackends
 
PGDLLIMPORT int MaxConnections
 
PGDLLIMPORT int max_worker_processes
 
PGDLLIMPORT int max_parallel_workers
 
PGDLLIMPORT int MyProcPid
 
PGDLLIMPORT pg_time_t MyStartTime
 
PGDLLIMPORT TimestampTz MyStartTimestamp
 
PGDLLIMPORT struct PortMyProcPort
 
PGDLLIMPORT struct LatchMyLatch
 
PGDLLIMPORT int32 MyCancelKey
 
PGDLLIMPORT int MyPMChildSlot
 
PGDLLIMPORT char OutputFileName []
 
PGDLLIMPORT char my_exec_path []
 
PGDLLIMPORT char pkglib_path []
 
PGDLLIMPORT Oid MyDatabaseId
 
PGDLLIMPORT Oid MyDatabaseTableSpace
 
PGDLLIMPORT int DateStyle
 
PGDLLIMPORT int DateOrder
 
PGDLLIMPORT int IntervalStyle
 
PGDLLIMPORT bool enableFsync
 
PGDLLIMPORT bool allowSystemTableMods
 
PGDLLIMPORT int work_mem
 
PGDLLIMPORT double hash_mem_multiplier
 
PGDLLIMPORT int maintenance_work_mem
 
PGDLLIMPORT int max_parallel_maintenance_workers
 
PGDLLIMPORT int VacuumCostPageHit
 
PGDLLIMPORT int VacuumCostPageMiss
 
PGDLLIMPORT int VacuumCostPageDirty
 
PGDLLIMPORT int VacuumCostLimit
 
PGDLLIMPORT double VacuumCostDelay
 
PGDLLIMPORT int64 VacuumPageHit
 
PGDLLIMPORT int64 VacuumPageMiss
 
PGDLLIMPORT int64 VacuumPageDirty
 
PGDLLIMPORT int VacuumCostBalance
 
PGDLLIMPORT bool VacuumCostActive
 
PGDLLIMPORT int trace_recovery_messages
 
PGDLLIMPORT char * DatabasePath
 
PGDLLIMPORT BackendType MyBackendType
 
PGDLLIMPORT ProcessingMode Mode
 
PGDLLIMPORT AuxProcType MyAuxProcType
 
PGDLLIMPORT bool IgnoreSystemIndexes
 
PGDLLIMPORT bool process_shared_preload_libraries_in_progress
 
PGDLLIMPORT bool process_shared_preload_libraries_done
 
PGDLLIMPORT bool process_shmem_requests_in_progress
 
PGDLLIMPORT char * session_preload_libraries_string
 
PGDLLIMPORT char * shared_preload_libraries_string
 
PGDLLIMPORT char * local_preload_libraries_string
 
PGDLLIMPORT shmem_request_hook_type shmem_request_hook
 

Macro Definition Documentation

◆ AmArchiverProcess

#define AmArchiverProcess ( )    (MyAuxProcType == ArchiverProcess)

Definition at line 445 of file miscadmin.h.

◆ AmBackgroundWriterProcess

#define AmBackgroundWriterProcess ( )    (MyAuxProcType == BgWriterProcess)

Definition at line 444 of file miscadmin.h.

◆ AmCheckpointerProcess

#define AmCheckpointerProcess ( )    (MyAuxProcType == CheckpointerProcess)

Definition at line 446 of file miscadmin.h.

◆ AmStartupProcess

#define AmStartupProcess ( )    (MyAuxProcType == StartupProcess)

Definition at line 443 of file miscadmin.h.

◆ AmWalReceiverProcess

#define AmWalReceiverProcess ( )    (MyAuxProcType == WalReceiverProcess)

Definition at line 448 of file miscadmin.h.

◆ AmWalWriterProcess

#define AmWalWriterProcess ( )    (MyAuxProcType == WalWriterProcess)

Definition at line 447 of file miscadmin.h.

◆ BACKEND_NUM_TYPES

#define BACKEND_NUM_TYPES   (B_WAL_WRITER + 1)

Definition at line 335 of file miscadmin.h.

◆ CHECK_FOR_INTERRUPTS

#define CHECK_FOR_INTERRUPTS ( )
Value:
do { \
ProcessInterrupts(); \
} while(0)
#define INTERRUPTS_PENDING_CONDITION()
Definition: miscadmin.h:112

Definition at line 121 of file miscadmin.h.

◆ DATEORDER_DMY

#define DATEORDER_DMY   1

Definition at line 237 of file miscadmin.h.

◆ DATEORDER_MDY

#define DATEORDER_MDY   2

Definition at line 238 of file miscadmin.h.

◆ DATEORDER_YMD

#define DATEORDER_YMD   0

Definition at line 236 of file miscadmin.h.

◆ END_CRIT_SECTION

#define END_CRIT_SECTION ( )
Value:
do { \
Assert(CritSectionCount > 0); \
CritSectionCount--; \
} while(0)
PGDLLIMPORT volatile uint32 CritSectionCount
Definition: globals.c:42

Definition at line 150 of file miscadmin.h.

◆ GetProcessingMode

#define GetProcessingMode ( )    Mode

Definition at line 409 of file miscadmin.h.

◆ HOLD_CANCEL_INTERRUPTS

#define HOLD_CANCEL_INTERRUPTS ( )    (QueryCancelHoldoffCount++)

Definition at line 140 of file miscadmin.h.

◆ HOLD_INTERRUPTS

#define HOLD_INTERRUPTS ( )    (InterruptHoldoffCount++)

Definition at line 132 of file miscadmin.h.

◆ INTERRUPTS_CAN_BE_PROCESSED

#define INTERRUPTS_CAN_BE_PROCESSED ( )
Value:
QueryCancelHoldoffCount == 0)
PGDLLIMPORT volatile uint32 InterruptHoldoffCount
Definition: globals.c:40

Definition at line 128 of file miscadmin.h.

◆ INTERRUPTS_PENDING_CONDITION

#define INTERRUPTS_PENDING_CONDITION ( )     (unlikely(InterruptPending))

Definition at line 112 of file miscadmin.h.

◆ INTSTYLE_ISO_8601

#define INTSTYLE_ISO_8601   3

Definition at line 253 of file miscadmin.h.

◆ INTSTYLE_POSTGRES

#define INTSTYLE_POSTGRES   0

Definition at line 250 of file miscadmin.h.

◆ INTSTYLE_POSTGRES_VERBOSE

#define INTSTYLE_POSTGRES_VERBOSE   1

Definition at line 251 of file miscadmin.h.

◆ INTSTYLE_SQL_STANDARD

#define INTSTYLE_SQL_STANDARD   2

Definition at line 252 of file miscadmin.h.

◆ InvalidPid

#define InvalidPid   (-1)

Definition at line 32 of file miscadmin.h.

◆ IsBootstrapProcessingMode

#define IsBootstrapProcessingMode ( )    (Mode == BootstrapProcessing)

Definition at line 405 of file miscadmin.h.

◆ IsInitProcessingMode

#define IsInitProcessingMode ( )    (Mode == InitProcessing)

Definition at line 406 of file miscadmin.h.

◆ IsNormalProcessingMode

#define IsNormalProcessingMode ( )    (Mode == NormalProcessing)

Definition at line 407 of file miscadmin.h.

◆ MAXTZLEN

#define MAXTZLEN   10 /* max TZ name len, not counting tr. null */

Definition at line 257 of file miscadmin.h.

◆ RESUME_CANCEL_INTERRUPTS

#define RESUME_CANCEL_INTERRUPTS ( )
Value:
do { \
Assert(QueryCancelHoldoffCount > 0); \
QueryCancelHoldoffCount--; \
} while(0)
PGDLLIMPORT volatile uint32 QueryCancelHoldoffCount
Definition: globals.c:41

Definition at line 142 of file miscadmin.h.

◆ RESUME_INTERRUPTS

#define RESUME_INTERRUPTS ( )
Value:
do { \
Assert(InterruptHoldoffCount > 0); \
InterruptHoldoffCount--; \
} while(0)

Definition at line 134 of file miscadmin.h.

◆ SECURITY_LOCAL_USERID_CHANGE

#define SECURITY_LOCAL_USERID_CHANGE   0x0001

Definition at line 304 of file miscadmin.h.

◆ SECURITY_NOFORCE_RLS

#define SECURITY_NOFORCE_RLS   0x0004

Definition at line 306 of file miscadmin.h.

◆ SECURITY_RESTRICTED_OPERATION

#define SECURITY_RESTRICTED_OPERATION   0x0002

Definition at line 305 of file miscadmin.h.

◆ SetProcessingMode

#define SetProcessingMode (   mode)
Value:
do { \
Assert((mode) == BootstrapProcessing || \
(mode) == InitProcessing || \
Mode = (mode); \
} while(0)
@ NormalProcessing
Definition: miscadmin.h:400
@ InitProcessing
Definition: miscadmin.h:399
@ BootstrapProcessing
Definition: miscadmin.h:398
static PgChecksumMode mode
Definition: pg_checksums.c:65

Definition at line 411 of file miscadmin.h.

◆ START_CRIT_SECTION

#define START_CRIT_SECTION ( )    (CritSectionCount++)

Definition at line 148 of file miscadmin.h.

◆ USE_GERMAN_DATES

#define USE_GERMAN_DATES   3

Definition at line 232 of file miscadmin.h.

◆ USE_ISO_DATES

#define USE_ISO_DATES   1

Definition at line 230 of file miscadmin.h.

◆ USE_POSTGRES_DATES

#define USE_POSTGRES_DATES   0

Definition at line 229 of file miscadmin.h.

◆ USE_SQL_DATES

#define USE_SQL_DATES   2

Definition at line 231 of file miscadmin.h.

◆ USE_XSD_DATES

#define USE_XSD_DATES   4

Definition at line 233 of file miscadmin.h.

Typedef Documentation

◆ BackendType

typedef enum BackendType BackendType

◆ pg_stack_base_t

typedef char* pg_stack_base_t

Definition at line 282 of file miscadmin.h.

◆ ProcessingMode

◆ shmem_request_hook_type

typedef void(* shmem_request_hook_type) (void)

Definition at line 488 of file miscadmin.h.

Enumeration Type Documentation

◆ AuxProcType

Enumerator
NotAnAuxProcess 
StartupProcess 
BgWriterProcess 
ArchiverProcess 
CheckpointerProcess 
WalWriterProcess 
WalReceiverProcess 
NUM_AUXPROCTYPES 

Definition at line 428 of file miscadmin.h.

429 {
430  NotAnAuxProcess = -1,
431  StartupProcess = 0,
437 
438  NUM_AUXPROCTYPES /* Must be last! */
439 } AuxProcType;
AuxProcType
Definition: miscadmin.h:429
@ BgWriterProcess
Definition: miscadmin.h:432
@ StartupProcess
Definition: miscadmin.h:431
@ NUM_AUXPROCTYPES
Definition: miscadmin.h:438
@ NotAnAuxProcess
Definition: miscadmin.h:430
@ ArchiverProcess
Definition: miscadmin.h:433
@ WalWriterProcess
Definition: miscadmin.h:435
@ WalReceiverProcess
Definition: miscadmin.h:436
@ CheckpointerProcess
Definition: miscadmin.h:434

◆ BackendType

Enumerator
B_INVALID 
B_ARCHIVER 
B_AUTOVAC_LAUNCHER 
B_AUTOVAC_WORKER 
B_BACKEND 
B_BG_WORKER 
B_BG_WRITER 
B_CHECKPOINTER 
B_LOGGER 
B_STANDALONE_BACKEND 
B_STARTUP 
B_WAL_RECEIVER 
B_WAL_SENDER 
B_WAL_WRITER 

Definition at line 317 of file miscadmin.h.

318 {
319  B_INVALID = 0,
320  B_ARCHIVER,
323  B_BACKEND,
324  B_BG_WORKER,
325  B_BG_WRITER,
327  B_LOGGER,
329  B_STARTUP,
331  B_WAL_SENDER,
332  B_WAL_WRITER,
333 } BackendType;
BackendType
Definition: miscadmin.h:318
@ B_WAL_WRITER
Definition: miscadmin.h:332
@ B_WAL_RECEIVER
Definition: miscadmin.h:330
@ B_CHECKPOINTER
Definition: miscadmin.h:326
@ B_WAL_SENDER
Definition: miscadmin.h:331
@ B_LOGGER
Definition: miscadmin.h:327
@ B_STARTUP
Definition: miscadmin.h:329
@ B_BG_WORKER
Definition: miscadmin.h:324
@ B_INVALID
Definition: miscadmin.h:319
@ B_STANDALONE_BACKEND
Definition: miscadmin.h:328
@ B_BG_WRITER
Definition: miscadmin.h:325
@ B_BACKEND
Definition: miscadmin.h:323
@ B_ARCHIVER
Definition: miscadmin.h:320
@ B_AUTOVAC_LAUNCHER
Definition: miscadmin.h:321
@ B_AUTOVAC_WORKER
Definition: miscadmin.h:322

◆ ProcessingMode

Enumerator
BootstrapProcessing 
InitProcessing 
NormalProcessing 

Definition at line 396 of file miscadmin.h.

397 {
398  BootstrapProcessing, /* bootstrap creation of template database */
399  InitProcessing, /* initializing system */
400  NormalProcessing /* normal processing */
ProcessingMode
Definition: miscadmin.h:397

Function Documentation

◆ AddToDataDirLockFile()

void AddToDataDirLockFile ( int  target_line,
const char *  str 
)

Definition at line 1515 of file miscinit.c.

1516 {
1517  int fd;
1518  int len;
1519  int lineno;
1520  char *srcptr;
1521  char *destptr;
1522  char srcbuffer[BLCKSZ];
1523  char destbuffer[BLCKSZ];
1524 
1525  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1526  if (fd < 0)
1527  {
1528  ereport(LOG,
1530  errmsg("could not open file \"%s\": %m",
1532  return;
1533  }
1535  len = read(fd, srcbuffer, sizeof(srcbuffer) - 1);
1537  if (len < 0)
1538  {
1539  ereport(LOG,
1541  errmsg("could not read from file \"%s\": %m",
1543  close(fd);
1544  return;
1545  }
1546  srcbuffer[len] = '\0';
1547 
1548  /*
1549  * Advance over lines we are not supposed to rewrite, then copy them to
1550  * destbuffer.
1551  */
1552  srcptr = srcbuffer;
1553  for (lineno = 1; lineno < target_line; lineno++)
1554  {
1555  char *eol = strchr(srcptr, '\n');
1556 
1557  if (eol == NULL)
1558  break; /* not enough lines in file yet */
1559  srcptr = eol + 1;
1560  }
1561  memcpy(destbuffer, srcbuffer, srcptr - srcbuffer);
1562  destptr = destbuffer + (srcptr - srcbuffer);
1563 
1564  /*
1565  * Fill in any missing lines before the target line, in case lines are
1566  * added to the file out of order.
1567  */
1568  for (; lineno < target_line; lineno++)
1569  {
1570  if (destptr < destbuffer + sizeof(destbuffer))
1571  *destptr++ = '\n';
1572  }
1573 
1574  /*
1575  * Write or rewrite the target line.
1576  */
1577  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s\n", str);
1578  destptr += strlen(destptr);
1579 
1580  /*
1581  * If there are more lines in the old file, append them to destbuffer.
1582  */
1583  if ((srcptr = strchr(srcptr, '\n')) != NULL)
1584  {
1585  srcptr++;
1586  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s",
1587  srcptr);
1588  }
1589 
1590  /*
1591  * And rewrite the data. Since we write in a single kernel call, this
1592  * update should appear atomic to onlookers.
1593  */
1594  len = strlen(destbuffer);
1595  errno = 0;
1597  if (pg_pwrite(fd, destbuffer, len, 0) != len)
1598  {
1600  /* if write didn't set errno, assume problem is no disk space */
1601  if (errno == 0)
1602  errno = ENOSPC;
1603  ereport(LOG,
1605  errmsg("could not write to file \"%s\": %m",
1607  close(fd);
1608  return;
1609  }
1612  if (pg_fsync(fd) != 0)
1613  {
1614  ereport(LOG,
1616  errmsg("could not write to file \"%s\": %m",
1618  }
1620  if (close(fd) != 0)
1621  {
1622  ereport(LOG,
1624  errmsg("could not write to file \"%s\": %m",
1626  }
1627 }
#define PG_BINARY
Definition: c.h:1260
int errcode_for_file_access(void)
Definition: elog.c:881
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define LOG
Definition: elog.h:31
#define ereport(elevel,...)
Definition: elog.h:149
int pg_fsync(int fd)
Definition: fd.c:356
#define close(a)
Definition: win32.h:12
#define read(a, b, c)
Definition: win32.h:13
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:59
const void size_t len
#define pg_pwrite
Definition: port.h:226
#define snprintf
Definition: port.h:238
static int fd(const char *x, int i)
Definition: preproc-init.c:105
@ WAIT_EVENT_LOCK_FILE_ADDTODATADIR_WRITE
Definition: wait_event.h:189
@ WAIT_EVENT_LOCK_FILE_ADDTODATADIR_READ
Definition: wait_event.h:187
@ WAIT_EVENT_LOCK_FILE_ADDTODATADIR_SYNC
Definition: wait_event.h:188
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:271
static void pgstat_report_wait_end(void)
Definition: wait_event.h:287

References close, DIRECTORY_LOCK_FILE, ereport, errcode_for_file_access(), errmsg(), fd(), len, LOG, PG_BINARY, pg_fsync(), pg_pwrite, pgstat_report_wait_end(), pgstat_report_wait_start(), read, snprintf, generate_unaccent_rules::str, WAIT_EVENT_LOCK_FILE_ADDTODATADIR_READ, WAIT_EVENT_LOCK_FILE_ADDTODATADIR_SYNC, and WAIT_EVENT_LOCK_FILE_ADDTODATADIR_WRITE.

Referenced by InternalIpcMemoryCreate(), PostmasterMain(), process_pm_child_exit(), process_pm_pmsignal(), and process_pm_shutdown_request().

◆ BaseInit()

void BaseInit ( void  )

Definition at line 636 of file postinit.c.

637 {
638  Assert(MyProc != NULL);
639 
640  /*
641  * Initialize our input/output/debugging file descriptors.
642  */
643  DebugFileOpen();
644 
645  /*
646  * Initialize file access. Done early so other subsystems can access
647  * files.
648  */
649  InitFileAccess();
650 
651  /*
652  * Initialize statistics reporting. This needs to happen early to ensure
653  * that pgstat's shutdown callback runs after the shutdown callbacks of
654  * all subsystems that can produce stats (like e.g. transaction commits
655  * can).
656  */
658 
659  /* Do local initialization of storage and buffer managers */
660  InitSync();
661  smgrinit();
663 
664  /*
665  * Initialize temporary file access after pgstat, so that the temporary
666  * file shutdown hook can report temporary file statistics.
667  */
669 
670  /*
671  * Initialize local buffers for WAL record construction, in case we ever
672  * try to insert XLOG.
673  */
674  InitXLogInsert();
675 
676  /*
677  * Initialize replication slots after pgstat. The exit hook might need to
678  * drop ephemeral slots, which in turn triggers stats reporting.
679  */
681 }
void InitBufferPoolAccess(void)
Definition: bufmgr.c:2659
void DebugFileOpen(void)
Definition: elog.c:2066
void InitFileAccess(void)
Definition: fd.c:809
void InitTemporaryFileAccess(void)
Definition: fd.c:839
Assert(fmt[strlen(fmt) - 1] !='\n')
void pgstat_initialize(void)
Definition: pgstat.c:533
void ReplicationSlotInitialize(void)
Definition: slot.c:170
void smgrinit(void)
Definition: smgr.c:111
PGPROC * MyProc
Definition: proc.c:66
void InitSync(void)
Definition: sync.c:131
void InitXLogInsert(void)
Definition: xloginsert.c:1298

References Assert(), DebugFileOpen(), InitBufferPoolAccess(), InitFileAccess(), InitSync(), InitTemporaryFileAccess(), InitXLogInsert(), MyProc, pgstat_initialize(), ReplicationSlotInitialize(), and smgrinit().

Referenced by AutoVacLauncherMain(), AutoVacWorkerMain(), AuxiliaryProcessMain(), BootstrapModeMain(), PostgresMain(), and StartBackgroundWorker().

◆ ChangeToDataDir()

void ChangeToDataDir ( void  )

Definition at line 449 of file miscinit.c.

450 {
451  Assert(DataDir);
452 
453  if (chdir(DataDir) < 0)
454  ereport(FATAL,
456  errmsg("could not change directory to \"%s\": %m",
457  DataDir)));
458 }
#define FATAL
Definition: elog.h:41
char * DataDir
Definition: globals.c:66

References Assert(), DataDir, ereport, errcode_for_file_access(), errmsg(), and FATAL.

Referenced by BootstrapModeMain(), PostgresSingleUserMain(), and PostmasterMain().

◆ check_stack_depth()

void check_stack_depth ( void  )

Definition at line 3461 of file postgres.c.

3462 {
3463  if (stack_is_too_deep())
3464  {
3465  ereport(ERROR,
3466  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3467  errmsg("stack depth limit exceeded"),
3468  errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3469  "after ensuring the platform's stack depth limit is adequate.",
3470  max_stack_depth)));
3471  }
3472 }
int errhint(const char *fmt,...)
Definition: elog.c:1316
int errcode(int sqlerrcode)
Definition: elog.c:858
#define ERROR
Definition: elog.h:39
int max_stack_depth
Definition: postgres.c:92
bool stack_is_too_deep(void)
Definition: postgres.c:3475

References ereport, errcode(), errhint(), errmsg(), ERROR, max_stack_depth, and stack_is_too_deep().

Referenced by _jumbleNode(), AlterTypeRecurse(), apply_scanjoin_target_to_paths(), checkCond(), clean_NOT_intree(), clean_stopword_intree(), cntsize(), contains_required_value(), convertJsonbValue(), copyObjectImpl(), Cover(), create_plan_recurse(), datum_to_json(), datum_to_jsonb(), dofindsubquery(), emit_jsp_gin_entries(), equal(), EventTriggerInvoke(), ExecEndNode(), ExecEvalSubPlan(), ExecInitExprRec(), ExecInitNode(), ExecMakeFunctionResultSet(), ExecProcNodeFirst(), ExecShutdownNode_walker(), execute(), executeAnyItem(), executeItemOptUnwrapTarget(), expand_partitioned_rtentry(), expression_tree_mutator_impl(), expression_tree_walker_impl(), extract_jsp_bool_expr(), fillQT(), find_composite_type_dependencies(), find_matching_subplans_recurse(), findoprnd(), findoprnd_recurse(), flatten_grouping_sets(), flattenJsonPathParseItem(), FreePageManagerDumpBtree(), freetree(), generate_partition_qual(), generate_partitionwise_join_paths(), get_query_def(), get_rels_with_domain(), get_rule_expr(), get_setop_query(), get_steps_using_prefix_recurse(), gistSplit(), hash_range(), hash_range_extended(), hash_record(), hash_record_extended(), hk_depth_search(), infix(), inline_set_returning_function(), int_query_opr_selec(), is_simple_union_all_recurse(), JsonbDeepContains(), lseg_inside_poly(), ltree_execute(), makepol(), maketree(), MatchText(), MultiExecProcNode(), outNode(), parse_array(), parse_object(), parseNodeString(), plainnode(), planstate_tree_walker_impl(), plperl_hash_from_tuple(), plperl_sv_to_datum(), PLy_input_setup_func(), PLy_output_setup_func(), populate_array_dim_jsonb(), populate_record_field(), printJsonPathItem(), pull_up_sublinks_jointree_recurse(), pull_up_subqueries_recurse(), QT2QTN(), QTNBinary(), QTNClearFlags(), QTNCopy(), QTNFree(), QTNodeCompare(), QTNSort(), QTNTernary(), range_cmp(), range_in(), range_out(), range_recv(), range_send(), raw_expression_tree_walker_impl(), record_cmp(), record_eq(), record_in(), record_out(), record_recv(), record_send(), recurse_set_operations(), regex_selectivity_sub(), relation_is_updatable(), resolve_special_varno(), set_append_rel_size(), setPath(), split_array(), SplitToVariants(), standard_ProcessUtility(), transformExprRecurse(), transformFromClauseItem(), transformSetOperationTree(), traverse_lacons(), try_partitionwise_join(), TS_execute_locations_recurse(), TS_execute_recurse(), TS_phrase_execute(), tsquery_opr_selec(), and tsquery_requires_match().

◆ checkDataDir()

void checkDataDir ( void  )

Definition at line 336 of file miscinit.c.

337 {
338  struct stat stat_buf;
339 
340  Assert(DataDir);
341 
342  if (stat(DataDir, &stat_buf) != 0)
343  {
344  if (errno == ENOENT)
345  ereport(FATAL,
347  errmsg("data directory \"%s\" does not exist",
348  DataDir)));
349  else
350  ereport(FATAL,
352  errmsg("could not read permissions of directory \"%s\": %m",
353  DataDir)));
354  }
355 
356  /* eventual chdir would fail anyway, but let's test ... */
357  if (!S_ISDIR(stat_buf.st_mode))
358  ereport(FATAL,
359  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
360  errmsg("specified data directory \"%s\" is not a directory",
361  DataDir)));
362 
363  /*
364  * Check that the directory belongs to my userid; if not, reject.
365  *
366  * This check is an essential part of the interlock that prevents two
367  * postmasters from starting in the same directory (see CreateLockFile()).
368  * Do not remove or weaken it.
369  *
370  * XXX can we safely enable this check on Windows?
371  */
372 #if !defined(WIN32) && !defined(__CYGWIN__)
373  if (stat_buf.st_uid != geteuid())
374  ereport(FATAL,
375  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
376  errmsg("data directory \"%s\" has wrong ownership",
377  DataDir),
378  errhint("The server must be started by the user that owns the data directory.")));
379 #endif
380 
381  /*
382  * Check if the directory has correct permissions. If not, reject.
383  *
384  * Only two possible modes are allowed, 0700 and 0750. The latter mode
385  * indicates that group read/execute should be allowed on all newly
386  * created files and directories.
387  *
388  * XXX temporarily suppress check when on Windows, because there may not
389  * be proper support for Unix-y file permissions. Need to think of a
390  * reasonable check to apply on Windows.
391  */
392 #if !defined(WIN32) && !defined(__CYGWIN__)
393  if (stat_buf.st_mode & PG_MODE_MASK_GROUP)
394  ereport(FATAL,
395  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
396  errmsg("data directory \"%s\" has invalid permissions",
397  DataDir),
398  errdetail("Permissions should be u=rwx (0700) or u=rwx,g=rx (0750).")));
399 #endif
400 
401  /*
402  * Reset creation modes and mask based on the mode of the data directory.
403  *
404  * The mask was set earlier in startup to disallow group permissions on
405  * newly created files and directories. However, if group read/execute
406  * are present on the data directory then modify the create modes and mask
407  * to allow group read/execute on newly created files and directories and
408  * set the data_directory_mode GUC.
409  *
410  * Suppress when on Windows, because there may not be proper support for
411  * Unix-y file permissions.
412  */
413 #if !defined(WIN32) && !defined(__CYGWIN__)
414  SetDataDirectoryCreatePerm(stat_buf.st_mode);
415 
416  umask(pg_mode_mask);
418 #endif
419 
420  /* Check for PG_VERSION */
422 }
int errdetail(const char *fmt,...)
Definition: elog.c:1202
void SetDataDirectoryCreatePerm(int dataDirMode)
Definition: file_perm.c:34
int pg_mode_mask
Definition: file_perm.c:25
int pg_dir_create_mode
Definition: file_perm.c:18
#define PG_MODE_MASK_GROUP
Definition: file_perm.h:29
int data_directory_mode
Definition: globals.c:72
void ValidatePgVersion(const char *path)
Definition: miscinit.c:1714
#define stat
Definition: win32_port.h:286
#define S_ISDIR(m)
Definition: win32_port.h:327

References Assert(), data_directory_mode, DataDir, ereport, errcode(), errcode_for_file_access(), errdetail(), errhint(), errmsg(), FATAL, pg_dir_create_mode, pg_mode_mask, PG_MODE_MASK_GROUP, S_ISDIR, SetDataDirectoryCreatePerm(), stat::st_mode, stat::st_uid, stat, and ValidatePgVersion().

Referenced by BootstrapModeMain(), PostgresSingleUserMain(), and PostmasterMain().

◆ CreateDataDirLockFile()

void CreateDataDirLockFile ( bool  amPostmaster)

Definition at line 1459 of file miscinit.c.

1460 {
1461  CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, "", true, DataDir);
1462 }
static void CreateLockFile(const char *filename, bool amPostmaster, const char *socketDir, bool isDDLock, const char *refName)
Definition: miscinit.c:1154

References CreateLockFile(), DataDir, and DIRECTORY_LOCK_FILE.

Referenced by BootstrapModeMain(), PostgresSingleUserMain(), and PostmasterMain().

◆ CreateSocketLockFile()

void CreateSocketLockFile ( const char *  socketfile,
bool  amPostmaster,
const char *  socketDir 
)

Definition at line 1468 of file miscinit.c.

1470 {
1471  char lockfile[MAXPGPATH];
1472 
1473  snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
1474  CreateLockFile(lockfile, amPostmaster, socketDir, false, socketfile);
1475 }
#define MAXPGPATH

References CreateLockFile(), MAXPGPATH, and snprintf.

Referenced by Lock_AF_UNIX().

◆ EstimateClientConnectionInfoSpace()

Size EstimateClientConnectionInfoSpace ( void  )

Definition at line 1031 of file miscinit.c.

1032 {
1033  Size size = 0;
1034 
1035  size = add_size(size, sizeof(SerializedClientConnectionInfo));
1036 
1038  size = add_size(size, strlen(MyClientConnectionInfo.authn_id) + 1);
1039 
1040  return size;
1041 }
size_t Size
Definition: c.h:589
ClientConnectionInfo MyClientConnectionInfo
Definition: miscinit.c:1014
Size add_size(Size s1, Size s2)
Definition: shmem.c:502
const char * authn_id
Definition: libpq-be.h:113

References add_size(), ClientConnectionInfo::authn_id, and MyClientConnectionInfo.

Referenced by InitializeParallelDSM().

◆ get_hash_memory_limit()

size_t get_hash_memory_limit ( void  )

Definition at line 3390 of file nodeHash.c.

3391 {
3392  double mem_limit;
3393 
3394  /* Do initial calculation in double arithmetic */
3395  mem_limit = (double) work_mem * hash_mem_multiplier * 1024.0;
3396 
3397  /* Clamp in case it doesn't fit in size_t */
3398  mem_limit = Min(mem_limit, (double) SIZE_MAX);
3399 
3400  return (size_t) mem_limit;
3401 }
#define Min(x, y)
Definition: c.h:988
double hash_mem_multiplier
Definition: globals.c:126
int work_mem
Definition: globals.c:125

References hash_mem_multiplier, Min, and work_mem.

Referenced by BuildTupleHashTableExt(), choose_hashed_setop(), consider_groupingsets_paths(), cost_memoize_rescan(), create_unique_path(), ExecChooseHashTableSize(), ExecInitMemoize(), ExecParallelHashIncreaseNumBatches(), final_cost_hashjoin(), hash_agg_set_limits(), hash_choose_num_partitions(), subpath_is_hashable(), and subplan_is_hashable().

◆ GetAuthenticatedUserId()

Oid GetAuthenticatedUserId ( void  )

Definition at line 579 of file miscinit.c.

580 {
582  return AuthenticatedUserId;
583 }
#define OidIsValid(objectId)
Definition: c.h:759
static Oid AuthenticatedUserId
Definition: miscinit.c:489

References Assert(), AuthenticatedUserId, and OidIsValid.

Referenced by InitializeParallelDSM().

◆ GetBackendTypeDesc()

const char* GetBackendTypeDesc ( BackendType  backendType)

Definition at line 264 of file miscinit.c.

265 {
266  const char *backendDesc = "unknown process type";
267 
268  switch (backendType)
269  {
270  case B_INVALID:
271  backendDesc = "not initialized";
272  break;
273  case B_ARCHIVER:
274  backendDesc = "archiver";
275  break;
276  case B_AUTOVAC_LAUNCHER:
277  backendDesc = "autovacuum launcher";
278  break;
279  case B_AUTOVAC_WORKER:
280  backendDesc = "autovacuum worker";
281  break;
282  case B_BACKEND:
283  backendDesc = "client backend";
284  break;
285  case B_BG_WORKER:
286  backendDesc = "background worker";
287  break;
288  case B_BG_WRITER:
289  backendDesc = "background writer";
290  break;
291  case B_CHECKPOINTER:
292  backendDesc = "checkpointer";
293  break;
294  case B_LOGGER:
295  backendDesc = "logger";
296  break;
298  backendDesc = "standalone backend";
299  break;
300  case B_STARTUP:
301  backendDesc = "startup";
302  break;
303  case B_WAL_RECEIVER:
304  backendDesc = "walreceiver";
305  break;
306  case B_WAL_SENDER:
307  backendDesc = "walsender";
308  break;
309  case B_WAL_WRITER:
310  backendDesc = "walwriter";
311  break;
312  }
313 
314  return backendDesc;
315 }

References B_ARCHIVER, B_AUTOVAC_LAUNCHER, B_AUTOVAC_WORKER, B_BACKEND, B_BG_WORKER, B_BG_WRITER, B_CHECKPOINTER, B_INVALID, B_LOGGER, B_STANDALONE_BACKEND, B_STARTUP, B_WAL_RECEIVER, B_WAL_SENDER, and B_WAL_WRITER.

Referenced by BackendInitialize(), get_backend_type_for_log(), init_ps_display(), pg_stat_get_activity(), and pg_stat_get_io().

◆ GetCurrentRoleId()

Oid GetCurrentRoleId ( void  )

Definition at line 928 of file miscinit.c.

929 {
930  if (SetRoleIsActive)
931  return OuterUserId;
932  else
933  return InvalidOid;
934 }
static Oid OuterUserId
Definition: miscinit.c:491
static bool SetRoleIsActive
Definition: miscinit.c:502
#define InvalidOid
Definition: postgres_ext.h:36

References InvalidOid, OuterUserId, and SetRoleIsActive.

Referenced by InitializeParallelDSM(), and show_role().

◆ GetOuterUserId()

Oid GetOuterUserId ( void  )

Definition at line 521 of file miscinit.c.

522 {
524  return OuterUserId;
525 }

References Assert(), OidIsValid, and OuterUserId.

Referenced by DropRole(), and RenameRole().

◆ GetSessionUserId()

Oid GetSessionUserId ( void  )

Definition at line 544 of file miscinit.c.

545 {
547  return SessionUserId;
548 }
static Oid SessionUserId
Definition: miscinit.c:490

References Assert(), OidIsValid, and SessionUserId.

Referenced by check_role(), DropRole(), get_rolespec_oid(), get_rolespec_tuple(), InitPostgres(), pgstat_bestart(), RenameRole(), and session_user().

◆ GetSystemUser()

const char* GetSystemUser ( void  )

Definition at line 570 of file miscinit.c.

571 {
572  return SystemUser;
573 }
static const char * SystemUser
Definition: miscinit.c:493

References SystemUser.

Referenced by system_user().

◆ GetUserId()

Oid GetUserId ( void  )

Definition at line 510 of file miscinit.c.

511 {
513  return CurrentUserId;
514 }
static Oid CurrentUserId
Definition: miscinit.c:492

References Assert(), CurrentUserId, and OidIsValid.

Referenced by AggregateCreate(), AlterCollation(), AlterDatabase(), AlterDatabaseOwner(), AlterDatabaseRefreshColl(), AlterDatabaseSet(), AlterEventTrigger(), AlterEventTriggerOwner_internal(), AlterExtensionNamespace(), AlterForeignServer(), AlterForeignServerOwner_internal(), AlterFunction(), AlterObjectNamespace_internal(), AlterObjectOwner_internal(), AlterObjectRename_internal(), AlterOperator(), AlterOpFamilyAdd(), AlterPublication(), AlterPublicationOwner_internal(), AlterRole(), AlterRoleSet(), AlterSchemaOwner_internal(), AlterStatistics(), AlterSubscription(), AlterSubscriptionOwner_internal(), AlterSystemSetConfigFile(), AlterTableMoveAll(), AlterTableSpaceOptions(), AlterTSConfiguration(), AlterTSDictionary(), AlterType(), AlterTypeNamespace_oid(), AlterTypeOwner(), ATExecAddColumn(), ATExecChangeOwner(), ATPrepAlterColumnType(), ATPrepSetTableSpace(), ATSimplePermissions(), bbsink_server_new(), be_lo_put(), be_lo_unlink(), binary_upgrade_create_empty_extension(), brin_desummarize_range(), BuildCachedPlan(), BuildDescForRelation(), BuildIndexValueDescription(), calculate_database_size(), calculate_tablespace_size(), call_pltcl_start_proc(), check_enable_rls(), check_temp_tablespaces(), CheckCachedPlan(), checkDomainOwner(), checkEnumOwner(), checkFkeyPermissions(), CheckFunctionValidatorAccess(), CheckMyDatabase(), CheckSlotPermissions(), CommentObject(), compile_plperl_function(), compile_pltcl_function(), CompleteCachedPlan(), compute_return_type(), ConfigOptionIsVisible(), convert_and_check_filename(), CreateCast(), CreateConversionCommand(), createdb(), CreateEventTrigger(), CreateExtensionInternal(), CreateForeignDataWrapper(), CreateForeignServer(), CreateForeignTable(), CreateFunction(), CreateOpFamily(), CreateProceduralLanguage(), CreatePublication(), CreateRole(), CreateStatistics(), CreateSubscription(), CreateTableSpace(), CreateTransform(), CreateTriggerFiringOn(), current_user(), currtid_internal(), currval_oid(), DefineAggregate(), DefineCollation(), DefineDomain(), DefineEnum(), DefineIndex(), DefineOpClass(), DefineOperator(), DefineOpFamily(), DefineQueryRewrite(), DefineRange(), DefineRelation(), DefineTSConfiguration(), DefineTSDictionary(), DefineType(), do_setval(), DoCopy(), dropdb(), DropOwnedObjects(), DropRole(), DropSubscription(), DropTableSpace(), emit_audit_message(), EnableDisableRule(), examine_simple_variable(), examine_variable(), ExecAlterDefaultPrivilegesStmt(), ExecAlterExtensionContentsStmt(), ExecAlterExtensionStmt(), ExecAlterObjectDependsStmt(), ExecBuildGroupingEqual(), ExecBuildParamSetEqual(), ExecBuildSlotPartitionKeyDescription(), ExecBuildSlotValueDescription(), ExecCheckOneRelPerms(), ExecGetResultRelCheckAsUser(), ExecGrant_Attribute(), ExecGrant_common(), ExecGrant_Largeobject(), ExecGrant_Parameter(), ExecGrant_Relation(), ExecInitAgg(), ExecInitExprRec(), ExecInitFunc(), ExecInitWindowAgg(), ExecReindex(), ExecSecLabelStmt(), execute_extension_script(), ExecuteCallStmt(), ExecuteDoStmt(), ExecuteGrantStmt(), ExecuteTruncateGuts(), extension_is_trusted(), file_fdw_validator(), findRangeCanonicalFunction(), findRangeSubtypeDiffFunction(), FinishPreparedTransaction(), get_connect_string(), get_other_operator(), get_rel_from_relname(), get_rolespec_oid(), get_rolespec_tuple(), get_row_security_policies(), get_tables_to_cluster(), GetConfigOptionValues(), gin_clean_pending_list(), GrantRole(), HandleFunctionRequest(), has_any_column_privilege_id(), has_any_column_privilege_name(), has_column_privilege_id_attnum(), has_column_privilege_id_name(), has_column_privilege_name_attnum(), has_column_privilege_name_name(), has_database_privilege_id(), has_database_privilege_name(), has_foreign_data_wrapper_privilege_id(), has_foreign_data_wrapper_privilege_name(), has_function_privilege_id(), has_function_privilege_name(), has_language_privilege_id(), has_language_privilege_name(), has_parameter_privilege_name(), has_schema_privilege_id(), has_schema_privilege_name(), has_sequence_privilege_id(), has_sequence_privilege_name(), has_server_privilege_id(), has_server_privilege_name(), has_table_privilege_id(), has_table_privilege_name(), has_tablespace_privilege_id(), has_tablespace_privilege_name(), has_type_privilege_id(), has_type_privilege_name(), have_createdb_privilege(), have_createrole_privilege(), heap_force_common(), ImportForeignSchema(), init_sexpr(), InitializeSearchPath(), InitPostgres(), InitTempTableNamespace(), inline_function(), inline_set_returning_function(), insert_username(), interpret_function_parameter_list(), inv_create(), inv_open(), LargeObjectCreate(), lastval(), LockViewRecurse(), LogicalRepSyncTableStart(), lookup_agg_function(), LookupCreationNamespace(), LookupExplicitNamespace(), MergeAttributes(), movedb(), nextval_internal(), OperatorCreate(), OperatorShellMake(), pg_has_role_id(), pg_has_role_name(), pg_import_system_collations(), pg_prewarm(), pg_sequence_last_value(), pg_sequence_parameters(), pg_signal_backend(), pg_stat_get_wal_receiver(), pg_stat_get_wal_senders(), pg_stat_statements_internal(), pgrowlocks(), pgss_store(), pgstat_get_backend_current_activity(), pltcl_fetch_interp(), postgresBeginDirectModify(), postgresBeginForeignScan(), postgresExecForeignTruncate(), postgresGetForeignRelSize(), postgresImportForeignSchema(), PrepareTempTablespaces(), PrepareTransaction(), PublicationAddTables(), RangeVarCallbackForAlterRelation(), RangeVarCallbackForDropRelation(), RangeVarCallbackForLockTable(), RangeVarCallbackForPolicy(), RangeVarCallbackForReindexIndex(), RangeVarCallbackForRenameRule(), RangeVarCallbackForRenameTrigger(), RangeVarCallbackMaintainsTable(), RangeVarCallbackOwnsRelation(), RangeVarGetAndCheckCreationNamespace(), ReassignOwnedObjects(), recomputeNamespacePath(), REGRESS_exec_check_perms(), REGRESS_object_access_hook(), REGRESS_object_access_hook_str(), REGRESS_utility_command(), ReindexMultipleInternal(), ReindexMultipleTables(), RemoveObjects(), renameatt_check(), RenameDatabase(), RenameRole(), RenameSchema(), RenameTableSpace(), RenameType(), RevalidateCachedQuery(), RI_Initial_Check(), ri_ReportViolation(), select_perl_context(), set_config_option(), set_foreign_rel_properties(), shell_check_detail(), standard_ProcessUtility(), statext_is_compatible_clause(), superuser(), TargetPrivilegesCheck(), TerminateOtherDBBackends(), transformTableLikeClause(), truncate_check_perms(), user_mapping_ddl_aclcheck(), vacuum_is_permitted_for_relation(), validate_option_array_item(), ValidateJoinEstimator(), and ValidateRestrictionEstimator().

◆ GetUserIdAndContext()

void GetUserIdAndContext ( Oid userid,
bool sec_def_context 
)

Definition at line 680 of file miscinit.c.

681 {
682  *userid = CurrentUserId;
683  *sec_def_context = InLocalUserIdChange();
684 }
bool InLocalUserIdChange(void)
Definition: miscinit.c:649

References CurrentUserId, and InLocalUserIdChange().

◆ GetUserIdAndSecContext()

◆ GetUserNameFromId()

char* GetUserNameFromId ( Oid  roleid,
bool  noerr 
)

Definition at line 984 of file miscinit.c.

985 {
986  HeapTuple tuple;
987  char *result;
988 
989  tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
990  if (!HeapTupleIsValid(tuple))
991  {
992  if (!noerr)
993  ereport(ERROR,
994  (errcode(ERRCODE_UNDEFINED_OBJECT),
995  errmsg("invalid role OID: %u", roleid)));
996  result = NULL;
997  }
998  else
999  {
1000  result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
1001  ReleaseSysCache(tuple);
1002  }
1003  return result;
1004 }
#define NameStr(name)
Definition: c.h:730
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
char * pstrdup(const char *in)
Definition: mcxt.c:1624
NameData rolname
Definition: pg_authid.h:34
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:56
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:865
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:817
@ AUTHOID
Definition: syscache.h:45

References AUTHOID, ereport, errcode(), errmsg(), ERROR, GETSTRUCT, HeapTupleIsValid, NameStr, ObjectIdGetDatum(), pstrdup(), ReleaseSysCache(), rolname, and SearchSysCache1().

Referenced by AddRoleMems(), check_can_set_role(), check_object_ownership(), check_role_grantor(), check_role_membership_authorization(), current_user(), DelRoleMems(), DropOwnedObjects(), execute_extension_script(), getObjectDescription(), getObjectIdentityParts(), insert_username(), LogicalRepSyncTableStart(), ReassignOwnedObjects(), regroleout(), session_user(), and TargetPrivilegesCheck().

◆ has_rolreplication()

bool has_rolreplication ( Oid  roleid)

Definition at line 707 of file miscinit.c.

708 {
709  bool result = false;
710  HeapTuple utup;
711 
712  /* Superusers bypass all permission checking. */
713  if (superuser_arg(roleid))
714  return true;
715 
716  utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
717  if (HeapTupleIsValid(utup))
718  {
719  result = ((Form_pg_authid) GETSTRUCT(utup))->rolreplication;
720  ReleaseSysCache(utup);
721  }
722  return result;
723 }
bool rolreplication
Definition: pg_authid.h:40
bool superuser_arg(Oid roleid)
Definition: superuser.c:56

References AUTHOID, GETSTRUCT, HeapTupleIsValid, ObjectIdGetDatum(), ReleaseSysCache(), rolreplication, SearchSysCache1(), and superuser_arg().

Referenced by AlterRole(), CheckSlotPermissions(), CreateRole(), and InitPostgres().

◆ InitializeMaxBackends()

void InitializeMaxBackends ( void  )

Definition at line 566 of file postinit.c.

567 {
568  Assert(MaxBackends == 0);
569 
570  /* the extra unit accounts for the autovacuum launcher */
573 
574  /* internal error because the values were all checked previously */
576  elog(ERROR, "too many backends configured");
577 }
int autovacuum_max_workers
Definition: autovacuum.c:117
int MaxConnections
Definition: globals.c:137
int MaxBackends
Definition: globals.c:140
int max_worker_processes
Definition: globals.c:138
#define MAX_BACKENDS
Definition: postmaster.h:78
int max_wal_senders
Definition: walsender.c:122

References Assert(), autovacuum_max_workers, elog(), ERROR, MAX_BACKENDS, max_wal_senders, max_worker_processes, MaxBackends, and MaxConnections.

Referenced by BootstrapModeMain(), PostgresSingleUserMain(), and PostmasterMain().

◆ InitializeSessionUserId()

void InitializeSessionUserId ( const char *  rolename,
Oid  roleid 
)

Definition at line 729 of file miscinit.c.

730 {
731  HeapTuple roleTup;
732  Form_pg_authid rform;
733  char *rname;
734 
735  /*
736  * Don't do scans if we're bootstrapping, none of the system catalogs
737  * exist yet, and they should be owned by postgres anyway.
738  */
740 
741  /* call only once */
743 
744  /*
745  * Make sure syscache entries are flushed for recent catalog changes. This
746  * allows us to find roles that were created on-the-fly during
747  * authentication.
748  */
750 
751  if (rolename != NULL)
752  {
753  roleTup = SearchSysCache1(AUTHNAME, PointerGetDatum(rolename));
754  if (!HeapTupleIsValid(roleTup))
755  ereport(FATAL,
756  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
757  errmsg("role \"%s\" does not exist", rolename)));
758  }
759  else
760  {
761  roleTup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
762  if (!HeapTupleIsValid(roleTup))
763  ereport(FATAL,
764  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
765  errmsg("role with OID %u does not exist", roleid)));
766  }
767 
768  rform = (Form_pg_authid) GETSTRUCT(roleTup);
769  roleid = rform->oid;
770  rname = NameStr(rform->rolname);
771 
772  AuthenticatedUserId = roleid;
773  AuthenticatedUserIsSuperuser = rform->rolsuper;
774 
775  /* This sets OuterUserId/CurrentUserId too */
777 
778  /* Also mark our PGPROC entry with the authenticated user id */
779  /* (We assume this is an atomic store so no lock is needed) */
780  MyProc->roleId = roleid;
781 
782  /*
783  * These next checks are not enforced when in standalone mode, so that
784  * there is a way to recover from sillinesses like "UPDATE pg_authid SET
785  * rolcanlogin = false;".
786  */
787  if (IsUnderPostmaster)
788  {
789  /*
790  * Is role allowed to login at all?
791  */
792  if (!rform->rolcanlogin)
793  ereport(FATAL,
794  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
795  errmsg("role \"%s\" is not permitted to log in",
796  rname)));
797 
798  /*
799  * Check connection limit for this role.
800  *
801  * There is a race condition here --- we create our PGPROC before
802  * checking for other PGPROCs. If two backends did this at about the
803  * same time, they might both think they were over the limit, while
804  * ideally one should succeed and one fail. Getting that to work
805  * exactly seems more trouble than it is worth, however; instead we
806  * just document that the connection limit is approximate.
807  */
808  if (rform->rolconnlimit >= 0 &&
810  CountUserBackends(roleid) > rform->rolconnlimit)
811  ereport(FATAL,
812  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
813  errmsg("too many connections for role \"%s\"",
814  rname)));
815  }
816 
817  /* Record username and superuser status as GUC settings too */
818  SetConfigOption("session_authorization", rname,
820  SetConfigOption("is_superuser",
821  AuthenticatedUserIsSuperuser ? "on" : "off",
823 
824  ReleaseSysCache(roleTup);
825 }
bool IsUnderPostmaster
Definition: globals.c:113
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:4176
@ PGC_S_DYNAMIC_DEFAULT
Definition: guc.h:110
@ PGC_S_OVERRIDE
Definition: guc.h:119
@ PGC_INTERNAL
Definition: guc.h:69
@ PGC_BACKEND
Definition: guc.h:73
void AcceptInvalidationMessages(void)
Definition: inval.c:746
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:405
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:496
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:552
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:322
int CountUserBackends(Oid roleid)
Definition: procarray.c:3689
Oid roleId
Definition: proc.h:199
@ AUTHNAME
Definition: syscache.h:44

References AcceptInvalidationMessages(), Assert(), AuthenticatedUserId, AuthenticatedUserIsSuperuser, AUTHNAME, AUTHOID, CountUserBackends(), ereport, errcode(), errmsg(), FATAL, GETSTRUCT, HeapTupleIsValid, IsBootstrapProcessingMode, IsUnderPostmaster, MyProc, NameStr, ObjectIdGetDatum(), OidIsValid, PGC_BACKEND, PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT, PGC_S_OVERRIDE, PointerGetDatum(), ReleaseSysCache(), PGPROC::roleId, SearchSysCache1(), SetConfigOption(), and SetSessionUserId().

Referenced by InitPostgres().

◆ InitializeSessionUserIdStandalone()

void InitializeSessionUserIdStandalone ( void  )

Definition at line 832 of file miscinit.c.

833 {
834  /*
835  * This function should only be called in single-user mode, in autovacuum
836  * workers, and in background workers.
837  */
839 
840  /* call only once */
842 
843  AuthenticatedUserId = BOOTSTRAP_SUPERUSERID;
845 
846  SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
847 }
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3321
bool IsBackgroundWorker
Definition: globals.c:115

References Assert(), AuthenticatedUserId, AuthenticatedUserIsSuperuser, IsAutoVacuumWorkerProcess(), IsBackgroundWorker, IsUnderPostmaster, OidIsValid, and SetSessionUserId().

Referenced by InitPostgres().

◆ InitializeSystemUser()

void InitializeSystemUser ( const char *  authn_id,
const char *  auth_method 
)

Definition at line 855 of file miscinit.c.

856 {
857  char *system_user;
858 
859  /* call only once */
860  Assert(SystemUser == NULL);
861 
862  /*
863  * InitializeSystemUser should be called only when authn_id is not NULL,
864  * meaning that auth_method is valid.
865  */
866  Assert(authn_id != NULL);
867 
868  system_user = psprintf("%s:%s", auth_method, authn_id);
869 
870  /* Store SystemUser in long-lived storage */
873 }
void pfree(void *pointer)
Definition: mcxt.c:1436
MemoryContext TopMemoryContext
Definition: mcxt.c:141
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1611
Datum system_user(PG_FUNCTION_ARGS)
Definition: miscinit.c:879
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46

References Assert(), MemoryContextStrdup(), pfree(), psprintf(), system_user(), SystemUser, and TopMemoryContext.

Referenced by InitPostgres(), and ParallelWorkerMain().

◆ InitPostgres()

void InitPostgres ( const char *  in_dbname,
Oid  dboid,
const char *  username,
Oid  useroid,
bool  load_session_libraries,
bool  override_allow_connections,
char *  out_dbname 
)

Definition at line 725 of file postinit.c.

730 {
731  bool bootstrap = IsBootstrapProcessingMode();
732  bool am_superuser;
733  char *fullpath;
734  char dbname[NAMEDATALEN];
735  int nfree = 0;
736 
737  elog(DEBUG3, "InitPostgres");
738 
739  /*
740  * Add my PGPROC struct to the ProcArray.
741  *
742  * Once I have done this, I am visible to other backends!
743  */
745 
746  /*
747  * Initialize my entry in the shared-invalidation manager's array of
748  * per-backend data.
749  *
750  * Sets up MyBackendId, a unique backend identifier.
751  */
753 
754  SharedInvalBackendInit(false);
755 
756  if (MyBackendId > MaxBackends || MyBackendId <= 0)
757  elog(FATAL, "bad backend ID: %d", MyBackendId);
758 
759  /* Now that we have a BackendId, we can participate in ProcSignal */
761 
762  /*
763  * Also set up timeout handlers needed for backend operation. We need
764  * these in every case except bootstrap.
765  */
766  if (!bootstrap)
767  {
777  }
778 
779  /*
780  * If this is either a bootstrap process or a standalone backend, start up
781  * the XLOG machinery, and register to have it closed down at exit. In
782  * other cases, the startup process is responsible for starting up the
783  * XLOG machinery, and the checkpointer for closing it down.
784  */
785  if (!IsUnderPostmaster)
786  {
787  /*
788  * We don't yet have an aux-process resource owner, but StartupXLOG
789  * and ShutdownXLOG will need one. Hence, create said resource owner
790  * (and register a callback to clean it up after ShutdownXLOG runs).
791  */
793 
794  StartupXLOG();
795  /* Release (and warn about) any buffer pins leaked in StartupXLOG */
797  /* Reset CurrentResourceOwner to nothing for the moment */
798  CurrentResourceOwner = NULL;
799 
800  /*
801  * Use before_shmem_exit() so that ShutdownXLOG() can rely on DSM
802  * segments etc to work (which in turn is required for pgstats).
803  */
806  }
807 
808  /*
809  * Initialize the relation cache and the system catalog caches. Note that
810  * no catalog access happens here; we only set up the hashtable structure.
811  * We must do this before starting a transaction because transaction abort
812  * would try to touch these hashtables.
813  */
816  InitPlanCache();
817 
818  /* Initialize portal manager */
820 
821  /* Initialize status reporting */
822  pgstat_beinit();
823 
824  /*
825  * Load relcache entries for the shared system catalogs. This must create
826  * at least entries for pg_database and catalogs used for authentication.
827  */
829 
830  /*
831  * Set up process-exit callback to do pre-shutdown cleanup. This is the
832  * one of the first before_shmem_exit callbacks we register; thus, this
833  * will be one the last things we do before low-level modules like the
834  * buffer manager begin to close down. We need to have this in place
835  * before we begin our first transaction --- if we fail during the
836  * initialization transaction, as is entirely possible, we need the
837  * AbortTransaction call to clean up.
838  */
840 
841  /* The autovacuum launcher is done here */
843  {
844  /* report this backend in the PgBackendStatus array */
845  pgstat_bestart();
846 
847  return;
848  }
849 
850  /*
851  * Start a new transaction here before first access to db, and get a
852  * snapshot. We don't have a use for the snapshot itself, but we're
853  * interested in the secondary effect that it sets RecentGlobalXmin. (This
854  * is critical for anything that reads heap pages, because HOT may decide
855  * to prune them even if the process doesn't attempt to modify any
856  * tuples.)
857  *
858  * FIXME: This comment is inaccurate / the code buggy. A snapshot that is
859  * not pushed/active does not reliably prevent HOT pruning (->xmin could
860  * e.g. be cleared when cache invalidations are processed).
861  */
862  if (!bootstrap)
863  {
864  /* statement_timestamp must be set for timeouts to work correctly */
867 
868  /*
869  * transaction_isolation will have been set to the default by the
870  * above. If the default is "serializable", and we are in hot
871  * standby, we will fail if we don't change it to something lower.
872  * Fortunately, "read committed" is plenty good enough.
873  */
875 
876  (void) GetTransactionSnapshot();
877  }
878 
879  /*
880  * Perform client authentication if necessary, then figure out our
881  * postgres user ID, and see if we are a superuser.
882  *
883  * In standalone mode and in autovacuum worker processes, we use a fixed
884  * ID, otherwise we figure it out from the authenticated user name.
885  */
886  if (bootstrap || IsAutoVacuumWorkerProcess())
887  {
889  am_superuser = true;
890  }
891  else if (!IsUnderPostmaster)
892  {
894  am_superuser = true;
895  if (!ThereIsAtLeastOneRole())
897  (errcode(ERRCODE_UNDEFINED_OBJECT),
898  errmsg("no roles are defined in this database system"),
899  errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
900  username != NULL ? username : "postgres")));
901  }
902  else if (IsBackgroundWorker)
903  {
904  if (username == NULL && !OidIsValid(useroid))
905  {
907  am_superuser = true;
908  }
909  else
910  {
912  am_superuser = superuser();
913  }
914  }
915  else
916  {
917  /* normal multiuser case */
918  Assert(MyProcPort != NULL);
921  /* ensure that auth_method is actually valid, aka authn_id is not NULL */
925  am_superuser = superuser();
926  }
927 
928  /*
929  * Binary upgrades only allowed super-user connections
930  */
931  if (IsBinaryUpgrade && !am_superuser)
932  {
933  ereport(FATAL,
934  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
935  errmsg("must be superuser to connect in binary upgrade mode")));
936  }
937 
938  /*
939  * The last few connection slots are reserved for superusers and roles with
940  * privileges of pg_use_reserved_connections. Replication connections are
941  * drawn from slots reserved with max_wal_senders and are not limited by
942  * max_connections, superuser_reserved_connections, or
943  * reserved_connections.
944  *
945  * Note: At this point, the new backend has already claimed a proc struct,
946  * so we must check whether the number of free slots is strictly less than
947  * the reserved connection limits.
948  */
949  if (!am_superuser && !am_walsender &&
952  {
953  if (nfree < SuperuserReservedConnections)
954  ereport(FATAL,
955  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
956  errmsg("remaining connection slots are reserved for roles with %s",
957  "SUPERUSER")));
958 
959  if (!has_privs_of_role(GetUserId(), ROLE_PG_USE_RESERVED_CONNECTIONS))
960  ereport(FATAL,
961  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
962  errmsg("remaining connection slots are reserved for roles with privileges of the \"%s\" role",
963  "pg_use_reserved_connections")));
964  }
965 
966  /* Check replication permissions needed for walsender processes. */
967  if (am_walsender)
968  {
969  Assert(!bootstrap);
970 
972  ereport(FATAL,
973  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
974  errmsg("permission denied to start WAL sender"),
975  errdetail("Only roles with the %s attribute may start a WAL sender process.",
976  "REPLICATION")));
977  }
978 
979  /*
980  * If this is a plain walsender only supporting physical replication, we
981  * don't want to connect to any particular database. Just finish the
982  * backend startup by processing any options from the startup packet, and
983  * we're done.
984  */
986  {
987  /* process any options passed in the startup packet */
988  if (MyProcPort != NULL)
989  process_startup_options(MyProcPort, am_superuser);
990 
991  /* Apply PostAuthDelay as soon as we've read all options */
992  if (PostAuthDelay > 0)
993  pg_usleep(PostAuthDelay * 1000000L);
994 
995  /* initialize client encoding */
997 
998  /* report this backend in the PgBackendStatus array */
999  pgstat_bestart();
1000 
1001  /* close the transaction we started above */
1003 
1004  return;
1005  }
1006 
1007  /*
1008  * Set up the global variables holding database id and default tablespace.
1009  * But note we won't actually try to touch the database just yet.
1010  *
1011  * We take a shortcut in the bootstrap case, otherwise we have to look up
1012  * the db's entry in pg_database.
1013  */
1014  if (bootstrap)
1015  {
1016  MyDatabaseId = Template1DbOid;
1017  MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
1018  }
1019  else if (in_dbname != NULL)
1020  {
1021  HeapTuple tuple;
1022  Form_pg_database dbform;
1023 
1024  tuple = GetDatabaseTuple(in_dbname);
1025  if (!HeapTupleIsValid(tuple))
1026  ereport(FATAL,
1027  (errcode(ERRCODE_UNDEFINED_DATABASE),
1028  errmsg("database \"%s\" does not exist", in_dbname)));
1029  dbform = (Form_pg_database) GETSTRUCT(tuple);
1030  MyDatabaseId = dbform->oid;
1031  MyDatabaseTableSpace = dbform->dattablespace;
1032  /* take database name from the caller, just for paranoia */
1033  strlcpy(dbname, in_dbname, sizeof(dbname));
1034  }
1035  else if (OidIsValid(dboid))
1036  {
1037  /* caller specified database by OID */
1038  HeapTuple tuple;
1039  Form_pg_database dbform;
1040 
1041  tuple = GetDatabaseTupleByOid(dboid);
1042  if (!HeapTupleIsValid(tuple))
1043  ereport(FATAL,
1044  (errcode(ERRCODE_UNDEFINED_DATABASE),
1045  errmsg("database %u does not exist", dboid)));
1046  dbform = (Form_pg_database) GETSTRUCT(tuple);
1047  MyDatabaseId = dbform->oid;
1048  MyDatabaseTableSpace = dbform->dattablespace;
1049  Assert(MyDatabaseId == dboid);
1050  strlcpy(dbname, NameStr(dbform->datname), sizeof(dbname));
1051  /* pass the database name back to the caller */
1052  if (out_dbname)
1053  strcpy(out_dbname, dbname);
1054  }
1055  else
1056  {
1057  /*
1058  * If this is a background worker not bound to any particular
1059  * database, we're done now. Everything that follows only makes sense
1060  * if we are bound to a specific database. We do need to close the
1061  * transaction we started before returning.
1062  */
1063  if (!bootstrap)
1064  {
1065  pgstat_bestart();
1067  }
1068  return;
1069  }
1070 
1071  /*
1072  * Now, take a writer's lock on the database we are trying to connect to.
1073  * If there is a concurrently running DROP DATABASE on that database, this
1074  * will block us until it finishes (and has committed its update of
1075  * pg_database).
1076  *
1077  * Note that the lock is not held long, only until the end of this startup
1078  * transaction. This is OK since we will advertise our use of the
1079  * database in the ProcArray before dropping the lock (in fact, that's the
1080  * next thing to do). Anyone trying a DROP DATABASE after this point will
1081  * see us in the array once they have the lock. Ordering is important for
1082  * this because we don't want to advertise ourselves as being in this
1083  * database until we have the lock; otherwise we create what amounts to a
1084  * deadlock with CountOtherDBBackends().
1085  *
1086  * Note: use of RowExclusiveLock here is reasonable because we envision
1087  * our session as being a concurrent writer of the database. If we had a
1088  * way of declaring a session as being guaranteed-read-only, we could use
1089  * AccessShareLock for such sessions and thereby not conflict against
1090  * CREATE DATABASE.
1091  */
1092  if (!bootstrap)
1093  LockSharedObject(DatabaseRelationId, MyDatabaseId, 0,
1095 
1096  /*
1097  * Now we can mark our PGPROC entry with the database ID.
1098  *
1099  * We assume this is an atomic store so no lock is needed; though actually
1100  * things would work fine even if it weren't atomic. Anyone searching the
1101  * ProcArray for this database's ID should hold the database lock, so they
1102  * would not be executing concurrently with this store. A process looking
1103  * for another database's ID could in theory see a chance match if it read
1104  * a partially-updated databaseId value; but as long as all such searches
1105  * wait and retry, as in CountOtherDBBackends(), they will certainly see
1106  * the correct value on their next try.
1107  */
1109 
1110  /*
1111  * We established a catalog snapshot while reading pg_authid and/or
1112  * pg_database; but until we have set up MyDatabaseId, we won't react to
1113  * incoming sinval messages for unshared catalogs, so we won't realize it
1114  * if the snapshot has been invalidated. Assume it's no good anymore.
1115  */
1117 
1118  /*
1119  * Recheck pg_database to make sure the target database hasn't gone away.
1120  * If there was a concurrent DROP DATABASE, this ensures we will die
1121  * cleanly without creating a mess.
1122  */
1123  if (!bootstrap)
1124  {
1125  HeapTuple tuple;
1126 
1127  tuple = GetDatabaseTuple(dbname);
1128  if (!HeapTupleIsValid(tuple) ||
1129  MyDatabaseId != ((Form_pg_database) GETSTRUCT(tuple))->oid ||
1130  MyDatabaseTableSpace != ((Form_pg_database) GETSTRUCT(tuple))->dattablespace)
1131  ereport(FATAL,
1132  (errcode(ERRCODE_UNDEFINED_DATABASE),
1133  errmsg("database \"%s\" does not exist", dbname),
1134  errdetail("It seems to have just been dropped or renamed.")));
1135  }
1136 
1137  /*
1138  * Now we should be able to access the database directory safely. Verify
1139  * it's there and looks reasonable.
1140  */
1142 
1143  if (!bootstrap)
1144  {
1145  if (access(fullpath, F_OK) == -1)
1146  {
1147  if (errno == ENOENT)
1148  ereport(FATAL,
1149  (errcode(ERRCODE_UNDEFINED_DATABASE),
1150  errmsg("database \"%s\" does not exist",
1151  dbname),
1152  errdetail("The database subdirectory \"%s\" is missing.",
1153  fullpath)));
1154  else
1155  ereport(FATAL,
1157  errmsg("could not access directory \"%s\": %m",
1158  fullpath)));
1159  }
1160 
1161  ValidatePgVersion(fullpath);
1162  }
1163 
1164  SetDatabasePath(fullpath);
1165  pfree(fullpath);
1166 
1167  /*
1168  * It's now possible to do real access to the system catalogs.
1169  *
1170  * Load relcache entries for the system catalogs. This must create at
1171  * least the minimum set of "nailed-in" cache entries.
1172  */
1174 
1175  /* set up ACL framework (so CheckMyDatabase can check permissions) */
1176  initialize_acl();
1177 
1178  /*
1179  * Re-read the pg_database row for our database, check permissions and set
1180  * up database-specific GUC settings. We can't do this until all the
1181  * database-access infrastructure is up. (Also, it wants to know if the
1182  * user is a superuser, so the above stuff has to happen first.)
1183  */
1184  if (!bootstrap)
1185  CheckMyDatabase(dbname, am_superuser, override_allow_connections);
1186 
1187  /*
1188  * Now process any command-line switches and any additional GUC variable
1189  * settings passed in the startup packet. We couldn't do this before
1190  * because we didn't know if client is a superuser.
1191  */
1192  if (MyProcPort != NULL)
1193  process_startup_options(MyProcPort, am_superuser);
1194 
1195  /* Process pg_db_role_setting options */
1197 
1198  /* Apply PostAuthDelay as soon as we've read all options */
1199  if (PostAuthDelay > 0)
1200  pg_usleep(PostAuthDelay * 1000000L);
1201 
1202  /*
1203  * Initialize various default states that can't be set up until we've
1204  * selected the active user and gotten the right GUC settings.
1205  */
1206 
1207  /* set default namespace search path */
1209 
1210  /* initialize client encoding */
1212 
1213  /* Initialize this backend's session state. */
1215 
1216  /*
1217  * If this is an interactive session, load any libraries that should be
1218  * preloaded at backend start. Since those are determined by GUCs, this
1219  * can't happen until GUC settings are complete, but we want it to happen
1220  * during the initial transaction in case anything that requires database
1221  * access needs to be done.
1222  */
1223  if (load_session_libraries)
1225 
1226  /* report this backend in the PgBackendStatus array */
1227  if (!bootstrap)
1228  pgstat_bestart();
1229 
1230  /* close the transaction we started above */
1231  if (!bootstrap)
1233 }
void initialize_acl(void)
Definition: acl.c:4779
bool has_privs_of_role(Oid member, Oid role)
Definition: acl.c:4969
bool IsAutoVacuumLauncherProcess(void)
Definition: autovacuum.c:3315
void pgstat_beinit(void)
void pgstat_bestart(void)
#define InvalidBackendId
Definition: backendid.h:23
#define DEBUG3
Definition: elog.h:28
#define WARNING
Definition: elog.h:36
bool IsBinaryUpgrade
Definition: globals.c:114
BackendId MyBackendId
Definition: globals.c:85
Oid MyDatabaseTableSpace
Definition: globals.c:91
struct Port * MyProcPort
Definition: globals.c:47
Oid MyDatabaseId
Definition: globals.c:89
const char * hba_authname(UserAuth auth_method)
Definition: hba.c:3162
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:333
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1046
#define RowExclusiveLock
Definition: lockdefs.h:38
void InitializeClientEncoding(void)
Definition: mbutils.c:282
void InitializeSystemUser(const char *authn_id, const char *auth_method)
Definition: miscinit.c:855
void InitializeSessionUserIdStandalone(void)
Definition: miscinit.c:832
void process_session_preload_libraries(void)
Definition: miscinit.c:1861
Oid GetUserId(void)
Definition: miscinit.c:510
Oid GetSessionUserId(void)
Definition: miscinit.c:544
void SetDatabasePath(const char *path)
Definition: miscinit.c:323
void InitializeSessionUserId(const char *rolename, Oid roleid)
Definition: miscinit.c:729
bool has_rolreplication(Oid roleid)
Definition: miscinit.c:707
void InitializeSearchPath(void)
Definition: namespace.c:4369
#define NAMEDATALEN
FormData_pg_database * Form_pg_database
Definition: pg_database.h:90
const char * username
Definition: pgbench.c:306
void pgstat_before_server_shutdown(int code, Datum arg)
Definition: pgstat.c:458
void InitPlanCache(void)
Definition: plancache.c:127
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
void EnablePortalManager(void)
Definition: portalmem.c:105
int PostAuthDelay
Definition: postgres.c:95
static void ShutdownPostgres(int code, Datum arg)
Definition: postinit.c:1339
static void IdleInTransactionSessionTimeoutHandler(void)
Definition: postinit.c:1388
static void LockTimeoutHandler(void)
Definition: postinit.c:1378
static void IdleStatsUpdateTimeoutHandler(void)
Definition: postinit.c:1404
static void process_settings(Oid databaseid, Oid roleid)
Definition: postinit.c:1305
static void IdleSessionTimeoutHandler(void)
Definition: postinit.c:1396
static void process_startup_options(Port *port, bool am_superuser)
Definition: postinit.c:1240
static void StatementTimeoutHandler(void)
Definition: postinit.c:1356
static void CheckMyDatabase(const char *name, bool am_superuser, bool override_allow_connections)
Definition: postinit.c:311
static bool ThereIsAtLeastOneRole(void)
Definition: postinit.c:1423
static void PerformAuthentication(Port *port)
Definition: postinit.c:190
static void ClientCheckTimeoutHandler(void)
Definition: postinit.c:1412
static HeapTuple GetDatabaseTuple(const char *dbname)
Definition: postinit.c:101
static HeapTuple GetDatabaseTupleByOid(Oid dboid)
Definition: postinit.c:144
int ReservedConnections
Definition: postmaster.c:225
int SuperuserReservedConnections
Definition: postmaster.c:224
short access
Definition: preproc-type.c:36
void ProcSignalInit(int pss_idx)
Definition: procsignal.c:162
void RelationCacheInitializePhase3(void)
Definition: relcache.c:4038
void RelationCacheInitialize(void)
Definition: relcache.c:3933
void RelationCacheInitializePhase2(void)
Definition: relcache.c:3979
char * GetDatabasePath(Oid dbOid, Oid spcOid)
Definition: relpath.c:110
void ReleaseAuxProcessResources(bool isCommit)
Definition: resowner.c:912
ResourceOwner CurrentResourceOwner
Definition: resowner.c:146
void CreateAuxProcessResourceOwner(void)
Definition: resowner.c:892
void InitializeSession(void)
Definition: session.c:54
void pg_usleep(long microsec)
Definition: signal.c:53
void SharedInvalBackendInit(bool sendOnly)
Definition: sinvaladt.c:266
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:251
void InvalidateCatalogSnapshot(void)
Definition: snapmgr.c:457
bool HaveNFreeProcs(int n, int *nfree)
Definition: proc.c:655
void CheckDeadLockAlert(void)
Definition: proc.c:1771
void InitProcessPhase2(void)
Definition: proc.c:474
char * dbname
Definition: streamutil.c:51
UserAuth auth_method
Definition: libpq-be.h:119
Oid databaseId
Definition: proc.h:198
bool superuser(void)
Definition: superuser.c:46
void InitCatalogCache(void)
Definition: syscache.c:708
TimeoutId RegisterTimeout(TimeoutId id, timeout_handler_proc handler)
Definition: timeout.c:509
@ IDLE_SESSION_TIMEOUT
Definition: timeout.h:34
@ IDLE_IN_TRANSACTION_SESSION_TIMEOUT
Definition: timeout.h:33
@ LOCK_TIMEOUT
Definition: timeout.h:28
@ STATEMENT_TIMEOUT
Definition: timeout.h:29
@ DEADLOCK_TIMEOUT
Definition: timeout.h:27
@ IDLE_STATS_UPDATE_TIMEOUT
Definition: timeout.h:35
@ CLIENT_CONNECTION_CHECK_TIMEOUT
Definition: timeout.h:36
bool am_walsender
Definition: walsender.c:116
bool am_db_walsender
Definition: walsender.c:119
void StartTransactionCommand(void)
Definition: xact.c:2944
int XactIsoLevel
Definition: xact.c:79
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:899
void CommitTransactionCommand(void)
Definition: xact.c:3041
#define XACT_READ_COMMITTED
Definition: xact.h:37
void StartupXLOG(void)
Definition: xlog.c:5020
void ShutdownXLOG(int code, Datum arg)
Definition: xlog.c:6159

References am_db_walsender, am_walsender, Assert(), ClientConnectionInfo::auth_method, ClientConnectionInfo::authn_id, before_shmem_exit(), CheckDeadLockAlert(), CheckMyDatabase(), CLIENT_CONNECTION_CHECK_TIMEOUT, ClientCheckTimeoutHandler(), CommitTransactionCommand(), CreateAuxProcessResourceOwner(), CurrentResourceOwner, PGPROC::databaseId, dbname, DEADLOCK_TIMEOUT, DEBUG3, elog(), EnablePortalManager(), ereport, errcode(), errcode_for_file_access(), errdetail(), errhint(), errmsg(), FATAL, GetDatabasePath(), GetDatabaseTuple(), GetDatabaseTupleByOid(), GetSessionUserId(), GETSTRUCT, GetTransactionSnapshot(), GetUserId(), has_privs_of_role(), has_rolreplication(), HaveNFreeProcs(), hba_authname(), HeapTupleIsValid, IDLE_IN_TRANSACTION_SESSION_TIMEOUT, IDLE_SESSION_TIMEOUT, IDLE_STATS_UPDATE_TIMEOUT, IdleInTransactionSessionTimeoutHandler(), IdleSessionTimeoutHandler(), IdleStatsUpdateTimeoutHandler(), InitCatalogCache(), initialize_acl(), InitializeClientEncoding(), InitializeSearchPath(), InitializeSession(), InitializeSessionUserId(), InitializeSessionUserIdStandalone(), InitializeSystemUser(), InitPlanCache(), InitProcessPhase2(), InvalidateCatalogSnapshot(), InvalidBackendId, IsAutoVacuumLauncherProcess(), IsAutoVacuumWorkerProcess(), IsBackgroundWorker, IsBinaryUpgrade, IsBootstrapProcessingMode, IsUnderPostmaster, LOCK_TIMEOUT, LockSharedObject(), LockTimeoutHandler(), MaxBackends, MyBackendId, MyClientConnectionInfo, MyDatabaseId, MyDatabaseTableSpace, MyProc, MyProcPort, NAMEDATALEN, NameStr, OidIsValid, PerformAuthentication(), pfree(), pg_usleep(), pgstat_before_server_shutdown(), pgstat_beinit(), pgstat_bestart(), PostAuthDelay, process_session_preload_libraries(), process_settings(), process_startup_options(), ProcSignalInit(), RegisterTimeout(), RelationCacheInitialize(), RelationCacheInitializePhase2(), RelationCacheInitializePhase3(), ReleaseAuxProcessResources(), ReservedConnections, RowExclusiveLock, SetCurrentStatementStartTimestamp(), SetDatabasePath(), SharedInvalBackendInit(), ShutdownPostgres(), ShutdownXLOG(), StartTransactionCommand(), StartupXLOG(), STATEMENT_TIMEOUT, StatementTimeoutHandler(), strlcpy(), superuser(), SuperuserReservedConnections, ThereIsAtLeastOneRole(), username, ValidatePgVersion(), WARNING, XACT_READ_COMMITTED, and XactIsoLevel.

Referenced by AutoVacLauncherMain(), AutoVacWorkerMain(), BackgroundWorkerInitializeConnection(), BackgroundWorkerInitializeConnectionByOid(), BootstrapModeMain(), and PostgresMain().

◆ InitPostmasterChild()

void InitPostmasterChild ( void  )

Definition at line 95 of file miscinit.c.

96 {
97  IsUnderPostmaster = true; /* we are a postmaster subprocess now */
98 
99  /*
100  * Start our win32 signal implementation. This has to be done after we
101  * read the backend variables, because we need to pick up the signal pipe
102  * from the parent process.
103  */
104 #ifdef WIN32
106 #endif
107 
108  /*
109  * Set reference point for stack-depth checking. This might seem
110  * redundant in !EXEC_BACKEND builds; but it's not because the postmaster
111  * launches its children from signal handlers, so we might be running on
112  * an alternative stack.
113  */
114  (void) set_stack_base();
115 
117 
118  /*
119  * make sure stderr is in binary mode before anything can possibly be
120  * written to it, in case it's actually the syslogger pipe, so the pipe
121  * chunking protocol isn't disturbed. Non-logpipe data gets translated on
122  * redirection (e.g. via pg_ctl -l) anyway.
123  */
124 #ifdef WIN32
125  _setmode(fileno(stderr), _O_BINARY);
126 #endif
127 
128  /* We don't want the postmaster's proc_exit() handlers */
129  on_exit_reset();
130 
131  /* In EXEC_BACKEND case we will not have inherited BlockSig etc values */
132 #ifdef EXEC_BACKEND
133  pqinitmask();
134 #endif
135 
136  /* Initialize process-local latch support */
140 
141  /*
142  * If possible, make this process a group leader, so that the postmaster
143  * can signal any child processes too. Not all processes will have
144  * children, but for consistency we make all postmaster child processes do
145  * this.
146  */
147 #ifdef HAVE_SETSID
148  if (setsid() < 0)
149  elog(FATAL, "setsid() failed: %m");
150 #endif
151 
152  /*
153  * Every postmaster child process is expected to respond promptly to
154  * SIGQUIT at all times. Therefore we centrally remove SIGQUIT from
155  * BlockSig and install a suitable signal handler. (Client-facing
156  * processes may choose to replace this default choice of handler with
157  * quickdie().) All other blockable signals remain blocked for now.
158  */
160 
161  sigdelset(&BlockSig, SIGQUIT);
162  sigprocmask(SIG_SETMASK, &BlockSig, NULL);
163 
164  /* Request a signal if the postmaster dies, if possible. */
166 
167  /* Don't give the pipe to subprograms that we execute. */
168 #ifndef WIN32
169  if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFD, FD_CLOEXEC) < 0)
170  ereport(FATAL,
172  errmsg_internal("could not set postmaster death monitoring pipe to FD_CLOEXEC mode: %m")));
173 #endif
174 }
void pqinitmask(void)
Definition: pqsignal.c:41
sigset_t BlockSig
Definition: pqsignal.c:23
int errcode_for_socket_access(void)
Definition: elog.c:952
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1156
void SignalHandlerForCrashExit(SIGNAL_ARGS)
Definition: interrupt.c:77
void on_exit_reset(void)
Definition: ipc.c:412
void InitializeLatchWaitSet(void)
Definition: latch.c:321
void InitializeLatchSupport(void)
Definition: latch.c:207
void InitProcessLocalLatch(void)
Definition: miscinit.c:242
void PostmasterDeathSignalInit(void)
Definition: pmsignal.c:437
pqsigfunc pqsignal(int signo, pqsigfunc func)
pg_stack_base_t set_stack_base(void)
Definition: postgres.c:3411
void InitProcessGlobals(void)
Definition: postmaster.c:2645
int postmaster_alive_fds[2]
Definition: postmaster.c:576
#define POSTMASTER_FD_WATCH
Definition: postmaster.h:46
void pgwin32_signal_initialize(void)
Definition: signal.c:79
#define SIGQUIT
Definition: win32_port.h:177

References BlockSig, elog(), ereport, errcode_for_socket_access(), errmsg_internal(), FATAL, InitializeLatchSupport(), InitializeLatchWaitSet(), InitProcessGlobals(), InitProcessLocalLatch(), IsUnderPostmaster, on_exit_reset(), pgwin32_signal_initialize(), postmaster_alive_fds, POSTMASTER_FD_WATCH, PostmasterDeathSignalInit(), pqinitmask(), pqsignal(), set_stack_base(), SignalHandlerForCrashExit(), and SIGQUIT.

Referenced by BackendStartup(), do_start_bgworker(), StartAutoVacWorker(), StartChildProcess(), and SysLogger_Start().

◆ InitProcessLocalLatch()

void InitProcessLocalLatch ( void  )

Definition at line 242 of file miscinit.c.

243 {
246 }
struct Latch * MyLatch
Definition: globals.c:58
void InitLatch(Latch *latch)
Definition: latch.c:369
static Latch LocalLatchData
Definition: miscinit.c:68

References InitLatch(), LocalLatchData, and MyLatch.

Referenced by InitPostmasterChild(), InitStandaloneProcess(), and PostmasterMain().

◆ InitStandaloneProcess()

void InitStandaloneProcess ( const char *  argv0)

Definition at line 182 of file miscinit.c.

183 {
185 
187 
188  /*
189  * Start our win32 signal implementation
190  */
191 #ifdef WIN32
193 #endif
194 
196 
197  /* Initialize process-local latch support */
201 
202  /*
203  * For consistency with InitPostmasterChild, initialize signal mask here.
204  * But we don't unblock SIGQUIT or provide a default handler for it.
205  */
206  pqinitmask();
207  sigprocmask(SIG_SETMASK, &BlockSig, NULL);
208 
209  /* Compute paths, no postmaster to inherit from */
210  if (my_exec_path[0] == '\0')
211  {
212  if (find_my_exec(argv0, my_exec_path) < 0)
213  elog(FATAL, "%s: could not locate my own executable path",
214  argv0);
215  }
216 
217  if (pkglib_path[0] == '\0')
219 }
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:152
char pkglib_path[MAXPGPATH]
Definition: globals.c:77
bool IsPostmasterEnvironment
Definition: globals.c:112
char my_exec_path[MAXPGPATH]
Definition: globals.c:76
BackendType MyBackendType
Definition: miscinit.c:63
static char * argv0
Definition: pg_ctl.c:92
void get_pkglib_path(const char *my_exec_path, char *ret_path)
Definition: path.c:879

References argv0, Assert(), B_STANDALONE_BACKEND, BlockSig, elog(), FATAL, find_my_exec(), get_pkglib_path(), InitializeLatchSupport(), InitializeLatchWaitSet(), InitProcessGlobals(), InitProcessLocalLatch(), IsPostmasterEnvironment, my_exec_path, MyBackendType, pgwin32_signal_initialize(), pkglib_path, and pqinitmask().

Referenced by BootstrapModeMain(), and PostgresSingleUserMain().

◆ InLocalUserIdChange()

bool InLocalUserIdChange ( void  )

Definition at line 649 of file miscinit.c.

650 {
652 }
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:304

References SECURITY_LOCAL_USERID_CHANGE, and SecurityRestrictionContext.

Referenced by GetUserIdAndContext(), and set_config_option_ext().

◆ InNoForceRLSOperation()

bool InNoForceRLSOperation ( void  )

Definition at line 667 of file miscinit.c.

668 {
670 }
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:306

References SECURITY_NOFORCE_RLS, and SecurityRestrictionContext.

Referenced by check_enable_rls().

◆ InSecurityRestrictedOperation()

bool InSecurityRestrictedOperation ( void  )

◆ pg_bindtextdomain()

void pg_bindtextdomain ( const char *  domain)

Definition at line 1884 of file miscinit.c.

1885 {
1886 #ifdef ENABLE_NLS
1887  if (my_exec_path[0] != '\0')
1888  {
1889  char locale_path[MAXPGPATH];
1890 
1891  get_locale_path(my_exec_path, locale_path);
1892  bindtextdomain(domain, locale_path);
1893  pg_bind_textdomain_codeset(domain);
1894  }
1895 #endif
1896 }
void get_locale_path(const char *my_exec_path, char *ret_path)
Definition: path.c:888

References get_locale_path(), MAXPGPATH, and my_exec_path.

Referenced by _PG_init().

◆ pg_split_opts()

void pg_split_opts ( char **  argv,
int *  argcp,
const char *  optstr 
)

Definition at line 508 of file postinit.c.

509 {
510  StringInfoData s;
511 
512  initStringInfo(&s);
513 
514  while (*optstr)
515  {
516  bool last_was_escape = false;
517 
518  resetStringInfo(&s);
519 
520  /* skip over leading space */
521  while (isspace((unsigned char) *optstr))
522  optstr++;
523 
524  if (*optstr == '\0')
525  break;
526 
527  /*
528  * Parse a single option, stopping at the first space, unless it's
529  * escaped.
530  */
531  while (*optstr)
532  {
533  if (isspace((unsigned char) *optstr) && !last_was_escape)
534  break;
535 
536  if (!last_was_escape && *optstr == '\\')
537  last_was_escape = true;
538  else
539  {
540  last_was_escape = false;
541  appendStringInfoChar(&s, *optstr);
542  }
543 
544  optstr++;
545  }
546 
547  /* now store the option in the next argv[] position */
548  argv[(*argcp)++] = pstrdup(s.data);
549  }
550 
551  pfree(s.data);
552 }
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:75
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59

References appendStringInfoChar(), StringInfoData::data, initStringInfo(), pfree(), pstrdup(), and resetStringInfo().

Referenced by process_startup_options().

◆ PreventCommandDuringRecovery()

void PreventCommandDuringRecovery ( const char *  cmdname)

Definition at line 448 of file utility.c.

449 {
450  if (RecoveryInProgress())
451  ereport(ERROR,
452  (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
453  /* translator: %s is name of a SQL command, eg CREATE */
454  errmsg("cannot execute %s during recovery",
455  cmdname)));
456 }
bool RecoveryInProgress(void)
Definition: xlog.c:5908

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

Referenced by pg_current_xact_id(), pg_notify(), and standard_ProcessUtility().

◆ PreventCommandIfParallelMode()

void PreventCommandIfParallelMode ( const char *  cmdname)

Definition at line 429 of file utility.c.

430 {
431  if (IsInParallelMode())
432  ereport(ERROR,
433  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
434  /* translator: %s is name of a SQL command, eg CREATE */
435  errmsg("cannot execute %s during a parallel operation",
436  cmdname)));
437 }
bool IsInParallelMode(void)
Definition: xact.c:1069

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

Referenced by do_setval(), ExecCheckXactReadOnly(), nextval_internal(), and standard_ProcessUtility().

◆ PreventCommandIfReadOnly()

void PreventCommandIfReadOnly ( const char *  cmdname)

Definition at line 411 of file utility.c.

412 {
413  if (XactReadOnly)
414  ereport(ERROR,
415  (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
416  /* translator: %s is name of a SQL command, eg CREATE */
417  errmsg("cannot execute %s in a read-only transaction",
418  cmdname)));
419 }
bool XactReadOnly
Definition: xact.c:82

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

Referenced by be_lo_creat(), be_lo_create(), be_lo_from_bytea(), be_lo_open(), be_lo_put(), be_lo_truncate(), be_lo_truncate64(), be_lo_unlink(), be_lowrite(), do_setval(), DoCopy(), ExecCheckXactReadOnly(), lo_import_internal(), nextval_internal(), and standard_ProcessUtility().

◆ process_session_preload_libraries()

void process_session_preload_libraries ( void  )

Definition at line 1861 of file miscinit.c.

1862 {
1864  "session_preload_libraries",
1865  false);
1867  "local_preload_libraries",
1868  true);
1869 }
char * session_preload_libraries_string
Definition: miscinit.c:1777
char * local_preload_libraries_string
Definition: miscinit.c:1779
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1795

References load_libraries(), local_preload_libraries_string, and session_preload_libraries_string.

Referenced by InitPostgres().

◆ process_shared_preload_libraries()

void process_shared_preload_libraries ( void  )

Definition at line 1847 of file miscinit.c.

1848 {
1851  "shared_preload_libraries",
1852  false);
1855 }
bool process_shared_preload_libraries_done
Definition: miscinit.c:1783
char * shared_preload_libraries_string
Definition: miscinit.c:1778
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1782

References load_libraries(), process_shared_preload_libraries_done, process_shared_preload_libraries_in_progress, and shared_preload_libraries_string.

Referenced by PostgresSingleUserMain(), and PostmasterMain().

◆ process_shmem_requests()

void process_shmem_requests ( void  )

Definition at line 1875 of file miscinit.c.

1876 {
1878  if (shmem_request_hook)
1881 }
bool process_shmem_requests_in_progress
Definition: miscinit.c:1786
shmem_request_hook_type shmem_request_hook
Definition: miscinit.c:1785

References process_shmem_requests_in_progress, and shmem_request_hook.

Referenced by PostgresSingleUserMain(), and PostmasterMain().

◆ ProcessInterrupts()

void ProcessInterrupts ( void  )

Definition at line 3149 of file postgres.c.

3150 {
3151  /* OK to accept any interrupts now? */
3152  if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
3153  return;
3154  InterruptPending = false;
3155 
3156  if (ProcDiePending)
3157  {
3158  ProcDiePending = false;
3159  QueryCancelPending = false; /* ProcDie trumps QueryCancel */
3160  LockErrorCleanup();
3161  /* As in quickdie, don't risk sending to client during auth */
3165  ereport(FATAL,
3166  (errcode(ERRCODE_QUERY_CANCELED),
3167  errmsg("canceling authentication due to timeout")));
3168  else if (IsAutoVacuumWorkerProcess())
3169  ereport(FATAL,
3170  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3171  errmsg("terminating autovacuum process due to administrator command")));
3172  else if (IsLogicalWorker())
3173  ereport(FATAL,
3174  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3175  errmsg("terminating logical replication worker due to administrator command")));
3176  else if (IsLogicalLauncher())
3177  {
3178  ereport(DEBUG1,
3179  (errmsg_internal("logical replication launcher shutting down")));
3180 
3181  /*
3182  * The logical replication launcher can be stopped at any time.
3183  * Use exit status 1 so the background worker is restarted.
3184  */
3185  proc_exit(1);
3186  }
3188  {
3190  ereport(FATAL,
3192  errmsg("terminating connection due to conflict with recovery"),
3194  }
3195  else if (RecoveryConflictPending)
3196  {
3197  /* Currently there is only one non-retryable recovery conflict */
3200  ereport(FATAL,
3201  (errcode(ERRCODE_DATABASE_DROPPED),
3202  errmsg("terminating connection due to conflict with recovery"),
3204  }
3205  else if (IsBackgroundWorker)
3206  ereport(FATAL,
3207  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3208  errmsg("terminating background worker \"%s\" due to administrator command",
3210  else
3211  ereport(FATAL,
3212  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3213  errmsg("terminating connection due to administrator command")));
3214  }
3215 
3217  {
3219 
3220  /*
3221  * Check for lost connection and re-arm, if still configured, but not
3222  * if we've arrived back at DoingCommandRead state. We don't want to
3223  * wake up idle sessions, and they already know how to detect lost
3224  * connections.
3225  */
3227  {
3228  if (!pq_check_connection())
3229  ClientConnectionLost = true;
3230  else
3233  }
3234  }
3235 
3237  {
3238  QueryCancelPending = false; /* lost connection trumps QueryCancel */
3239  LockErrorCleanup();
3240  /* don't send to client, we already know the connection to be dead. */
3242  ereport(FATAL,
3243  (errcode(ERRCODE_CONNECTION_FAILURE),
3244  errmsg("connection to client lost")));
3245  }
3246 
3247  /*
3248  * If a recovery conflict happens while we are waiting for input from the
3249  * client, the client is presumably just sitting idle in a transaction,
3250  * preventing recovery from making progress. Terminate the connection to
3251  * dislodge it.
3252  */
3254  {
3255  QueryCancelPending = false; /* this trumps QueryCancel */
3256  RecoveryConflictPending = false;
3257  LockErrorCleanup();
3259  ereport(FATAL,
3261  errmsg("terminating connection due to conflict with recovery"),
3263  errhint("In a moment you should be able to reconnect to the"
3264  " database and repeat your command.")));
3265  }
3266 
3267  /*
3268  * Don't allow query cancel interrupts while reading input from the
3269  * client, because we might lose sync in the FE/BE protocol. (Die
3270  * interrupts are OK, because we won't read any further messages from the
3271  * client in that case.)
3272  */
3274  {
3275  /*
3276  * Re-arm InterruptPending so that we process the cancel request as
3277  * soon as we're done reading the message. (XXX this is seriously
3278  * ugly: it complicates INTERRUPTS_CAN_BE_PROCESSED(), and it means we
3279  * can't use that macro directly as the initial test in this function,
3280  * meaning that this code also creates opportunities for other bugs to
3281  * appear.)
3282  */
3283  InterruptPending = true;
3284  }
3285  else if (QueryCancelPending)
3286  {
3287  bool lock_timeout_occurred;
3288  bool stmt_timeout_occurred;
3289 
3290  QueryCancelPending = false;
3291 
3292  /*
3293  * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
3294  * need to clear both, so always fetch both.
3295  */
3296  lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
3297  stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
3298 
3299  /*
3300  * If both were set, we want to report whichever timeout completed
3301  * earlier; this ensures consistent behavior if the machine is slow
3302  * enough that the second timeout triggers before we get here. A tie
3303  * is arbitrarily broken in favor of reporting a lock timeout.
3304  */
3305  if (lock_timeout_occurred && stmt_timeout_occurred &&
3307  lock_timeout_occurred = false; /* report stmt timeout */
3308 
3309  if (lock_timeout_occurred)
3310  {
3311  LockErrorCleanup();
3312  ereport(ERROR,
3313  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
3314  errmsg("canceling statement due to lock timeout")));
3315  }
3316  if (stmt_timeout_occurred)
3317  {
3318  LockErrorCleanup();
3319  ereport(ERROR,
3320  (errcode(ERRCODE_QUERY_CANCELED),
3321  errmsg("canceling statement due to statement timeout")));
3322  }
3324  {
3325  LockErrorCleanup();
3326  ereport(ERROR,
3327  (errcode(ERRCODE_QUERY_CANCELED),
3328  errmsg("canceling autovacuum task")));
3329  }
3331  {
3332  RecoveryConflictPending = false;
3333  LockErrorCleanup();
3335  ereport(ERROR,
3337  errmsg("canceling statement due to conflict with recovery"),
3339  }
3340 
3341  /*
3342  * If we are reading a command from the client, just ignore the cancel
3343  * request --- sending an extra error message won't accomplish
3344  * anything. Otherwise, go ahead and throw the error.
3345  */
3346  if (!DoingCommandRead)
3347  {
3348  LockErrorCleanup();
3349  ereport(ERROR,
3350  (errcode(ERRCODE_QUERY_CANCELED),
3351  errmsg("canceling statement due to user request")));
3352  }
3353  }
3354 
3356  {
3357  /*
3358  * If the GUC has been reset to zero, ignore the signal. This is
3359  * important because the GUC update itself won't disable any pending
3360  * interrupt.
3361  */
3363  ereport(FATAL,
3364  (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
3365  errmsg("terminating connection due to idle-in-transaction timeout")));
3366  else
3368  }
3369 
3371  {
3372  /* As above, ignore the signal if the GUC has been reset to zero. */
3373  if (IdleSessionTimeout > 0)
3374  ereport(FATAL,
3375  (errcode(ERRCODE_IDLE_SESSION_TIMEOUT),
3376  errmsg("terminating connection due to idle-session timeout")));
3377  else
3378  IdleSessionTimeoutPending = false;
3379  }
3380 
3381  /*
3382  * If there are pending stats updates and we currently are truly idle
3383  * (matching the conditions in PostgresMain(), report stats now.
3384  */
3387  {
3389  pgstat_report_stat(true);
3390  }
3391 
3394 
3397 
3400 
3403 }
volatile sig_atomic_t ParallelApplyMessagePending
void HandleParallelApplyMessages(void)
void HandleParallelMessages(void)
Definition: parallel.c:1025
volatile sig_atomic_t ParallelMessagePending
Definition: parallel.c:116
bool IsLogicalWorker(void)
Definition: worker.c:4705
@ DestRemote
Definition: dest.h:89
@ DestNone
Definition: dest.h:87
#define DEBUG1
Definition: elog.h:30
volatile sig_atomic_t IdleStatsUpdateTimeoutPending
Definition: globals.c:39
volatile sig_atomic_t LogMemoryContextPending
Definition: globals.c:38
volatile sig_atomic_t ProcSignalBarrierPending
Definition: globals.c:37
volatile sig_atomic_t InterruptPending
Definition: globals.c:30
volatile sig_atomic_t IdleSessionTimeoutPending
Definition: globals.c:36
volatile uint32 QueryCancelHoldoffCount
Definition: globals.c:41
volatile sig_atomic_t IdleInTransactionSessionTimeoutPending
Definition: globals.c:35
volatile uint32 InterruptHoldoffCount
Definition: globals.c:40
volatile sig_atomic_t ClientConnectionLost
Definition: globals.c:34
volatile uint32 CritSectionCount
Definition: globals.c:42
volatile sig_atomic_t QueryCancelPending
Definition: globals.c:31
volatile sig_atomic_t ProcDiePending
Definition: globals.c:32
volatile sig_atomic_t CheckClientConnectionPending
Definition: globals.c:33
void proc_exit(int code)
Definition: ipc.c:104
bool IsLogicalLauncher(void)
Definition: launcher.c:1198
void ProcessLogMemoryContextInterrupt(void)
Definition: mcxt.c:1183
#define ERRCODE_T_R_SERIALIZATION_FAILURE
Definition: pgbench.c:76
long pgstat_report_stat(bool force)
Definition: pgstat.c:575
void pgstat_report_recovery_conflict(int reason)
int client_connection_check_interval
Definition: postgres.c:98
static int errdetail_recovery_conflict(void)
Definition: postgres.c:2475
CommandDest whereToSendOutput
Definition: postgres.c:84
static bool RecoveryConflictRetryable
Definition: postgres.c:161
static bool DoingCommandRead
Definition: postgres.c:138
static ProcSignalReason RecoveryConflictReason
Definition: postgres.c:162
static bool RecoveryConflictPending
Definition: postgres.c:160
bool ClientAuthInProgress
Definition: postmaster.c:356
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:193
bool pq_check_connection(void)
Definition: pqcomm.c:2029
void ProcessProcSignalBarrier(void)
Definition: procsignal.c:468
@ PROCSIG_RECOVERY_CONFLICT_DATABASE
Definition: procsignal.h:41
int IdleSessionTimeout
Definition: proc.c:62
int IdleInTransactionSessionTimeout
Definition: proc.c:61
void LockErrorCleanup(void)
Definition: proc.c:698
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:92
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:564
TimestampTz get_timeout_finish_time(TimeoutId id)
Definition: timeout.c:831
bool get_timeout_indicator(TimeoutId id, bool reset_indicator)
Definition: timeout.c:797
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4841

References Assert(), BackgroundWorker::bgw_type, CheckClientConnectionPending, client_connection_check_interval, CLIENT_CONNECTION_CHECK_TIMEOUT, ClientAuthInProgress, ClientConnectionLost, CritSectionCount, DEBUG1, DestNone, DestRemote, DoingCommandRead, enable_timeout_after(), ereport, errcode(), ERRCODE_T_R_SERIALIZATION_FAILURE, errdetail_recovery_conflict(), errhint(), errmsg(), errmsg_internal(), ERROR, FATAL, get_timeout_finish_time(), get_timeout_indicator(), HandleParallelApplyMessages(), HandleParallelMessages(), IdleInTransactionSessionTimeout, IdleInTransactionSessionTimeoutPending, IdleSessionTimeout, IdleSessionTimeoutPending, IdleStatsUpdateTimeoutPending, InterruptHoldoffCount, InterruptPending, IsAutoVacuumWorkerProcess(), IsBackgroundWorker, IsLogicalLauncher(), IsLogicalWorker(), IsTransactionOrTransactionBlock(), LOCK_TIMEOUT, LockErrorCleanup(), LogMemoryContextPending, MyBgworkerEntry, ParallelApplyMessagePending, ParallelMessagePending, pgstat_report_recovery_conflict(), pgstat_report_stat(), pq_check_connection(), proc_exit(), ProcDiePending, ProcessLogMemoryContextInterrupt(), ProcessProcSignalBarrier(), PROCSIG_RECOVERY_CONFLICT_DATABASE, ProcSignalBarrierPending, QueryCancelHoldoffCount, QueryCancelPending, RecoveryConflictPending, RecoveryConflictReason, RecoveryConflictRetryable, STATEMENT_TIMEOUT, and whereToSendOutput.

Referenced by die().

◆ RecheckDataDirLockFile()

bool RecheckDataDirLockFile ( void  )

Definition at line 1642 of file miscinit.c.

1643 {
1644  int fd;
1645  int len;
1646  long file_pid;
1647  char buffer[BLCKSZ];
1648 
1649  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1650  if (fd < 0)
1651  {
1652  /*
1653  * There are many foreseeable false-positive error conditions. For
1654  * safety, fail only on enumerated clearly-something-is-wrong
1655  * conditions.
1656  */
1657  switch (errno)
1658  {
1659  case ENOENT:
1660  case ENOTDIR:
1661  /* disaster */
1662  ereport(LOG,
1664  errmsg("could not open file \"%s\": %m",
1666  return false;
1667  default:
1668  /* non-fatal, at least for now */
1669  ereport(LOG,
1671  errmsg("could not open file \"%s\": %m; continuing anyway",
1673  return true;
1674  }
1675  }
1677  len = read(fd, buffer, sizeof(buffer) - 1);
1679  if (len < 0)
1680  {
1681  ereport(LOG,
1683  errmsg("could not read from file \"%s\": %m",
1685  close(fd);
1686  return true; /* treat read failure as nonfatal */
1687  }
1688  buffer[len] = '\0';
1689  close(fd);
1690  file_pid = atol(buffer);
1691  if (file_pid == getpid())
1692  return true; /* all is well */
1693 
1694  /* Trouble: someone's overwritten the lock file */
1695  ereport(LOG,
1696  (errmsg("lock file \"%s\" contains wrong PID: %ld instead of %ld",
1697  DIRECTORY_LOCK_FILE, file_pid, (long) getpid())));
1698  return false;
1699 }
@ WAIT_EVENT_LOCK_FILE_RECHECKDATADIR_READ
Definition: wait_event.h:193

References close, DIRECTORY_LOCK_FILE, ereport, errcode_for_file_access(), errmsg(), fd(), len, LOG, PG_BINARY, pgstat_report_wait_end(), pgstat_report_wait_start(), read, and WAIT_EVENT_LOCK_FILE_RECHECKDATADIR_READ.

Referenced by ServerLoop().

◆ restore_stack_base()

void restore_stack_base ( pg_stack_base_t  base)

Definition at line 3444 of file postgres.c.

3445 {
3446  stack_base_ptr = base;
3447 }
static char * stack_base_ptr
Definition: postgres.c:125

References stack_base_ptr.

◆ RestoreClientConnectionInfo()

void RestoreClientConnectionInfo ( char *  conninfo)

Definition at line 1079 of file miscinit.c.

1080 {
1081  SerializedClientConnectionInfo serialized;
1082 
1083  memcpy(&serialized, conninfo, sizeof(serialized));
1084 
1085  /* Copy the fields back into place */
1088 
1089  if (serialized.authn_id_len >= 0)
1090  {
1091  char *authn_id;
1092 
1093  authn_id = conninfo + sizeof(serialized);
1095  authn_id);
1096  }
1097 }

References SerializedClientConnectionInfo::auth_method, ClientConnectionInfo::auth_method, ClientConnectionInfo::authn_id, SerializedClientConnectionInfo::authn_id_len, MemoryContextStrdup(), MyClientConnectionInfo, and TopMemoryContext.

Referenced by ParallelWorkerMain().

◆ SerializeClientConnectionInfo()

void SerializeClientConnectionInfo ( Size  maxsize,
char *  start_address 
)

Definition at line 1047 of file miscinit.c.

1048 {
1049  SerializedClientConnectionInfo serialized = {0};
1050 
1051  serialized.authn_id_len = -1;
1053 
1055  serialized.authn_id_len = strlen(MyClientConnectionInfo.authn_id);
1056 
1057  /* Copy serialized representation to buffer */
1058  Assert(maxsize >= sizeof(serialized));
1059  memcpy(start_address, &serialized, sizeof(serialized));
1060 
1061  maxsize -= sizeof(serialized);
1062  start_address += sizeof(serialized);
1063 
1064  /* Copy authn_id into the space after the struct */
1065  if (serialized.authn_id_len >= 0)
1066  {
1067  Assert(maxsize >= (serialized.authn_id_len + 1));
1068  memcpy(start_address,
1070  /* include the NULL terminator to ease deserialization */
1071  serialized.authn_id_len + 1);
1072  }
1073 }

References Assert(), SerializedClientConnectionInfo::auth_method, ClientConnectionInfo::auth_method, ClientConnectionInfo::authn_id, SerializedClientConnectionInfo::authn_id_len, and MyClientConnectionInfo.

Referenced by InitializeParallelDSM().

◆ set_stack_base()

pg_stack_base_t set_stack_base ( void  )

Definition at line 3411 of file postgres.c.

3412 {
3413 #ifndef HAVE__BUILTIN_FRAME_ADDRESS
3414  char stack_base;
3415 #endif
3416  pg_stack_base_t old;
3417 
3418  old = stack_base_ptr;
3419 
3420  /*
3421  * Set up reference point for stack depth checking. On recent gcc we use
3422  * __builtin_frame_address() to avoid a warning about storing a local
3423  * variable's address in a long-lived variable.
3424  */
3425 #ifdef HAVE__BUILTIN_FRAME_ADDRESS
3426  stack_base_ptr = __builtin_frame_address(0);
3427 #else
3428  stack_base_ptr = &stack_base;
3429 #endif
3430 
3431  return old;
3432 }
char * pg_stack_base_t
Definition: miscadmin.h:282

References stack_base_ptr.

Referenced by InitPostmasterChild(), and PostmasterMain().

◆ SetCurrentRoleId()

void SetCurrentRoleId ( Oid  roleid,
bool  is_superuser 
)

Definition at line 949 of file miscinit.c.

950 {
951  /*
952  * Get correct info if it's SET ROLE NONE
953  *
954  * If SessionUserId hasn't been set yet, just do nothing --- the eventual
955  * SetSessionUserId call will fix everything. This is needed since we
956  * will get called during GUC initialization.
957  */
958  if (!OidIsValid(roleid))
959  {
961  return;
962 
963  roleid = SessionUserId;
965 
966  SetRoleIsActive = false;
967  }
968  else
969  SetRoleIsActive = true;
970 
971  SetOuterUserId(roleid);
972 
973  SetConfigOption("is_superuser",
974  is_superuser ? "on" : "off",
976 }
static void SetOuterUserId(Oid userid)
Definition: miscinit.c:529
static bool SessionUserIsSuperuser
Definition: miscinit.c:497
static bool is_superuser(Archive *fout)
Definition: pg_dump.c:4574

References is_superuser(), OidIsValid, PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT, SessionUserId, SessionUserIsSuperuser, SetConfigOption(), SetOuterUserId(), and SetRoleIsActive.

Referenced by assign_role(), and ParallelWorkerMain().

◆ SetDatabasePath()

void SetDatabasePath ( const char *  path)

Definition at line 323 of file miscinit.c.

324 {
325  /* This should happen only once per process */
328 }
char * DatabasePath
Definition: globals.c:97

References Assert(), DatabasePath, MemoryContextStrdup(), and TopMemoryContext.

Referenced by InitPostgres().

◆ SetDataDir()

void SetDataDir ( const char *  dir)

Definition at line 429 of file miscinit.c.

430 {
431  char *new;
432 
433  Assert(dir);
434 
435  /* If presented path is relative, convert to absolute */
436  new = make_absolute_path(dir);
437 
438  free(DataDir);
439  DataDir = new;
440 }
#define free(a)
Definition: header.h:65
char * make_absolute_path(const char *path)
Definition: path.c:729

References Assert(), DataDir, free, and make_absolute_path().

Referenced by SelectConfigFiles().

◆ SetSessionAuthorization()

void SetSessionAuthorization ( Oid  userid,
bool  is_superuser 
)

Definition at line 903 of file miscinit.c.

904 {
905  /* Must have authenticated already, else can't make permission check */
907 
908  if (userid != AuthenticatedUserId &&
910  ereport(ERROR,
911  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
912  errmsg("permission denied to set session authorization")));
913 
915 
916  SetConfigOption("is_superuser",
917  is_superuser ? "on" : "off",
919 }

References Assert(), AuthenticatedUserId, AuthenticatedUserIsSuperuser, ereport, errcode(), errmsg(), ERROR, is_superuser(), OidIsValid, PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT, SetConfigOption(), and SetSessionUserId().

Referenced by assign_session_authorization().

◆ SetUserIdAndContext()

void SetUserIdAndContext ( Oid  userid,
bool  sec_def_context 
)

Definition at line 687 of file miscinit.c.

688 {
689  /* We throw the same error SET ROLE would. */
691  ereport(ERROR,
692  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
693  errmsg("cannot set parameter \"%s\" within security-restricted operation",
694  "role")));
695  CurrentUserId = userid;
696  if (sec_def_context)
698  else
700 }
bool InSecurityRestrictedOperation(void)
Definition: miscinit.c:658

References CurrentUserId, ereport, errcode(), errmsg(), ERROR, InSecurityRestrictedOperation(), SECURITY_LOCAL_USERID_CHANGE, and SecurityRestrictionContext.

◆ SetUserIdAndSecContext()

◆ stack_is_too_deep()

bool stack_is_too_deep ( void  )

Definition at line 3475 of file postgres.c.

3476 {
3477  char stack_top_loc;
3478  long stack_depth;
3479 
3480  /*
3481  * Compute distance from reference point to my local variables
3482  */
3483  stack_depth = (long) (stack_base_ptr - &stack_top_loc);
3484 
3485  /*
3486  * Take abs value, since stacks grow up on some machines, down on others
3487  */
3488  if (stack_depth < 0)
3489  stack_depth = -stack_depth;
3490 
3491  /*
3492  * Trouble?
3493  *
3494  * The test on stack_base_ptr prevents us from erroring out if called
3495  * during process setup or in a non-backend process. Logically it should
3496  * be done first, but putting it here avoids wasting cycles during normal
3497  * cases.
3498  */
3499  if (stack_depth > max_stack_depth_bytes &&
3500  stack_base_ptr != NULL)
3501  return true;
3502 
3503  return false;
3504 }
static long max_stack_depth_bytes
Definition: postgres.c:119

References max_stack_depth_bytes, and stack_base_ptr.

Referenced by check_stack_depth(), and rstacktoodeep().

◆ superuser()

bool superuser ( void  )

Definition at line 46 of file superuser.c.

47 {
48  return superuser_arg(GetUserId());
49 }

References GetUserId(), and superuser_arg().

Referenced by AlterForeignDataWrapper(), AlterForeignDataWrapperOwner_internal(), AlterForeignServerOwner_internal(), AlterFunction(), AlterObjectNamespace_internal(), AlterObjectOwner_internal(), AlterObjectRename_internal(), AlterOpFamily(), AlterPublicationOwner_internal(), AlterRole(), AlterRoleSet(), AlterSubscription(), AlterSystemSetConfigFile(), AlterType(), AlterTypeOwner(), ATExecChangeOwner(), brin_metapage_info(), brin_page_items(), brin_page_type(), brin_revmap_data(), bt_metap(), bt_multi_page_stats(), bt_page_items_bytea(), bt_page_items_internal(), bt_page_stats_internal(), check_encoding_locale_matches(), CheckAlterPublication(), CreateAccessMethod(), CreateCast(), CreateEventTrigger(), CreateForeignDataWrapper(), CreateFunction(), CreateProceduralLanguage(), CreatePublication(), CreateRole(), CreateSubscription(), CreateTableSpace(), dblink_connstr_check(), dblink_security_check(), DefineAggregate(), DefineOpClass(), DefineOpFamily(), DefineTSParser(), DefineTSTemplate(), DefineType(), DropRole(), dummy_object_relabel(), EnableDisableTrigger(), ExecSetVariableStmt(), execute_extension_script(), ExecuteDoStmt(), fmgr_security_definer(), fsm_page_contents(), get_raw_page_internal(), gin_leafpage_items(), gin_metapage_info(), gin_page_opaque_info(), gist_page_items(), gist_page_items_bytea(), gist_page_opaque_info(), GUCArrayReset(), hash_bitmap_info(), hash_metapage_info(), hash_page_items(), hash_page_stats(), hash_page_type(), have_createdb_privilege(), heap_page_items(), heap_tuple_infomask_flags(), InitPostgres(), interpret_func_support(), main(), page_checksum_internal(), page_header(), pg_import_system_collations(), pg_logdir_ls(), pg_nextoid(), pg_read_file(), pg_relpages(), pg_relpagesbyid(), pg_rotate_logfile(), pg_signal_backend(), pg_stop_making_pinned_objects(), pgstat_get_backend_current_activity(), pgstatginindex(), pgstatindex(), pgstatindexbyid(), pgstattuple(), pgstattuple_approx(), pgstattuplebyid(), postgres_fdw_validator(), ProcedureCreate(), regress_setenv(), RenameRole(), requireSuperuser(), sepgsql_restorecon(), set_config_by_name(), SetPGVariable(), standard_ProcessUtility(), TerminateOtherDBBackends(), tuple_data_split(), validate_option_array_item(), and wait_pid().

◆ superuser_arg()

bool superuser_arg ( Oid  roleid)

Definition at line 56 of file superuser.c.

57 {
58  bool result;
59  HeapTuple rtup;
60 
61  /* Quick out for cache hit */
62  if (OidIsValid(last_roleid) && last_roleid == roleid)
63  return last_roleid_is_super;
64 
65  /* Special escape path in case you deleted all your users. */
66  if (!IsUnderPostmaster && roleid == BOOTSTRAP_SUPERUSERID)
67  return true;
68 
69  /* OK, look up the information in pg_authid */
70  rtup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
71  if (HeapTupleIsValid(rtup))
72  {
73  result = ((Form_pg_authid) GETSTRUCT(rtup))->rolsuper;
74  ReleaseSysCache(rtup);
75  }
76  else
77  {
78  /* Report "not superuser" for invalid roleids */
79  result = false;
80  }
81 
82  /* If first time through, set up callback for cache flushes */
84  {
87  (Datum) 0);
89  }
90 
91  /* Cache the result for next time */
92  last_roleid = roleid;
93  last_roleid_is_super = result;
94 
95  return result;
96 }
void CacheRegisterSyscacheCallback(int cacheid, SyscacheCallbackFunction func, Datum arg)
Definition: inval.c:1519
bool rolsuper
Definition: pg_authid.h:35
uintptr_t Datum
Definition: postgres.h:64
static Oid last_roleid
Definition: superuser.c:35
static bool roleid_callback_registered
Definition: superuser.c:37
static void RoleidCallback(Datum arg, int cacheid, uint32 hashvalue)
Definition: superuser.c:103
static bool last_roleid_is_super
Definition: superuser.c:36

References AUTHOID, CacheRegisterSyscacheCallback(), GETSTRUCT, HeapTupleIsValid, IsUnderPostmaster, last_roleid, last_roleid_is_super, ObjectIdGetDatum(), OidIsValid, ReleaseSysCache(), roleid_callback_registered, RoleidCallback(), rolsuper, and SearchSysCache1().

Referenced by AlterEventTriggerOwner_internal(), AlterForeignDataWrapperOwner_internal(), AlterPublicationOwner_internal(), AlterSubscriptionOwner_internal(), check_conn_params(), check_object_ownership(), check_role_grantor(), check_role_membership_authorization(), connect_pg_server(), CreateRole(), emit_audit_message(), has_bypassrls_privilege(), has_createrole_privilege(), has_privs_of_role(), has_rolreplication(), is_admin_of_role(), is_member_of_role(), LockGXact(), member_can_set_role(), object_aclmask(), object_ownercheck(), pg_class_aclmask_ext(), pg_largeobject_aclmask_snapshot(), pg_namespace_aclmask(), pg_parameter_acl_aclmask(), pg_parameter_aclmask(), pg_signal_backend(), pg_type_aclmask(), REGRESS_exec_check_perms(), REGRESS_object_access_hook(), REGRESS_object_access_hook_str(), REGRESS_utility_command(), select_best_grantor(), superuser(), and TerminateOtherDBBackends().

◆ SwitchBackToLocalLatch()

void SwitchBackToLocalLatch ( void  )

Definition at line 249 of file miscinit.c.

250 {
252  Assert(MyProc != NULL && MyLatch == &MyProc->procLatch);
253 
255 
256  if (FeBeWaitSet)
258  MyLatch);
259 
260  SetLatch(MyLatch);
261 }
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:1008
void SetLatch(Latch *latch)
Definition: latch.c:607
#define WL_LATCH_SET
Definition: latch.h:125
#define FeBeWaitSetLatchPos
Definition: libpq.h:64
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:164
Latch procLatch
Definition: proc.h:170

References Assert(), FeBeWaitSet, FeBeWaitSetLatchPos, LocalLatchData, ModifyWaitEvent(), MyLatch, MyProc, PGPROC::procLatch, SetLatch(), and WL_LATCH_SET.

Referenced by AuxiliaryProcKill(), and ProcKill().

◆ SwitchToSharedLatch()

void SwitchToSharedLatch ( void  )

Definition at line 222 of file miscinit.c.

223 {
225  Assert(MyProc != NULL);
226 
228 
229  if (FeBeWaitSet)
231  MyLatch);
232 
233  /*
234  * Set the shared latch as the local one might have been set. This
235  * shouldn't normally be necessary as code is supposed to check the
236  * condition before waiting for the latch, but a bit care can't hurt.
237  */
238  SetLatch(MyLatch);
239 }

References Assert(), FeBeWaitSet, FeBeWaitSetLatchPos, LocalLatchData, ModifyWaitEvent(), MyLatch, MyProc, PGPROC::procLatch, SetLatch(), and WL_LATCH_SET.

Referenced by InitAuxiliaryProcess(), and InitProcess().

◆ TouchSocketLockFiles()

void TouchSocketLockFiles ( void  )

Definition at line 1486 of file miscinit.c.

1487 {
1488  ListCell *l;
1489 
1490  foreach(l, lock_files)
1491  {
1492  char *socketLockFile = (char *) lfirst(l);
1493 
1494  /* No need to touch the data directory lock file, we trust */
1495  if (strcmp(socketLockFile, DIRECTORY_LOCK_FILE) == 0)
1496  continue;
1497 
1498  /* we just ignore any error here */
1499  (void) utime(socketLockFile, NULL);
1500  }
1501 }
static List * lock_files
Definition: miscinit.c:66
#define lfirst(lc)
Definition: pg_list.h:172

References DIRECTORY_LOCK_FILE, lfirst, and lock_files.

Referenced by ServerLoop().

◆ trace_recovery()

int trace_recovery ( int  trace_level)

◆ ValidatePgVersion()

void ValidatePgVersion ( const char *  path)

Definition at line 1714 of file miscinit.c.

1715 {
1716  char full_path[MAXPGPATH];
1717  FILE *file;
1718  int ret;
1719  long file_major;
1720  long my_major;
1721  char *endptr;
1722  char file_version_string[64];
1723  const char *my_version_string = PG_VERSION;
1724 
1725  my_major = strtol(my_version_string, &endptr, 10);
1726 
1727  snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
1728 
1729  file = AllocateFile(full_path, "r");
1730  if (!file)
1731  {
1732  if (errno == ENOENT)
1733  ereport(FATAL,
1734  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1735  errmsg("\"%s\" is not a valid data directory",
1736  path),
1737  errdetail("File \"%s\" is missing.", full_path)));
1738  else
1739  ereport(FATAL,
1741  errmsg("could not open file \"%s\": %m", full_path)));
1742  }
1743 
1744  file_version_string[0] = '\0';
1745  ret = fscanf(file, "%63s", file_version_string);
1746  file_major = strtol(file_version_string, &endptr, 10);
1747 
1748  if (ret != 1 || endptr == file_version_string)
1749  ereport(FATAL,
1750  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1751  errmsg("\"%s\" is not a valid data directory",
1752  path),
1753  errdetail("File \"%s\" does not contain valid data.",
1754  full_path),
1755  errhint("You might need to initdb.")));
1756 
1757  FreeFile(file);
1758 
1759  if (my_major != file_major)
1760  ereport(FATAL,
1761  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1762  errmsg("database files are incompatible with server"),
1763  errdetail("The data directory was initialized by PostgreSQL version %s, "
1764  "which is not compatible with this version %s.",
1765  file_version_string, my_version_string)));
1766 }
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2384
int FreeFile(FILE *file)
Definition: fd.c:2582

References AllocateFile(), ereport, errcode(), errcode_for_file_access(), errdetail(), errhint(), errmsg(), FATAL, FreeFile(), MAXPGPATH, and snprintf.

Referenced by checkDataDir(), and InitPostgres().

Variable Documentation

◆ allowSystemTableMods

◆ CheckClientConnectionPending

PGDLLIMPORT volatile sig_atomic_t CheckClientConnectionPending
extern

Definition at line 33 of file globals.c.

Referenced by ClientCheckTimeoutHandler(), and ProcessInterrupts().

◆ ClientConnectionLost

PGDLLIMPORT volatile sig_atomic_t ClientConnectionLost
extern

Definition at line 34 of file globals.c.

Referenced by internal_flush(), and ProcessInterrupts().

◆ CritSectionCount

◆ data_directory_mode

PGDLLIMPORT int data_directory_mode
extern

Definition at line 72 of file globals.c.

Referenced by checkDataDir(), RetrieveDataDirCreatePerm(), and show_data_directory_mode().

◆ DatabasePath

◆ DataDir

◆ DateOrder

PGDLLIMPORT int DateOrder
extern

◆ DateStyle

◆ enableFsync

◆ ExitOnAnyError

PGDLLIMPORT bool ExitOnAnyError
extern

Definition at line 117 of file globals.c.

Referenced by errstart(), and HandleCheckpointerInterrupts().

◆ hash_mem_multiplier

PGDLLIMPORT double hash_mem_multiplier
extern

Definition at line 126 of file globals.c.

Referenced by get_hash_memory_limit().

◆ IdleInTransactionSessionTimeoutPending

PGDLLIMPORT volatile sig_atomic_t IdleInTransactionSessionTimeoutPending
extern

Definition at line 35 of file globals.c.

Referenced by IdleInTransactionSessionTimeoutHandler(), and ProcessInterrupts().

◆ IdleSessionTimeoutPending

PGDLLIMPORT volatile sig_atomic_t IdleSessionTimeoutPending
extern

Definition at line 36 of file globals.c.

Referenced by IdleSessionTimeoutHandler(), and ProcessInterrupts().

◆ IdleStatsUpdateTimeoutPending

PGDLLIMPORT volatile sig_atomic_t IdleStatsUpdateTimeoutPending
extern

Definition at line 39 of file globals.c.

Referenced by IdleStatsUpdateTimeoutHandler(), and ProcessInterrupts().

◆ IgnoreSystemIndexes

◆ InterruptHoldoffCount

PGDLLIMPORT volatile uint32 InterruptHoldoffCount
extern

◆ InterruptPending

◆ IntervalStyle

PGDLLIMPORT int IntervalStyle
extern

◆ IsBackgroundWorker

◆ IsBinaryUpgrade

◆ IsPostmasterEnvironment

◆ IsUnderPostmaster

PGDLLIMPORT bool IsUnderPostmaster
extern

Definition at line 113 of file globals.c.

Referenced by _PG_init(), AdvanceNextFullTransactionIdPastXid(), AutoVacuumShmemInit(), AuxiliaryProcessMain(), BackgroundWorkerShmemInit(), bootstrap_signals(), BootstrapModeMain(), BTreeShmemInit(), CheckMyDatabase(), CheckRecoveryConsistency(), CommitTsShmemInit(), createdb(), CreateLWLocks(), CreateRestartPoint(), CreateSharedMemoryAndSemaphores(), DebugFileOpen(), dsm_attach(), dsm_backend_startup(), dsm_create(), dsm_impl_pin_segment(), dsm_impl_posix_resize(), dsm_impl_unpin_segment(), dsm_postmaster_startup(), EventTriggerDDLCommandEnd(), EventTriggerDDLCommandStart(), EventTriggerSQLDrop(), EventTriggerTableRewrite(), ForwardSyncRequest(), get_slru_entry(), GetNewMultiXactId(), GetNewTransactionId(), GetQuitSignalReason(), HandleStartupProcInterrupts(), init_ps_display(), InitializeLatchSupport(), InitializeLatchWaitSet(), InitializeSessionUserId(), InitializeSessionUserIdStandalone(), InitPostgres(), InitPostmasterChild(), InitPredicateLocks(), InitProcess(), InitSync(), LWLockAcquire(), MaintainLatestCompletedXidRecovery(), MultiXactShmemInit(), parallel_vacuum_compute_workers(), PerformRecoveryXLogAction(), PerformWalRecovery(), PGSemaphoreCreate(), PGSharedMemoryNoReAttach(), PGSharedMemoryReAttach(), pgss_shmem_startup(), pgstat_fetch_entry(), pgstat_flush_wal(), pgstat_read_statsfile(), pgstat_report_autovac(), pgstat_report_recovery_conflict(), pgstat_shutdown_hook(), plan_create_index_workers(), PostgresMain(), PostgresSingleUserMain(), process_postgres_switches(), process_settings(), ProcessConfigFileInternal(), ProcKill(), readRecoverySignalFile(), RegisterBackgroundWorker(), RegisterDynamicBackgroundWorker(), ReplicationSlotAcquire(), SendPostmasterSignal(), SerialInit(), set_config_option_ext(), set_config_sourcefile(), SetMultiXactIdLimit(), SetTransactionIdLimit(), ShmemInitStruct(), SimpleLruInit(), standard_planner(), start_xact_command(), StatsShmemInit(), superuser_arg(), SyncScanShmemInit(), TwoPhaseShmemInit(), vacuum_delay_point(), verify_dictoptions(), WaitLatch(), WaitLatchOrSocket(), XLogArchiveNotify(), XLogPageRead(), XLogPrefetchIncrement(), XLogRecGetFullXid(), and XLogWrite().

◆ local_preload_libraries_string

PGDLLIMPORT char* local_preload_libraries_string
extern

Definition at line 1779 of file miscinit.c.

Referenced by process_session_preload_libraries().

◆ LogMemoryContextPending

◆ maintenance_work_mem

◆ max_parallel_maintenance_workers

PGDLLIMPORT int max_parallel_maintenance_workers
extern

Definition at line 128 of file globals.c.

Referenced by parallel_vacuum_compute_workers(), and plan_create_index_workers().

◆ max_parallel_workers

PGDLLIMPORT int max_parallel_workers
extern

Definition at line 139 of file globals.c.

Referenced by RegisterDynamicBackgroundWorker().

◆ max_worker_processes

◆ MaxBackends

◆ MaxConnections

◆ Mode

Definition at line 61 of file miscinit.c.

◆ my_exec_path

◆ MyAuxProcType

PGDLLIMPORT AuxProcType MyAuxProcType
extern

Definition at line 45 of file auxprocess.c.

Referenced by AuxiliaryProcessMain(), and pgstat_beinit().

◆ MyBackendType

◆ MyCancelKey

◆ MyDatabaseId

PGDLLIMPORT Oid MyDatabaseId
extern

Definition at line 89 of file globals.c.

Referenced by AfterTriggerSetState(), AlterDatabase(), AlterObjectRename_internal(), AlterPublicationOwner_internal(), AlterSchemaOwner_internal(), AlterSubscription(), AlterSubscriptionOwner(), asyncQueueNotificationToEntry(), asyncQueueProcessPageEntries(), ATExecDetachPartition(), AutoVacuumRequestWork(), CacheInvalidateCatalog(), CacheInvalidateHeapTuple(), CacheInvalidateRelcache(), CacheInvalidateRelcacheByTuple(), check_default_table_access_method(), check_default_tablespace(), check_default_text_search_config(), check_temp_tablespaces(), CheckLogicalDecodingRequirements(), CheckMyDatabase(), checkSharedDependencies(), checkTempNamespaceStatus(), classIdGetDbId(), ComputeXidHorizons(), CreateDecodingContext(), CreateInitDecodingContext(), CreatePublication(), CreateSchemaCommand(), CreateSubscription(), current_database(), database_to_xml_internal(), DeconstructQualifiedName(), do_analyze_rel(), do_autovacuum(), dropdb(), DropSubscription(), Exec_ListenPreCommit(), exec_object_restorecon(), exec_replication_command(), ExecuteTruncateGuts(), ExpandColumnRefStar(), ExportSnapshot(), extension_is_trusted(), find_funcstat_entry(), find_tabstat_entry(), get_subscription_oid(), GetCurrentVirtualXIDs(), GetNewRelFileNumber(), heap_vacuum_rel(), IdentifySystem(), ImportSnapshot(), initialize_acl(), InitializeParallelDSM(), InitPostgres(), InitTempTableNamespace(), libpqrcv_exec(), LocalExecuteInvalidationMessage(), LockApplyTransactionForSession(), LockDatabaseFrozenIds(), LockDatabaseObject(), LockGXact(), logical_heap_rewrite_flush_mappings(), logical_rewrite_log_mapping(), LogLogicalMessage(), LogStandbyInvalidations(), map_sql_catalog_to_xmlschema_types(), map_sql_schema_to_xmlschema_types(), map_sql_table_to_xmlschema(), map_sql_type_to_xml_name(), match_db_entries(), movedb(), perform_relmap_update(), perform_work_item(), pg_collation_actual_version(), pg_namespace_aclmask(), pg_relation_filepath(), pg_stat_reset_single_function_counters(), pg_stat_reset_single_table_counters(), pgss_store(), pgstat_bestart(), pgstat_build_snapshot(), pgstat_copy_relation_stats(), pgstat_create_function(), pgstat_create_relation(), pgstat_drop_function(), pgstat_drop_relation(), pgstat_fetch_stat_funcentry(), pgstat_fetch_stat_tabentry_ext(), pgstat_init_function_usage(), pgstat_prep_relation_pending(), pgstat_report_analyze(), pgstat_report_checksum_failure(), pgstat_report_connect(), pgstat_report_deadlock(), pgstat_report_disconnect(), pgstat_report_recovery_conflict(), pgstat_report_tempfile(), pgstat_report_vacuum(), pgstat_reset_counters(), pgstat_reset_database_timestamp(), pgstat_shutdown_hook(), pgstat_update_dbstats(), PostgresMain(), PrepareToInvalidateCacheTuple(), PrepareTransaction(), ProcArrayInstallImportedXmin(), ProcArrayInstallRestoredXmin(), RangeVarGetAndCheckCreationNamespace(), RangeVarGetCreationNamespace(), RangeVarGetRelidExtended(), ReindexMultipleTables(), RelationInitLockInfo(), RelationInitPhysicalAddr(), RelationMapFinishBootstrap(), RenameDatabase(), RenameSchema(), ReplicationSlotCreate(), roles_is_member_of(), ScanPgRelation(), sepgsql_schema_post_create(), SetLocktagRelationOid(), shdepDropOwned(), shdepReassignOwned(), SignalBackends(), transformColumnRef(), UnlockApplyTransactionForSession(), UnlockDatabaseObject(), UpdateLogicalMappings(), vac_truncate_clog(), vac_update_datfrozenxid(), vacuum_is_permitted_for_relation(), XactLogAbortRecord(), and XactLogCommitRecord().

◆ MyDatabaseTableSpace

◆ MyLatch

PGDLLIMPORT struct Latch* MyLatch
extern

Definition at line 58 of file globals.c.

Referenced by ApplyLauncherMain(), autoprewarm_main(), AutoVacLauncherMain(), avl_sigusr2_handler(), BackgroundWriterMain(), be_tls_open_server(), CheckDeadLockAlert(), CheckpointerMain(), CheckpointWriteDelay(), ClientCheckTimeoutHandler(), ConditionVariableTimedSleep(), ConfigurePostmasterWaitSet(), copy_read_data(), die(), do_pg_backup_stop(), gather_readnext(), handle_pm_child_exit_signal(), handle_pm_pmsignal_signal(), handle_pm_reload_request_signal(), handle_pm_shutdown_request_signal(), handle_sig_alarm(), HandleCatchupInterrupt(), HandleNotifyInterrupt(), HandleParallelApplyMessageInterrupt(), HandleParallelMessageInterrupt(), IdleInTransactionSessionTimeoutHandler(), IdleSessionTimeoutHandler(), IdleStatsUpdateTimeoutHandler(), InitializeLatchWaitSet(), InitProcessLocalLatch(), lazy_truncate_heap(), libpqrcv_PQgetResult(), libpqsrv_connect_internal(), LogicalParallelApplyLoop(), logicalrep_worker_stop_internal(), LogicalRepApplyLoop(), mq_putmessage(), pa_send_data(), pa_wait_for_xact_state(), pg_promote(), pg_sleep(), pg_wait_until_termination(), pgarch_MainLoop(), pgarch_waken_stop(), pgfdw_get_cleanup_result(), pgfdw_get_result(), pq_check_connection(), pq_init(), ProcessClientReadInterrupt(), ProcessClientWriteInterrupt(), ProcessPendingWrites(), procsignal_sigusr1_handler(), ProcSleep(), ProcWaitForSignal(), read_or_wait(), RecoveryConflictInterrupt(), ReqCheckpointHandler(), secure_open_gssapi(), secure_read(), secure_write(), ServerLoop(), shm_mq_receive_bytes(), shm_mq_send_bytes(), shm_mq_wait_internal(), SignalHandlerForConfigReload(), SignalHandlerForShutdownRequest(), sigUsr1Handler(), StatementCancelHandler(), SwitchBackToLocalLatch(), SwitchToSharedLatch(), SyncRepWaitForLSN(), SysLoggerMain(), test_shm_mq_pipelined(), throttle(), wait_for_relation_state_change(), wait_for_worker_state_change(), wait_for_workers_to_become_ready(), WaitForBackgroundWorkerShutdown(), WaitForBackgroundWorkerStartup(), WaitForParallelWorkersToAttach(), WaitForParallelWorkersToFinish(), WaitForReplicationWorkerAttach(), WalRcvWaitForStartPosition(), WalReceiverMain(), WalSndLastCycleHandler(), WalSndLoop(), WalSndWaitForWal(), and WalWriterMain().

◆ MyPMChildSlot

◆ MyProcPid

PGDLLIMPORT int MyProcPid
extern

Definition at line 44 of file globals.c.

Referenced by AddWaitEventToSet(), ApplyLauncherMain(), apw_detach_shmem(), apw_dump_now(), apw_load_buffers(), apw_start_database_worker(), apw_start_leader_worker(), Async_Listen(), Async_Unlisten(), Async_UnlistenAll(), asyncQueueNotificationToEntry(), asyncQueueReadAllNotifications(), autoprewarm_main(), AutoVacLauncherMain(), basic_archive_file_internal(), CheckpointerMain(), CleanupProcSignalState(), DisownLatch(), Exec_ListenPreCommit(), Exec_UnlistenAllCommit(), Exec_UnlistenCommit(), ExportSnapshot(), FileSetInit(), get_backend_type_for_log(), GetSerializableTransactionSnapshotInt(), HandleWalSndInitStopping(), InitAuxiliaryProcess(), initialize_drandom_seed(), InitializeLatchSupport(), InitializeParallelDSM(), InitLatch(), InitPostmasterDeathWatchHandle(), InitProcess(), InitProcessGlobals(), InitWalSenderSlot(), InvalidatePossiblyObsoleteSlot(), IsLogicalLauncher(), LaunchParallelWorkers(), llvm_compile_module(), LockTimeoutHandler(), log_status_format(), logicalrep_worker_launch(), ModifyWaitEvent(), OpenTemporaryFileInTablespace(), OwnLatch(), ParallelWorkerMain(), pg_backend_pid(), pgstat_bestart(), PostgresMain(), PostmasterMain(), process_pgfdw_appname(), ProcessLogMemoryContextInterrupt(), ProcSignalInit(), ProcSleep(), ReplicationOriginExitCleanup(), ReplicationSlotAcquire(), ReplicationSlotCleanup(), ReplicationSlotCreate(), ReplicationSlotsDropDBSlots(), replorigin_session_setup(), ResetLatch(), ServerLoop(), SetLatch(), setup_background_workers(), SharedInvalBackendInit(), SignalBackends(), SnapBuildSerialize(), StatementTimeoutHandler(), WalRcvDie(), WalReceiverMain(), worker_spi_launch(), write_csvlog(), write_jsonlog(), write_pipe_chunks(), and write_relcache_init_file().

◆ MyProcPort

◆ MyStartTime

◆ MyStartTimestamp

PGDLLIMPORT TimestampTz MyStartTimestamp
extern

◆ NBuffers

PGDLLIMPORT int NBuffers
extern

Definition at line 136 of file globals.c.

◆ OutputFileName

PGDLLIMPORT char OutputFileName[]
extern

Definition at line 74 of file globals.c.

Referenced by BootstrapModeMain(), DebugFileOpen(), and process_postgres_switches().

◆ pkglib_path

◆ PostmasterPid

◆ ProcDiePending

◆ process_shared_preload_libraries_done

PGDLLIMPORT bool process_shared_preload_libraries_done
extern

◆ process_shared_preload_libraries_in_progress

PGDLLIMPORT bool process_shared_preload_libraries_in_progress
extern

◆ process_shmem_requests_in_progress

PGDLLIMPORT bool process_shmem_requests_in_progress
extern

◆ ProcSignalBarrierPending

◆ QueryCancelHoldoffCount

PGDLLIMPORT volatile uint32 QueryCancelHoldoffCount
extern

Definition at line 41 of file globals.c.

Referenced by errfinish(), and ProcessInterrupts().

◆ QueryCancelPending

◆ session_preload_libraries_string

PGDLLIMPORT char* session_preload_libraries_string
extern

Definition at line 1777 of file miscinit.c.

Referenced by process_session_preload_libraries().

◆ shared_preload_libraries_string

PGDLLIMPORT char* shared_preload_libraries_string
extern

Definition at line 1778 of file miscinit.c.

Referenced by process_shared_preload_libraries().

◆ shmem_request_hook

PGDLLIMPORT shmem_request_hook_type shmem_request_hook
extern

Definition at line 1785 of file miscinit.c.

Referenced by _PG_init(), and process_shmem_requests().

◆ trace_recovery_messages

PGDLLIMPORT int trace_recovery_messages
extern

Definition at line 502 of file guc_tables.c.

Referenced by PerformWalRecovery(), and trace_recovery().

◆ VacuumCostActive

◆ VacuumCostBalance

◆ VacuumCostDelay

◆ VacuumCostLimit

◆ VacuumCostPageDirty

PGDLLIMPORT int VacuumCostPageDirty
extern

Definition at line 144 of file globals.c.

Referenced by MarkBufferDirty(), and MarkBufferDirtyHint().

◆ VacuumCostPageHit

PGDLLIMPORT int VacuumCostPageHit
extern

Definition at line 142 of file globals.c.

Referenced by ReadBuffer_common().

◆ VacuumCostPageMiss

PGDLLIMPORT int VacuumCostPageMiss
extern

Definition at line 143 of file globals.c.

Referenced by ReadBuffer_common().

◆ VacuumPageDirty

PGDLLIMPORT int64 VacuumPageDirty
extern

◆ VacuumPageHit

PGDLLIMPORT int64 VacuumPageHit
extern

◆ VacuumPageMiss

PGDLLIMPORT int64 VacuumPageMiss
extern

◆ work_mem