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 MIN_BAS_VAC_RING_SIZE_KB   128
 
#define MAX_BAS_VAC_RING_SIZE_KB   (16 * 1024 * 1024)
 
#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 VacuumBufferUsageLimit
 
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 454 of file miscadmin.h.

◆ AmBackgroundWriterProcess

#define AmBackgroundWriterProcess ( )    (MyAuxProcType == BgWriterProcess)

Definition at line 453 of file miscadmin.h.

◆ AmCheckpointerProcess

#define AmCheckpointerProcess ( )    (MyAuxProcType == CheckpointerProcess)

Definition at line 455 of file miscadmin.h.

◆ AmStartupProcess

#define AmStartupProcess ( )    (MyAuxProcType == StartupProcess)

Definition at line 452 of file miscadmin.h.

◆ AmWalReceiverProcess

#define AmWalReceiverProcess ( )    (MyAuxProcType == WalReceiverProcess)

Definition at line 457 of file miscadmin.h.

◆ AmWalWriterProcess

#define AmWalWriterProcess ( )    (MyAuxProcType == WalWriterProcess)

Definition at line 456 of file miscadmin.h.

◆ BACKEND_NUM_TYPES

#define BACKEND_NUM_TYPES   (B_WAL_WRITER + 1)

Definition at line 344 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 418 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 414 of file miscadmin.h.

◆ IsInitProcessingMode

#define IsInitProcessingMode ( )    (Mode == InitProcessing)

Definition at line 415 of file miscadmin.h.

◆ IsNormalProcessingMode

#define IsNormalProcessingMode ( )    (Mode == NormalProcessing)

Definition at line 416 of file miscadmin.h.

◆ MAX_BAS_VAC_RING_SIZE_KB

#define MAX_BAS_VAC_RING_SIZE_KB   (16 * 1024 * 1024)

Definition at line 272 of file miscadmin.h.

◆ MAXTZLEN

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

Definition at line 257 of file miscadmin.h.

◆ MIN_BAS_VAC_RING_SIZE_KB

#define MIN_BAS_VAC_RING_SIZE_KB   128

Definition at line 271 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 313 of file miscadmin.h.

◆ SECURITY_NOFORCE_RLS

#define SECURITY_NOFORCE_RLS   0x0004

Definition at line 315 of file miscadmin.h.

◆ SECURITY_RESTRICTED_OPERATION

#define SECURITY_RESTRICTED_OPERATION   0x0002

Definition at line 314 of file miscadmin.h.

◆ SetProcessingMode

#define SetProcessingMode (   mode)
Value:
do { \
Assert((mode) == BootstrapProcessing || \
(mode) == InitProcessing || \
Mode = (mode); \
} while(0)
@ NormalProcessing
Definition: miscadmin.h:409
@ InitProcessing
Definition: miscadmin.h:408
@ BootstrapProcessing
Definition: miscadmin.h:407
static PgChecksumMode mode
Definition: pg_checksums.c:56

Definition at line 420 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 291 of file miscadmin.h.

◆ ProcessingMode

◆ shmem_request_hook_type

typedef void(* shmem_request_hook_type) (void)

Definition at line 497 of file miscadmin.h.

Enumeration Type Documentation

◆ AuxProcType

Enumerator
NotAnAuxProcess 
StartupProcess 
BgWriterProcess 
ArchiverProcess 
CheckpointerProcess 
WalWriterProcess 
WalReceiverProcess 
NUM_AUXPROCTYPES 

Definition at line 437 of file miscadmin.h.

438 {
439  NotAnAuxProcess = -1,
440  StartupProcess = 0,
446 
447  NUM_AUXPROCTYPES /* Must be last! */
448 } AuxProcType;
AuxProcType
Definition: miscadmin.h:438
@ BgWriterProcess
Definition: miscadmin.h:441
@ StartupProcess
Definition: miscadmin.h:440
@ NUM_AUXPROCTYPES
Definition: miscadmin.h:447
@ NotAnAuxProcess
Definition: miscadmin.h:439
@ ArchiverProcess
Definition: miscadmin.h:442
@ WalWriterProcess
Definition: miscadmin.h:444
@ WalReceiverProcess
Definition: miscadmin.h:445
@ CheckpointerProcess
Definition: miscadmin.h:443

◆ 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 326 of file miscadmin.h.

327 {
328  B_INVALID = 0,
329  B_ARCHIVER,
332  B_BACKEND,
333  B_BG_WORKER,
334  B_BG_WRITER,
336  B_LOGGER,
338  B_STARTUP,
340  B_WAL_SENDER,
341  B_WAL_WRITER,
342 } BackendType;
BackendType
Definition: miscadmin.h:327
@ B_WAL_WRITER
Definition: miscadmin.h:341
@ B_WAL_RECEIVER
Definition: miscadmin.h:339
@ B_CHECKPOINTER
Definition: miscadmin.h:335
@ B_WAL_SENDER
Definition: miscadmin.h:340
@ B_LOGGER
Definition: miscadmin.h:336
@ B_STARTUP
Definition: miscadmin.h:338
@ B_BG_WORKER
Definition: miscadmin.h:333
@ B_INVALID
Definition: miscadmin.h:328
@ B_STANDALONE_BACKEND
Definition: miscadmin.h:337
@ B_BG_WRITER
Definition: miscadmin.h:334
@ B_BACKEND
Definition: miscadmin.h:332
@ B_ARCHIVER
Definition: miscadmin.h:329
@ B_AUTOVAC_LAUNCHER
Definition: miscadmin.h:330
@ B_AUTOVAC_WORKER
Definition: miscadmin.h:331

◆ ProcessingMode

Enumerator
BootstrapProcessing 
InitProcessing 
NormalProcessing 

Definition at line 405 of file miscadmin.h.

406 {
407  BootstrapProcessing, /* bootstrap creation of template database */
408  InitProcessing, /* initializing system */
409  NormalProcessing /* normal processing */
ProcessingMode
Definition: miscadmin.h:406

Function Documentation

◆ AddToDataDirLockFile()

void AddToDataDirLockFile ( int  target_line,
const char *  str 
)

Definition at line 1497 of file miscinit.c.

1498 {
1499  int fd;
1500  int len;
1501  int lineno;
1502  char *srcptr;
1503  char *destptr;
1504  char srcbuffer[BLCKSZ];
1505  char destbuffer[BLCKSZ];
1506 
1507  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1508  if (fd < 0)
1509  {
1510  ereport(LOG,
1512  errmsg("could not open file \"%s\": %m",
1514  return;
1515  }
1516  pgstat_report_wait_start(WAIT_EVENT_LOCK_FILE_ADDTODATADIR_READ);
1517  len = read(fd, srcbuffer, sizeof(srcbuffer) - 1);
1519  if (len < 0)
1520  {
1521  ereport(LOG,
1523  errmsg("could not read from file \"%s\": %m",
1525  close(fd);
1526  return;
1527  }
1528  srcbuffer[len] = '\0';
1529 
1530  /*
1531  * Advance over lines we are not supposed to rewrite, then copy them to
1532  * destbuffer.
1533  */
1534  srcptr = srcbuffer;
1535  for (lineno = 1; lineno < target_line; lineno++)
1536  {
1537  char *eol = strchr(srcptr, '\n');
1538 
1539  if (eol == NULL)
1540  break; /* not enough lines in file yet */
1541  srcptr = eol + 1;
1542  }
1543  memcpy(destbuffer, srcbuffer, srcptr - srcbuffer);
1544  destptr = destbuffer + (srcptr - srcbuffer);
1545 
1546  /*
1547  * Fill in any missing lines before the target line, in case lines are
1548  * added to the file out of order.
1549  */
1550  for (; lineno < target_line; lineno++)
1551  {
1552  if (destptr < destbuffer + sizeof(destbuffer))
1553  *destptr++ = '\n';
1554  }
1555 
1556  /*
1557  * Write or rewrite the target line.
1558  */
1559  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s\n", str);
1560  destptr += strlen(destptr);
1561 
1562  /*
1563  * If there are more lines in the old file, append them to destbuffer.
1564  */
1565  if ((srcptr = strchr(srcptr, '\n')) != NULL)
1566  {
1567  srcptr++;
1568  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s",
1569  srcptr);
1570  }
1571 
1572  /*
1573  * And rewrite the data. Since we write in a single kernel call, this
1574  * update should appear atomic to onlookers.
1575  */
1576  len = strlen(destbuffer);
1577  errno = 0;
1578  pgstat_report_wait_start(WAIT_EVENT_LOCK_FILE_ADDTODATADIR_WRITE);
1579  if (pg_pwrite(fd, destbuffer, len, 0) != len)
1580  {
1582  /* if write didn't set errno, assume problem is no disk space */
1583  if (errno == 0)
1584  errno = ENOSPC;
1585  ereport(LOG,
1587  errmsg("could not write to file \"%s\": %m",
1589  close(fd);
1590  return;
1591  }
1593  pgstat_report_wait_start(WAIT_EVENT_LOCK_FILE_ADDTODATADIR_SYNC);
1594  if (pg_fsync(fd) != 0)
1595  {
1596  ereport(LOG,
1598  errmsg("could not write to file \"%s\": %m",
1600  }
1602  if (close(fd) != 0)
1603  {
1604  ereport(LOG,
1606  errmsg("could not write to file \"%s\": %m",
1608  }
1609 }
#define PG_BINARY
Definition: c.h:1283
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:361
#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
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:88
static void pgstat_report_wait_end(void)
Definition: wait_event.h:104

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, and generate_unaccent_rules::str.

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

◆ BaseInit()

void BaseInit ( void  )

Definition at line 629 of file postinit.c.

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

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 3523 of file postgres.c.

3524 {
3525  if (stack_is_too_deep())
3526  {
3527  ereport(ERROR,
3528  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3529  errmsg("stack depth limit exceeded"),
3530  errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3531  "after ensuring the platform's stack depth limit is adequate.",
3532  max_stack_depth)));
3533  }
3534 }
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:96
bool stack_is_too_deep(void)
Definition: postgres.c:3537

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_internal(), datum_to_jsonb_internal(), 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(), p_ishost(), p_isURLPath(), 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:1696
#define stat
Definition: win32_port.h:284
#define S_ISDIR(m)
Definition: win32_port.h:325

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 1441 of file miscinit.c.

1442 {
1443  CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, "", true, DataDir);
1444 }
static void CreateLockFile(const char *filename, bool amPostmaster, const char *socketDir, bool isDDLock, const char *refName)
Definition: miscinit.c:1136

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 1450 of file miscinit.c.

1452 {
1453  char lockfile[MAXPGPATH];
1454 
1455  snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
1456  CreateLockFile(lockfile, amPostmaster, socketDir, false, socketfile);
1457 }
#define MAXPGPATH

References CreateLockFile(), MAXPGPATH, and snprintf.

Referenced by Lock_AF_UNIX().

◆ EstimateClientConnectionInfoSpace()

Size EstimateClientConnectionInfoSpace ( void  )

Definition at line 1013 of file miscinit.c.

1014 {
1015  Size size = 0;
1016 
1017  size = add_size(size, sizeof(SerializedClientConnectionInfo));
1018 
1020  size = add_size(size, strlen(MyClientConnectionInfo.authn_id) + 1);
1021 
1022  return size;
1023 }
size_t Size
Definition: c.h:594
ClientConnectionInfo MyClientConnectionInfo
Definition: miscinit.c:996
Size add_size(Size s1, Size s2)
Definition: shmem.c:502
const char * authn_id
Definition: libpq-be.h:114

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 3587 of file nodeHash.c.

3588 {
3589  double mem_limit;
3590 
3591  /* Do initial calculation in double arithmetic */
3592  mem_limit = (double) work_mem * hash_mem_multiplier * 1024.0;
3593 
3594  /* Clamp in case it doesn't fit in size_t */
3595  mem_limit = Min(mem_limit, (double) SIZE_MAX);
3596 
3597  return (size_t) mem_limit;
3598 }
#define Min(x, y)
Definition: c.h:993
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 578 of file miscinit.c.

579 {
581  return AuthenticatedUserId;
582 }
#define OidIsValid(objectId)
Definition: c.h:764
static Oid AuthenticatedUserId
Definition: miscinit.c:489

References Assert(), AuthenticatedUserId, and OidIsValid.

Referenced by check_session_authorization(), and 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 910 of file miscinit.c.

911 {
912  if (SetRoleIsActive)
913  return OuterUserId;
914  else
915  return InvalidOid;
916 }
static Oid OuterUserId
Definition: miscinit.c:491
static bool SetRoleIsActive
Definition: miscinit.c:501
#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 520 of file miscinit.c.

521 {
523  return OuterUserId;
524 }

References Assert(), OidIsValid, and OuterUserId.

Referenced by DropRole(), and RenameRole().

◆ GetSessionUserId()

Oid GetSessionUserId ( void  )

Definition at line 543 of file miscinit.c.

544 {
546  return SessionUserId;
547 }
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 569 of file miscinit.c.

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

References SystemUser.

Referenced by system_user().

◆ GetUserId()

Oid GetUserId ( void  )

Definition at line 509 of file miscinit.c.

510 {
512  return CurrentUserId;
513 }
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(), get_tables_to_cluster_partitioned(), 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(), RangeVarCallbackOwnsRelation(), RangeVarCallbackOwnsTable(), 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_relation_owner(), validate_option_array_item(), ValidateJoinEstimator(), and ValidateRestrictionEstimator().

◆ GetUserIdAndContext()

void GetUserIdAndContext ( Oid userid,
bool sec_def_context 
)

Definition at line 679 of file miscinit.c.

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

References CurrentUserId, and InLocalUserIdChange().

◆ GetUserIdAndSecContext()

◆ GetUserNameFromId()

char* GetUserNameFromId ( Oid  roleid,
bool  noerr 
)

Definition at line 966 of file miscinit.c.

967 {
968  HeapTuple tuple;
969  char *result;
970 
971  tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
972  if (!HeapTupleIsValid(tuple))
973  {
974  if (!noerr)
975  ereport(ERROR,
976  (errcode(ERRCODE_UNDEFINED_OBJECT),
977  errmsg("invalid role OID: %u", roleid)));
978  result = NULL;
979  }
980  else
981  {
982  result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
983  ReleaseSysCache(tuple);
984  }
985  return result;
986 }
#define NameStr(name)
Definition: c.h:735
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
char * pstrdup(const char *in)
Definition: mcxt.c:1644
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:868
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:820
@ 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(), SwitchToUntrustedUser(), and TargetPrivilegesCheck().

◆ has_rolreplication()

bool has_rolreplication ( Oid  roleid)

Definition at line 706 of file miscinit.c.

707 {
708  bool result = false;
709  HeapTuple utup;
710 
711  /* Superusers bypass all permission checking. */
712  if (superuser_arg(roleid))
713  return true;
714 
715  utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
716  if (HeapTupleIsValid(utup))
717  {
718  result = ((Form_pg_authid) GETSTRUCT(utup))->rolreplication;
719  ReleaseSysCache(utup);
720  }
721  return result;
722 }
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 559 of file postinit.c.

560 {
561  Assert(MaxBackends == 0);
562 
563  /* the extra unit accounts for the autovacuum launcher */
566 
567  /* internal error because the values were all checked previously */
569  elog(ERROR, "too many backends configured");
570 }
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 728 of file miscinit.c.

729 {
730  HeapTuple roleTup;
731  Form_pg_authid rform;
732  char *rname;
733  bool is_superuser;
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  is_superuser = 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 &&
809  !is_superuser &&
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  is_superuser ? "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:414
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:551
static bool is_superuser(Archive *fout)
Definition: pg_dump.c:4566
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:322
int CountUserBackends(Oid roleid)
Definition: procarray.c:3607
Oid roleId
Definition: proc.h:199
@ AUTHNAME
Definition: syscache.h:44

References AcceptInvalidationMessages(), Assert(), AuthenticatedUserId, AUTHNAME, AUTHOID, CountUserBackends(), ereport, errcode(), errmsg(), FATAL, GETSTRUCT, HeapTupleIsValid, is_superuser(), 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;
844  SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
845 }
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3397
bool IsBackgroundWorker
Definition: globals.c:115

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

Referenced by InitPostgres().

◆ InitializeSystemUser()

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

Definition at line 853 of file miscinit.c.

854 {
855  char *system_user;
856 
857  /* call only once */
858  Assert(SystemUser == NULL);
859 
860  /*
861  * InitializeSystemUser should be called only when authn_id is not NULL,
862  * meaning that auth_method is valid.
863  */
864  Assert(authn_id != NULL);
865 
866  system_user = psprintf("%s:%s", auth_method, authn_id);
867 
868  /* Store SystemUser in long-lived storage */
871 }
void pfree(void *pointer)
Definition: mcxt.c:1456
MemoryContext TopMemoryContext
Definition: mcxt.c:141
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1631
Datum system_user(PG_FUNCTION_ARGS)
Definition: miscinit.c:877
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 718 of file postinit.c.

723 {
724  bool bootstrap = IsBootstrapProcessingMode();
725  bool am_superuser;
726  char *fullpath;
727  char dbname[NAMEDATALEN];
728  int nfree = 0;
729 
730  elog(DEBUG3, "InitPostgres");
731 
732  /*
733  * Add my PGPROC struct to the ProcArray.
734  *
735  * Once I have done this, I am visible to other backends!
736  */
738 
739  /*
740  * Initialize my entry in the shared-invalidation manager's array of
741  * per-backend data.
742  *
743  * Sets up MyBackendId, a unique backend identifier.
744  */
746 
747  SharedInvalBackendInit(false);
748 
749  if (MyBackendId > MaxBackends || MyBackendId <= 0)
750  elog(FATAL, "bad backend ID: %d", MyBackendId);
751 
752  /* Now that we have a BackendId, we can participate in ProcSignal */
754 
755  /*
756  * Also set up timeout handlers needed for backend operation. We need
757  * these in every case except bootstrap.
758  */
759  if (!bootstrap)
760  {
770  }
771 
772  /*
773  * If this is either a bootstrap process or a standalone backend, start up
774  * the XLOG machinery, and register to have it closed down at exit. In
775  * other cases, the startup process is responsible for starting up the
776  * XLOG machinery, and the checkpointer for closing it down.
777  */
778  if (!IsUnderPostmaster)
779  {
780  /*
781  * We don't yet have an aux-process resource owner, but StartupXLOG
782  * and ShutdownXLOG will need one. Hence, create said resource owner
783  * (and register a callback to clean it up after ShutdownXLOG runs).
784  */
786 
787  StartupXLOG();
788  /* Release (and warn about) any buffer pins leaked in StartupXLOG */
790  /* Reset CurrentResourceOwner to nothing for the moment */
791  CurrentResourceOwner = NULL;
792 
793  /*
794  * Use before_shmem_exit() so that ShutdownXLOG() can rely on DSM
795  * segments etc to work (which in turn is required for pgstats).
796  */
799  }
800 
801  /*
802  * Initialize the relation cache and the system catalog caches. Note that
803  * no catalog access happens here; we only set up the hashtable structure.
804  * We must do this before starting a transaction because transaction abort
805  * would try to touch these hashtables.
806  */
809  InitPlanCache();
810 
811  /* Initialize portal manager */
813 
814  /* Initialize status reporting */
815  pgstat_beinit();
816 
817  /*
818  * Load relcache entries for the shared system catalogs. This must create
819  * at least entries for pg_database and catalogs used for authentication.
820  */
822 
823  /*
824  * Set up process-exit callback to do pre-shutdown cleanup. This is the
825  * one of the first before_shmem_exit callbacks we register; thus, this
826  * will be one the last things we do before low-level modules like the
827  * buffer manager begin to close down. We need to have this in place
828  * before we begin our first transaction --- if we fail during the
829  * initialization transaction, as is entirely possible, we need the
830  * AbortTransaction call to clean up.
831  */
833 
834  /* The autovacuum launcher is done here */
836  {
837  /* report this backend in the PgBackendStatus array */
838  pgstat_bestart();
839 
840  return;
841  }
842 
843  /*
844  * Start a new transaction here before first access to db, and get a
845  * snapshot. We don't have a use for the snapshot itself, but we're
846  * interested in the secondary effect that it sets RecentGlobalXmin. (This
847  * is critical for anything that reads heap pages, because HOT may decide
848  * to prune them even if the process doesn't attempt to modify any
849  * tuples.)
850  *
851  * FIXME: This comment is inaccurate / the code buggy. A snapshot that is
852  * not pushed/active does not reliably prevent HOT pruning (->xmin could
853  * e.g. be cleared when cache invalidations are processed).
854  */
855  if (!bootstrap)
856  {
857  /* statement_timestamp must be set for timeouts to work correctly */
860 
861  /*
862  * transaction_isolation will have been set to the default by the
863  * above. If the default is "serializable", and we are in hot
864  * standby, we will fail if we don't change it to something lower.
865  * Fortunately, "read committed" is plenty good enough.
866  */
868 
869  (void) GetTransactionSnapshot();
870  }
871 
872  /*
873  * Perform client authentication if necessary, then figure out our
874  * postgres user ID, and see if we are a superuser.
875  *
876  * In standalone mode and in autovacuum worker processes, we use a fixed
877  * ID, otherwise we figure it out from the authenticated user name.
878  */
879  if (bootstrap || IsAutoVacuumWorkerProcess())
880  {
882  am_superuser = true;
883  }
884  else if (!IsUnderPostmaster)
885  {
887  am_superuser = true;
888  if (!ThereIsAtLeastOneRole())
890  (errcode(ERRCODE_UNDEFINED_OBJECT),
891  errmsg("no roles are defined in this database system"),
892  errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
893  username != NULL ? username : "postgres")));
894  }
895  else if (IsBackgroundWorker)
896  {
897  if (username == NULL && !OidIsValid(useroid))
898  {
900  am_superuser = true;
901  }
902  else
903  {
905  am_superuser = superuser();
906  }
907  }
908  else
909  {
910  /* normal multiuser case */
911  Assert(MyProcPort != NULL);
914  /* ensure that auth_method is actually valid, aka authn_id is not NULL */
918  am_superuser = superuser();
919  }
920 
921  /*
922  * Binary upgrades only allowed super-user connections
923  */
924  if (IsBinaryUpgrade && !am_superuser)
925  {
926  ereport(FATAL,
927  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
928  errmsg("must be superuser to connect in binary upgrade mode")));
929  }
930 
931  /*
932  * The last few connection slots are reserved for superusers and roles
933  * with privileges of pg_use_reserved_connections. Replication
934  * connections are drawn from slots reserved with max_wal_senders and are
935  * not limited by max_connections, superuser_reserved_connections, or
936  * reserved_connections.
937  *
938  * Note: At this point, the new backend has already claimed a proc struct,
939  * so we must check whether the number of free slots is strictly less than
940  * the reserved connection limits.
941  */
942  if (!am_superuser && !am_walsender &&
945  {
946  if (nfree < SuperuserReservedConnections)
947  ereport(FATAL,
948  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
949  errmsg("remaining connection slots are reserved for roles with the %s attribute",
950  "SUPERUSER")));
951 
952  if (!has_privs_of_role(GetUserId(), ROLE_PG_USE_RESERVED_CONNECTIONS))
953  ereport(FATAL,
954  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
955  errmsg("remaining connection slots are reserved for roles with privileges of the \"%s\" role",
956  "pg_use_reserved_connections")));
957  }
958 
959  /* Check replication permissions needed for walsender processes. */
960  if (am_walsender)
961  {
962  Assert(!bootstrap);
963 
965  ereport(FATAL,
966  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
967  errmsg("permission denied to start WAL sender"),
968  errdetail("Only roles with the %s attribute may start a WAL sender process.",
969  "REPLICATION")));
970  }
971 
972  /*
973  * If this is a plain walsender only supporting physical replication, we
974  * don't want to connect to any particular database. Just finish the
975  * backend startup by processing any options from the startup packet, and
976  * we're done.
977  */
979  {
980  /* process any options passed in the startup packet */
981  if (MyProcPort != NULL)
982  process_startup_options(MyProcPort, am_superuser);
983 
984  /* Apply PostAuthDelay as soon as we've read all options */
985  if (PostAuthDelay > 0)
986  pg_usleep(PostAuthDelay * 1000000L);
987 
988  /* initialize client encoding */
990 
991  /* report this backend in the PgBackendStatus array */
992  pgstat_bestart();
993 
994  /* close the transaction we started above */
996 
997  return;
998  }
999 
1000  /*
1001  * Set up the global variables holding database id and default tablespace.
1002  * But note we won't actually try to touch the database just yet.
1003  *
1004  * We take a shortcut in the bootstrap case, otherwise we have to look up
1005  * the db's entry in pg_database.
1006  */
1007  if (bootstrap)
1008  {
1009  dboid = Template1DbOid;
1010  MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
1011  }
1012  else if (in_dbname != NULL)
1013  {
1014  HeapTuple tuple;
1015  Form_pg_database dbform;
1016 
1017  tuple = GetDatabaseTuple(in_dbname);
1018  if (!HeapTupleIsValid(tuple))
1019  ereport(FATAL,
1020  (errcode(ERRCODE_UNDEFINED_DATABASE),
1021  errmsg("database \"%s\" does not exist", in_dbname)));
1022  dbform = (Form_pg_database) GETSTRUCT(tuple);
1023  dboid = dbform->oid;
1024  }
1025  else if (!OidIsValid(dboid))
1026  {
1027  /*
1028  * If this is a background worker not bound to any particular
1029  * database, we're done now. Everything that follows only makes sense
1030  * if we are bound to a specific database. We do need to close the
1031  * transaction we started before returning.
1032  */
1033  if (!bootstrap)
1034  {
1035  pgstat_bestart();
1037  }
1038  return;
1039  }
1040 
1041  /*
1042  * Now, take a writer's lock on the database we are trying to connect to.
1043  * If there is a concurrently running DROP DATABASE on that database, this
1044  * will block us until it finishes (and has committed its update of
1045  * pg_database).
1046  *
1047  * Note that the lock is not held long, only until the end of this startup
1048  * transaction. This is OK since we will advertise our use of the
1049  * database in the ProcArray before dropping the lock (in fact, that's the
1050  * next thing to do). Anyone trying a DROP DATABASE after this point will
1051  * see us in the array once they have the lock. Ordering is important for
1052  * this because we don't want to advertise ourselves as being in this
1053  * database until we have the lock; otherwise we create what amounts to a
1054  * deadlock with CountOtherDBBackends().
1055  *
1056  * Note: use of RowExclusiveLock here is reasonable because we envision
1057  * our session as being a concurrent writer of the database. If we had a
1058  * way of declaring a session as being guaranteed-read-only, we could use
1059  * AccessShareLock for such sessions and thereby not conflict against
1060  * CREATE DATABASE.
1061  */
1062  if (!bootstrap)
1063  LockSharedObject(DatabaseRelationId, dboid, 0, RowExclusiveLock);
1064 
1065  /*
1066  * Recheck pg_database to make sure the target database hasn't gone away.
1067  * If there was a concurrent DROP DATABASE, this ensures we will die
1068  * cleanly without creating a mess.
1069  */
1070  if (!bootstrap)
1071  {
1072  HeapTuple tuple;
1073  Form_pg_database datform;
1074 
1075  tuple = GetDatabaseTupleByOid(dboid);
1076  if (HeapTupleIsValid(tuple))
1077  datform = (Form_pg_database) GETSTRUCT(tuple);
1078 
1079  if (!HeapTupleIsValid(tuple) ||
1080  (in_dbname && namestrcmp(&datform->datname, in_dbname)))
1081  {
1082  if (in_dbname)
1083  ereport(FATAL,
1084  (errcode(ERRCODE_UNDEFINED_DATABASE),
1085  errmsg("database \"%s\" does not exist", in_dbname),
1086  errdetail("It seems to have just been dropped or renamed.")));
1087  else
1088  ereport(FATAL,
1089  (errcode(ERRCODE_UNDEFINED_DATABASE),
1090  errmsg("database %u does not exist", dboid)));
1091  }
1092 
1093  strlcpy(dbname, NameStr(datform->datname), sizeof(dbname));
1094 
1095  if (database_is_invalid_form(datform))
1096  {
1097  ereport(FATAL,
1098  errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1099  errmsg("cannot connect to invalid database \"%s\"", dbname),
1100  errhint("Use DROP DATABASE to drop invalid databases."));
1101  }
1102 
1103  MyDatabaseTableSpace = datform->dattablespace;
1104  /* pass the database name back to the caller */
1105  if (out_dbname)
1106  strcpy(out_dbname, dbname);
1107  }
1108 
1109  /*
1110  * Now that we rechecked, we are certain to be connected to a database and
1111  * thus can set MyDatabaseId.
1112  *
1113  * It is important that MyDatabaseId only be set once we are sure that the
1114  * target database can no longer be concurrently dropped or renamed. For
1115  * example, without this guarantee, pgstat_update_dbstats() could create
1116  * entries for databases that were just dropped in the pgstat shutdown
1117  * callback, which could confuse other code paths like the autovacuum
1118  * scheduler.
1119  */
1120  MyDatabaseId = dboid;
1121 
1122  /*
1123  * Now we can mark our PGPROC entry with the database ID.
1124  *
1125  * We assume this is an atomic store so no lock is needed; though actually
1126  * things would work fine even if it weren't atomic. Anyone searching the
1127  * ProcArray for this database's ID should hold the database lock, so they
1128  * would not be executing concurrently with this store. A process looking
1129  * for another database's ID could in theory see a chance match if it read
1130  * a partially-updated databaseId value; but as long as all such searches
1131  * wait and retry, as in CountOtherDBBackends(), they will certainly see
1132  * the correct value on their next try.
1133  */
1135 
1136  /*
1137  * We established a catalog snapshot while reading pg_authid and/or
1138  * pg_database; but until we have set up MyDatabaseId, we won't react to
1139  * incoming sinval messages for unshared catalogs, so we won't realize it
1140  * if the snapshot has been invalidated. Assume it's no good anymore.
1141  */
1143 
1144  /*
1145  * Now we should be able to access the database directory safely. Verify
1146  * it's there and looks reasonable.
1147  */
1149 
1150  if (!bootstrap)
1151  {
1152  if (access(fullpath, F_OK) == -1)
1153  {
1154  if (errno == ENOENT)
1155  ereport(FATAL,
1156  (errcode(ERRCODE_UNDEFINED_DATABASE),
1157  errmsg("database \"%s\" does not exist",
1158  dbname),
1159  errdetail("The database subdirectory \"%s\" is missing.",
1160  fullpath)));
1161  else
1162  ereport(FATAL,
1164  errmsg("could not access directory \"%s\": %m",
1165  fullpath)));
1166  }
1167 
1168  ValidatePgVersion(fullpath);
1169  }
1170 
1171  SetDatabasePath(fullpath);
1172  pfree(fullpath);
1173 
1174  /*
1175  * It's now possible to do real access to the system catalogs.
1176  *
1177  * Load relcache entries for the system catalogs. This must create at
1178  * least the minimum set of "nailed-in" cache entries.
1179  */
1181 
1182  /* set up ACL framework (so CheckMyDatabase can check permissions) */
1183  initialize_acl();
1184 
1185  /*
1186  * Re-read the pg_database row for our database, check permissions and set
1187  * up database-specific GUC settings. We can't do this until all the
1188  * database-access infrastructure is up. (Also, it wants to know if the
1189  * user is a superuser, so the above stuff has to happen first.)
1190  */
1191  if (!bootstrap)
1192  CheckMyDatabase(dbname, am_superuser, override_allow_connections);
1193 
1194  /*
1195  * Now process any command-line switches and any additional GUC variable
1196  * settings passed in the startup packet. We couldn't do this before
1197  * because we didn't know if client is a superuser.
1198  */
1199  if (MyProcPort != NULL)
1200  process_startup_options(MyProcPort, am_superuser);
1201 
1202  /* Process pg_db_role_setting options */
1204 
1205  /* Apply PostAuthDelay as soon as we've read all options */
1206  if (PostAuthDelay > 0)
1207  pg_usleep(PostAuthDelay * 1000000L);
1208 
1209  /*
1210  * Initialize various default states that can't be set up until we've
1211  * selected the active user and gotten the right GUC settings.
1212  */
1213 
1214  /* set default namespace search path */
1216 
1217  /* initialize client encoding */
1219 
1220  /* Initialize this backend's session state. */
1222 
1223  /*
1224  * If this is an interactive session, load any libraries that should be
1225  * preloaded at backend start. Since those are determined by GUCs, this
1226  * can't happen until GUC settings are complete, but we want it to happen
1227  * during the initial transaction in case anything that requires database
1228  * access needs to be done.
1229  */
1230  if (load_session_libraries)
1232 
1233  /* report this backend in the PgBackendStatus array */
1234  if (!bootstrap)
1235  pgstat_bestart();
1236 
1237  /* close the transaction we started above */
1238  if (!bootstrap)
1240 }
void initialize_acl(void)
Definition: acl.c:4771
bool has_privs_of_role(Oid member, Oid role)
Definition: acl.c:4961
bool IsAutoVacuumLauncherProcess(void)
Definition: autovacuum.c:3391
void pgstat_beinit(void)
void pgstat_bestart(void)
#define InvalidBackendId
Definition: backendid.h:23
bool database_is_invalid_form(Form_pg_database datform)
Definition: dbcommands.c:3108
#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:3066
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:853
void InitializeSessionUserIdStandalone(void)
Definition: miscinit.c:832
void process_session_preload_libraries(void)
Definition: miscinit.c:1843
Oid GetUserId(void)
Definition: miscinit.c:509
Oid GetSessionUserId(void)
Definition: miscinit.c:543
void SetDatabasePath(const char *path)
Definition: miscinit.c:323
void InitializeSessionUserId(const char *rolename, Oid roleid)
Definition: miscinit.c:728
bool has_rolreplication(Oid roleid)
Definition: miscinit.c:706
int namestrcmp(Name name, const char *str)
Definition: name.c:247
void InitializeSearchPath(void)
Definition: namespace.c:4152
#define NAMEDATALEN
FormData_pg_database * Form_pg_database
Definition: pg_database.h:93
const char * username
Definition: pgbench.c:296
void pgstat_before_server_shutdown(int code, Datum arg)
Definition: pgstat.c:465
void InitPlanCache(void)
Definition: plancache.c:131
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:99
static void ShutdownPostgres(int code, Datum arg)
Definition: postinit.c:1346
static void IdleInTransactionSessionTimeoutHandler(void)
Definition: postinit.c:1395
static void LockTimeoutHandler(void)
Definition: postinit.c:1385
static void IdleStatsUpdateTimeoutHandler(void)
Definition: postinit.c:1411
static void process_settings(Oid databaseid, Oid roleid)
Definition: postinit.c:1312
static void IdleSessionTimeoutHandler(void)
Definition: postinit.c:1403
static void process_startup_options(Port *port, bool am_superuser)
Definition: postinit.c:1247
static void StatementTimeoutHandler(void)
Definition: postinit.c:1363
static void CheckMyDatabase(const char *name, bool am_superuser, bool override_allow_connections)
Definition: postinit.c:313
static bool ThereIsAtLeastOneRole(void)
Definition: postinit.c:1430
static void PerformAuthentication(Port *port)
Definition: postinit.c:190
static void ClientCheckTimeoutHandler(void)
Definition: postinit.c:1419
static HeapTuple GetDatabaseTuple(const char *dbname)
Definition: postinit.c:101
static HeapTuple GetDatabaseTupleByOid(Oid dboid)
Definition: postinit.c:144
int ReservedConnections
Definition: postmaster.c:226
int SuperuserReservedConnections
Definition: postmaster.c:225
short access
Definition: preproc-type.c:36
void ProcSignalInit(int pss_idx)
Definition: procsignal.c:162
void RelationCacheInitializePhase3(void)
Definition: relcache.c:4040
void RelationCacheInitialize(void)
Definition: relcache.c:3935
void RelationCacheInitializePhase2(void)
Definition: relcache.c:3981
char * GetDatabasePath(Oid dbOid, Oid spcOid)
Definition: relpath.c:110
void ReleaseAuxProcessResources(bool isCommit)
Definition: resowner.c:934
ResourceOwner CurrentResourceOwner
Definition: resowner.c:147
void CreateAuxProcessResourceOwner(void)
Definition: resowner.c:914
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:197
void InvalidateCatalogSnapshot(void)
Definition: snapmgr.c:403
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:120
Oid databaseId
Definition: proc.h:198
bool superuser(void)
Definition: superuser.c:46
void InitCatalogCache(void)
Definition: syscache.c:709
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:2937
int XactIsoLevel
Definition: xact.c:79
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:899
void CommitTransactionCommand(void)
Definition: xact.c:3034
#define XACT_READ_COMMITTED
Definition: xact.h:37
void StartupXLOG(void)
Definition: xlog.c:5056
void ShutdownXLOG(int code, Datum arg)
Definition: xlog.c:6199

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, database_is_invalid_form(), 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, namestrcmp(), 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:319
void InitializeLatchSupport(void)
Definition: latch.c:205
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:3473
void InitProcessGlobals(void)
Definition: postmaster.c:2623
int postmaster_alive_fds[2]
Definition: postmaster.c:575
#define POSTMASTER_FD_WATCH
Definition: postmaster.h:46
void pgwin32_signal_initialize(void)
Definition: signal.c:79
#define SIGQUIT
Definition: win32_port.h:169

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:367
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:158
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 648 of file miscinit.c.

649 {
651 }
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:313

References SECURITY_LOCAL_USERID_CHANGE, and SecurityRestrictionContext.

Referenced by GetUserIdAndContext(), and set_config_option_ext().

◆ InNoForceRLSOperation()

bool InNoForceRLSOperation ( void  )

Definition at line 666 of file miscinit.c.

667 {
669 }
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:315

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 1866 of file miscinit.c.

1867 {
1868 #ifdef ENABLE_NLS
1869  if (my_exec_path[0] != '\0')
1870  {
1871  char locale_path[MAXPGPATH];
1872 
1873  get_locale_path(my_exec_path, locale_path);
1874  bindtextdomain(domain, locale_path);
1875  pg_bind_textdomain_codeset(domain);
1876  }
1877 #endif
1878 }
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 501 of file postinit.c.

502 {
503  StringInfoData s;
504 
505  initStringInfo(&s);
506 
507  while (*optstr)
508  {
509  bool last_was_escape = false;
510 
511  resetStringInfo(&s);
512 
513  /* skip over leading space */
514  while (isspace((unsigned char) *optstr))
515  optstr++;
516 
517  if (*optstr == '\0')
518  break;
519 
520  /*
521  * Parse a single option, stopping at the first space, unless it's
522  * escaped.
523  */
524  while (*optstr)
525  {
526  if (isspace((unsigned char) *optstr) && !last_was_escape)
527  break;
528 
529  if (!last_was_escape && *optstr == '\\')
530  last_was_escape = true;
531  else
532  {
533  last_was_escape = false;
534  appendStringInfoChar(&s, *optstr);
535  }
536 
537  optstr++;
538  }
539 
540  /* now store the option in the next argv[] position */
541  argv[(*argcp)++] = pstrdup(s.data);
542  }
543 
544  pfree(s.data);
545 }
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:5948

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 1843 of file miscinit.c.

1844 {
1846  "session_preload_libraries",
1847  false);
1849  "local_preload_libraries",
1850  true);
1851 }
char * session_preload_libraries_string
Definition: miscinit.c:1759
char * local_preload_libraries_string
Definition: miscinit.c:1761
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1777

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 1829 of file miscinit.c.

1830 {
1833  "shared_preload_libraries",
1834  false);
1837 }
bool process_shared_preload_libraries_done
Definition: miscinit.c:1765
char * shared_preload_libraries_string
Definition: miscinit.c:1760
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1764

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 1857 of file miscinit.c.

1858 {
1860  if (shmem_request_hook)
1863 }
bool process_shmem_requests_in_progress
Definition: miscinit.c:1768
shmem_request_hook_type shmem_request_hook
Definition: miscinit.c:1767

References process_shmem_requests_in_progress, and shmem_request_hook.

Referenced by PostgresSingleUserMain(), and PostmasterMain().

◆ ProcessInterrupts()

void ProcessInterrupts ( void  )

Definition at line 3254 of file postgres.c.

3255 {
3256  /* OK to accept any interrupts now? */
3257  if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
3258  return;
3259  InterruptPending = false;
3260 
3261  if (ProcDiePending)
3262  {
3263  ProcDiePending = false;
3264  QueryCancelPending = false; /* ProcDie trumps QueryCancel */
3265  LockErrorCleanup();
3266  /* As in quickdie, don't risk sending to client during auth */
3270  ereport(FATAL,
3271  (errcode(ERRCODE_QUERY_CANCELED),
3272  errmsg("canceling authentication due to timeout")));
3273  else if (IsAutoVacuumWorkerProcess())
3274  ereport(FATAL,
3275  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3276  errmsg("terminating autovacuum process due to administrator command")));
3277  else if (IsLogicalWorker())
3278  ereport(FATAL,
3279  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3280  errmsg("terminating logical replication worker due to administrator command")));
3281  else if (IsLogicalLauncher())
3282  {
3283  ereport(DEBUG1,
3284  (errmsg_internal("logical replication launcher shutting down")));
3285 
3286  /*
3287  * The logical replication launcher can be stopped at any time.
3288  * Use exit status 1 so the background worker is restarted.
3289  */
3290  proc_exit(1);
3291  }
3292  else if (IsBackgroundWorker)
3293  ereport(FATAL,
3294  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3295  errmsg("terminating background worker \"%s\" due to administrator command",
3297  else
3298  ereport(FATAL,
3299  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3300  errmsg("terminating connection due to administrator command")));
3301  }
3302 
3304  {
3306 
3307  /*
3308  * Check for lost connection and re-arm, if still configured, but not
3309  * if we've arrived back at DoingCommandRead state. We don't want to
3310  * wake up idle sessions, and they already know how to detect lost
3311  * connections.
3312  */
3314  {
3315  if (!pq_check_connection())
3316  ClientConnectionLost = true;
3317  else
3320  }
3321  }
3322 
3324  {
3325  QueryCancelPending = false; /* lost connection trumps QueryCancel */
3326  LockErrorCleanup();
3327  /* don't send to client, we already know the connection to be dead. */
3329  ereport(FATAL,
3330  (errcode(ERRCODE_CONNECTION_FAILURE),
3331  errmsg("connection to client lost")));
3332  }
3333 
3334  /*
3335  * Don't allow query cancel interrupts while reading input from the
3336  * client, because we might lose sync in the FE/BE protocol. (Die
3337  * interrupts are OK, because we won't read any further messages from the
3338  * client in that case.)
3339  *
3340  * See similar logic in ProcessRecoveryConflictInterrupts().
3341  */
3343  {
3344  /*
3345  * Re-arm InterruptPending so that we process the cancel request as
3346  * soon as we're done reading the message. (XXX this is seriously
3347  * ugly: it complicates INTERRUPTS_CAN_BE_PROCESSED(), and it means we
3348  * can't use that macro directly as the initial test in this function,
3349  * meaning that this code also creates opportunities for other bugs to
3350  * appear.)
3351  */
3352  InterruptPending = true;
3353  }
3354  else if (QueryCancelPending)
3355  {
3356  bool lock_timeout_occurred;
3357  bool stmt_timeout_occurred;
3358 
3359  QueryCancelPending = false;
3360 
3361  /*
3362  * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
3363  * need to clear both, so always fetch both.
3364  */
3365  lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
3366  stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
3367 
3368  /*
3369  * If both were set, we want to report whichever timeout completed
3370  * earlier; this ensures consistent behavior if the machine is slow
3371  * enough that the second timeout triggers before we get here. A tie
3372  * is arbitrarily broken in favor of reporting a lock timeout.
3373  */
3374  if (lock_timeout_occurred && stmt_timeout_occurred &&
3376  lock_timeout_occurred = false; /* report stmt timeout */
3377 
3378  if (lock_timeout_occurred)
3379  {
3380  LockErrorCleanup();
3381  ereport(ERROR,
3382  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
3383  errmsg("canceling statement due to lock timeout")));
3384  }
3385  if (stmt_timeout_occurred)
3386  {
3387  LockErrorCleanup();
3388  ereport(ERROR,
3389  (errcode(ERRCODE_QUERY_CANCELED),
3390  errmsg("canceling statement due to statement timeout")));
3391  }
3393  {
3394  LockErrorCleanup();
3395  ereport(ERROR,
3396  (errcode(ERRCODE_QUERY_CANCELED),
3397  errmsg("canceling autovacuum task")));
3398  }
3399 
3400  /*
3401  * If we are reading a command from the client, just ignore the cancel
3402  * request --- sending an extra error message won't accomplish
3403  * anything. Otherwise, go ahead and throw the error.
3404  */
3405  if (!DoingCommandRead)
3406  {
3407  LockErrorCleanup();
3408  ereport(ERROR,
3409  (errcode(ERRCODE_QUERY_CANCELED),
3410  errmsg("canceling statement due to user request")));
3411  }
3412  }
3413 
3416 
3418  {
3419  /*
3420  * If the GUC has been reset to zero, ignore the signal. This is
3421  * important because the GUC update itself won't disable any pending
3422  * interrupt.
3423  */
3425  ereport(FATAL,
3426  (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
3427  errmsg("terminating connection due to idle-in-transaction timeout")));
3428  else
3430  }
3431 
3433  {
3434  /* As above, ignore the signal if the GUC has been reset to zero. */
3435  if (IdleSessionTimeout > 0)
3436  ereport(FATAL,
3437  (errcode(ERRCODE_IDLE_SESSION_TIMEOUT),
3438  errmsg("terminating connection due to idle-session timeout")));
3439  else
3440  IdleSessionTimeoutPending = false;
3441  }
3442 
3443  /*
3444  * If there are pending stats updates and we currently are truly idle
3445  * (matching the conditions in PostgresMain(), report stats now.
3446  */
3449  {
3451  pgstat_report_stat(true);
3452  }
3453 
3456 
3459 
3462 
3465 }
volatile sig_atomic_t ParallelApplyMessagePending
void HandleParallelApplyMessages(void)
void HandleParallelMessages(void)
Definition: parallel.c:1026
volatile sig_atomic_t ParallelMessagePending
Definition: parallel.c:117
bool IsLogicalWorker(void)
Definition: worker.c:4744
@ 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:1242
void ProcessLogMemoryContextInterrupt(void)
Definition: mcxt.c:1199
long pgstat_report_stat(bool force)
Definition: pgstat.c:582
int client_connection_check_interval
Definition: postgres.c:102
CommandDest whereToSendOutput
Definition: postgres.c:88
static volatile sig_atomic_t RecoveryConflictPending
Definition: postgres.c:164
static bool DoingCommandRead
Definition: postgres.c:142
static void ProcessRecoveryConflictInterrupts(void)
Definition: postgres.c:3215
bool ClientAuthInProgress
Definition: postmaster.c:356
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:194
bool pq_check_connection(void)
Definition: pqcomm.c:2033
void ProcessProcSignalBarrier(void)
Definition: procsignal.c:468
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:4834

References BackgroundWorker::bgw_type, CheckClientConnectionPending, client_connection_check_interval, CLIENT_CONNECTION_CHECK_TIMEOUT, ClientAuthInProgress, ClientConnectionLost, CritSectionCount, DEBUG1, DestNone, DestRemote, DoingCommandRead, enable_timeout_after(), ereport, errcode(), 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_stat(), pq_check_connection(), proc_exit(), ProcDiePending, ProcessLogMemoryContextInterrupt(), ProcessProcSignalBarrier(), ProcessRecoveryConflictInterrupts(), ProcSignalBarrierPending, QueryCancelHoldoffCount, QueryCancelPending, RecoveryConflictPending, STATEMENT_TIMEOUT, and whereToSendOutput.

Referenced by die().

◆ RecheckDataDirLockFile()

bool RecheckDataDirLockFile ( void  )

Definition at line 1624 of file miscinit.c.

1625 {
1626  int fd;
1627  int len;
1628  long file_pid;
1629  char buffer[BLCKSZ];
1630 
1631  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1632  if (fd < 0)
1633  {
1634  /*
1635  * There are many foreseeable false-positive error conditions. For
1636  * safety, fail only on enumerated clearly-something-is-wrong
1637  * conditions.
1638  */
1639  switch (errno)
1640  {
1641  case ENOENT:
1642  case ENOTDIR:
1643  /* disaster */
1644  ereport(LOG,
1646  errmsg("could not open file \"%s\": %m",
1648  return false;
1649  default:
1650  /* non-fatal, at least for now */
1651  ereport(LOG,
1653  errmsg("could not open file \"%s\": %m; continuing anyway",
1655  return true;
1656  }
1657  }
1658  pgstat_report_wait_start(WAIT_EVENT_LOCK_FILE_RECHECKDATADIR_READ);
1659  len = read(fd, buffer, sizeof(buffer) - 1);
1661  if (len < 0)
1662  {
1663  ereport(LOG,
1665  errmsg("could not read from file \"%s\": %m",
1667  close(fd);
1668  return true; /* treat read failure as nonfatal */
1669  }
1670  buffer[len] = '\0';
1671  close(fd);
1672  file_pid = atol(buffer);
1673  if (file_pid == getpid())
1674  return true; /* all is well */
1675 
1676  /* Trouble: someone's overwritten the lock file */
1677  ereport(LOG,
1678  (errmsg("lock file \"%s\" contains wrong PID: %ld instead of %ld",
1679  DIRECTORY_LOCK_FILE, file_pid, (long) getpid())));
1680  return false;
1681 }

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

Referenced by ServerLoop().

◆ restore_stack_base()

void restore_stack_base ( pg_stack_base_t  base)

Definition at line 3506 of file postgres.c.

3507 {
3508  stack_base_ptr = base;
3509 }
static char * stack_base_ptr
Definition: postgres.c:129

References stack_base_ptr.

◆ RestoreClientConnectionInfo()

void RestoreClientConnectionInfo ( char *  conninfo)

Definition at line 1061 of file miscinit.c.

1062 {
1063  SerializedClientConnectionInfo serialized;
1064 
1065  memcpy(&serialized, conninfo, sizeof(serialized));
1066 
1067  /* Copy the fields back into place */
1070 
1071  if (serialized.authn_id_len >= 0)
1072  {
1073  char *authn_id;
1074 
1075  authn_id = conninfo + sizeof(serialized);
1077  authn_id);
1078  }
1079 }

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 1029 of file miscinit.c.

1030 {
1031  SerializedClientConnectionInfo serialized = {0};
1032 
1033  serialized.authn_id_len = -1;
1035 
1037  serialized.authn_id_len = strlen(MyClientConnectionInfo.authn_id);
1038 
1039  /* Copy serialized representation to buffer */
1040  Assert(maxsize >= sizeof(serialized));
1041  memcpy(start_address, &serialized, sizeof(serialized));
1042 
1043  maxsize -= sizeof(serialized);
1044  start_address += sizeof(serialized);
1045 
1046  /* Copy authn_id into the space after the struct */
1047  if (serialized.authn_id_len >= 0)
1048  {
1049  Assert(maxsize >= (serialized.authn_id_len + 1));
1050  memcpy(start_address,
1052  /* include the NULL terminator to ease deserialization */
1053  serialized.authn_id_len + 1);
1054  }
1055 }

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 3473 of file postgres.c.

3474 {
3475 #ifndef HAVE__BUILTIN_FRAME_ADDRESS
3476  char stack_base;
3477 #endif
3478  pg_stack_base_t old;
3479 
3480  old = stack_base_ptr;
3481 
3482  /*
3483  * Set up reference point for stack depth checking. On recent gcc we use
3484  * __builtin_frame_address() to avoid a warning about storing a local
3485  * variable's address in a long-lived variable.
3486  */
3487 #ifdef HAVE__BUILTIN_FRAME_ADDRESS
3488  stack_base_ptr = __builtin_frame_address(0);
3489 #else
3490  stack_base_ptr = &stack_base;
3491 #endif
3492 
3493  return old;
3494 }
char * pg_stack_base_t
Definition: miscadmin.h:291

References stack_base_ptr.

Referenced by InitPostmasterChild(), and PostmasterMain().

◆ SetCurrentRoleId()

void SetCurrentRoleId ( Oid  roleid,
bool  is_superuser 
)

Definition at line 931 of file miscinit.c.

932 {
933  /*
934  * Get correct info if it's SET ROLE NONE
935  *
936  * If SessionUserId hasn't been set yet, just do nothing --- the eventual
937  * SetSessionUserId call will fix everything. This is needed since we
938  * will get called during GUC initialization.
939  */
940  if (!OidIsValid(roleid))
941  {
943  return;
944 
945  roleid = SessionUserId;
947 
948  SetRoleIsActive = false;
949  }
950  else
951  SetRoleIsActive = true;
952 
953  SetOuterUserId(roleid);
954 
955  SetConfigOption("is_superuser",
956  is_superuser ? "on" : "off",
958 }
static void SetOuterUserId(Oid userid)
Definition: miscinit.c:528
static bool SessionUserIsSuperuser
Definition: miscinit.c:496

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 894 of file miscinit.c.

895 {
897 
898  SetConfigOption("is_superuser",
899  is_superuser ? "on" : "off",
901 }

References is_superuser(), 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 686 of file miscinit.c.

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

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 3537 of file postgres.c.

3538 {
3539  char stack_top_loc;
3540  long stack_depth;
3541 
3542  /*
3543  * Compute distance from reference point to my local variables
3544  */
3545  stack_depth = (long) (stack_base_ptr - &stack_top_loc);
3546 
3547  /*
3548  * Take abs value, since stacks grow up on some machines, down on others
3549  */
3550  if (stack_depth < 0)
3551  stack_depth = -stack_depth;
3552 
3553  /*
3554  * Trouble?
3555  *
3556  * The test on stack_base_ptr prevents us from erroring out if called
3557  * during process setup or in a non-backend process. Logically it should
3558  * be done first, but putting it here avoids wasting cycles during normal
3559  * cases.
3560  */
3561  if (stack_depth > max_stack_depth_bytes &&
3562  stack_base_ptr != NULL)
3563  return true;
3564 
3565  return false;
3566 }
static long max_stack_depth_bytes
Definition: postgres.c:123

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(), AlterSubscriptionOwner_internal(), 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(), AlterSubscription(), AlterSubscription_refresh(), check_conn_params(), check_object_ownership(), check_role_grantor(), check_role_membership_authorization(), check_session_authorization(), CreateRole(), CreateSubscription(), DropSubscription(), emit_audit_message(), has_bypassrls_privilege(), has_createrole_privilege(), has_privs_of_role(), has_rolreplication(), is_admin_of_role(), is_member_of_role(), LockGXact(), LogicalRepSyncTableStart(), 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(), pgfdw_security_check(), REGRESS_exec_check_perms(), REGRESS_object_access_hook(), REGRESS_object_access_hook_str(), REGRESS_utility_command(), run_apply_worker(), 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:1006
void SetLatch(Latch *latch)
Definition: latch.c:605
#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 1468 of file miscinit.c.

1469 {
1470  ListCell *l;
1471 
1472  foreach(l, lock_files)
1473  {
1474  char *socketLockFile = (char *) lfirst(l);
1475 
1476  /* No need to touch the data directory lock file, we trust */
1477  if (strcmp(socketLockFile, DIRECTORY_LOCK_FILE) == 0)
1478  continue;
1479 
1480  /* we just ignore any error here */
1481  (void) utime(socketLockFile, NULL);
1482  }
1483 }
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 1696 of file miscinit.c.

1697 {
1698  char full_path[MAXPGPATH];
1699  FILE *file;
1700  int ret;
1701  long file_major;
1702  long my_major;
1703  char *endptr;
1704  char file_version_string[64];
1705  const char *my_version_string = PG_VERSION;
1706 
1707  my_major = strtol(my_version_string, &endptr, 10);
1708 
1709  snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
1710 
1711  file = AllocateFile(full_path, "r");
1712  if (!file)
1713  {
1714  if (errno == ENOENT)
1715  ereport(FATAL,
1716  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1717  errmsg("\"%s\" is not a valid data directory",
1718  path),
1719  errdetail("File \"%s\" is missing.", full_path)));
1720  else
1721  ereport(FATAL,
1723  errmsg("could not open file \"%s\": %m", full_path)));
1724  }
1725 
1726  file_version_string[0] = '\0';
1727  ret = fscanf(file, "%63s", file_version_string);
1728  file_major = strtol(file_version_string, &endptr, 10);
1729 
1730  if (ret != 1 || endptr == file_version_string)
1731  ereport(FATAL,
1732  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1733  errmsg("\"%s\" is not a valid data directory",
1734  path),
1735  errdetail("File \"%s\" does not contain valid data.",
1736  full_path),
1737  errhint("You might need to initdb.")));
1738 
1739  FreeFile(file);
1740 
1741  if (my_major != file_major)
1742  ereport(FATAL,
1743  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1744  errmsg("database files are incompatible with server"),
1745  errdetail("The data directory was initialized by PostgreSQL version %s, "
1746  "which is not compatible with this version %s.",
1747  file_version_string, my_version_string)));
1748 }
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2528
int FreeFile(FILE *file)
Definition: fd.c:2726

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

◆ 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 1761 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(), AlterSubscriptionOwner_internal(), 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(), get_tables_to_cluster_partitioned(), GetCurrentVirtualXIDs(), GetNewRelFileNumber(), heap_vacuum_rel(), IdentifySystem(), ImportSnapshot(), initialize_acl(), InitializeParallelDSM(), InitPostgres(), InitTempTableNamespace(), InitWalSenderSlot(), 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_database_pending(), 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_relation_owner(), 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(), 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(), WalWriterMain(), and worker_spi_main().

◆ 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

PGDLLIMPORT volatile sig_atomic_t ProcDiePending
extern

◆ 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(), ProcessInterrupts(), and ProcessRecoveryConflictInterrupt().

◆ QueryCancelPending

◆ session_preload_libraries_string

PGDLLIMPORT char* session_preload_libraries_string
extern

Definition at line 1759 of file miscinit.c.

Referenced by process_session_preload_libraries().

◆ shared_preload_libraries_string

PGDLLIMPORT char* shared_preload_libraries_string
extern

Definition at line 1760 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 1767 of file miscinit.c.

Referenced by _PG_init(), and process_shmem_requests().

◆ trace_recovery_messages

PGDLLIMPORT int trace_recovery_messages
extern

Definition at line 528 of file guc_tables.c.

Referenced by PerformWalRecovery(), and trace_recovery().

◆ VacuumBufferUsageLimit

PGDLLIMPORT int VacuumBufferUsageLimit
extern

Definition at line 143 of file globals.c.

Referenced by do_autovacuum(), and ExecVacuum().

◆ VacuumCostActive

◆ VacuumCostBalance

◆ VacuumCostDelay

PGDLLIMPORT double VacuumCostDelay
extern

Definition at line 149 of file globals.c.

Referenced by VacuumUpdateCosts().

◆ VacuumCostLimit

PGDLLIMPORT int VacuumCostLimit
extern

Definition at line 148 of file globals.c.

Referenced by AutoVacuumUpdateCostLimit(), and VacuumUpdateCosts().

◆ VacuumCostPageDirty

PGDLLIMPORT int VacuumCostPageDirty
extern

Definition at line 147 of file globals.c.

Referenced by MarkBufferDirty(), and MarkBufferDirtyHint().

◆ VacuumCostPageHit

PGDLLIMPORT int VacuumCostPageHit
extern

Definition at line 145 of file globals.c.

Referenced by ReadBuffer_common().

◆ VacuumCostPageMiss

PGDLLIMPORT int VacuumCostPageMiss
extern

Definition at line 146 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