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_LOGGER + 1)
 
#define AmAutoVacuumLauncherProcess()   (MyBackendType == B_AUTOVAC_LAUNCHER)
 
#define AmAutoVacuumWorkerProcess()   (MyBackendType == B_AUTOVAC_WORKER)
 
#define AmBackgroundWorkerProcess()   (MyBackendType == B_BG_WORKER)
 
#define AmWalSenderProcess()   (MyBackendType == B_WAL_SENDER)
 
#define AmLogicalSlotSyncWorkerProcess()   (MyBackendType == B_SLOTSYNC_WORKER)
 
#define AmArchiverProcess()   (MyBackendType == B_ARCHIVER)
 
#define AmBackgroundWriterProcess()   (MyBackendType == B_BG_WRITER)
 
#define AmCheckpointerProcess()   (MyBackendType == B_CHECKPOINTER)
 
#define AmStartupProcess()   (MyBackendType == B_STARTUP)
 
#define AmWalReceiverProcess()   (MyBackendType == B_WAL_RECEIVER)
 
#define AmWalSummarizerProcess()   (MyBackendType == B_WAL_SUMMARIZER)
 
#define AmWalWriterProcess()   (MyBackendType == B_WAL_WRITER)
 
#define IsBootstrapProcessingMode()   (Mode == BootstrapProcessing)
 
#define IsInitProcessingMode()   (Mode == InitProcessing)
 
#define IsNormalProcessingMode()   (Mode == NormalProcessing)
 
#define GetProcessingMode()   Mode
 
#define SetProcessingMode(mode)
 
#define INIT_PG_LOAD_SESSION_LIBS   0x0001
 
#define INIT_PG_OVERRIDE_ALLOW_CONNS   0x0002
 
#define INIT_PG_OVERRIDE_ROLE_LOGIN   0x0004
 

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_BACKEND , B_AUTOVAC_LAUNCHER , B_AUTOVAC_WORKER ,
  B_BG_WORKER , B_WAL_SENDER , B_SLOTSYNC_WORKER , B_STANDALONE_BACKEND ,
  B_ARCHIVER , B_BG_WRITER , B_CHECKPOINTER , B_STARTUP ,
  B_WAL_RECEIVER , B_WAL_SUMMARIZER , B_WAL_WRITER , B_LOGGER
}
 
enum  ProcessingMode { BootstrapProcessing , InitProcessing , NormalProcessing }
 

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)
 
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, bool bypass_login_check)
 
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 InitializeFastPathLocks (void)
 
void InitPostgres (const char *in_dbname, Oid dboid, const char *username, Oid useroid, bits32 flags, 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 TransactionTimeoutPending
 
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 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 commit_timestamp_buffers
 
PGDLLIMPORT int multixact_member_buffers
 
PGDLLIMPORT int multixact_offset_buffers
 
PGDLLIMPORT int notify_buffers
 
PGDLLIMPORT int serializable_buffers
 
PGDLLIMPORT int subtransaction_buffers
 
PGDLLIMPORT int transaction_buffers
 
PGDLLIMPORT int MyProcPid
 
PGDLLIMPORT pg_time_t MyStartTime
 
PGDLLIMPORT TimestampTz MyStartTimestamp
 
PGDLLIMPORT struct PortMyProcPort
 
PGDLLIMPORT struct LatchMyLatch
 
PGDLLIMPORT bool MyCancelKeyValid
 
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 bool MyDatabaseHasLoginEventTriggers
 
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 int VacuumCostBalance
 
PGDLLIMPORT bool VacuumCostActive
 
PGDLLIMPORT char * DatabasePath
 
PGDLLIMPORT BackendType MyBackendType
 
PGDLLIMPORT ProcessingMode Mode
 
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 ( )    (MyBackendType == B_ARCHIVER)

Definition at line 376 of file miscadmin.h.

◆ AmAutoVacuumLauncherProcess

#define AmAutoVacuumLauncherProcess ( )    (MyBackendType == B_AUTOVAC_LAUNCHER)

Definition at line 371 of file miscadmin.h.

◆ AmAutoVacuumWorkerProcess

#define AmAutoVacuumWorkerProcess ( )    (MyBackendType == B_AUTOVAC_WORKER)

Definition at line 372 of file miscadmin.h.

◆ AmBackgroundWorkerProcess

#define AmBackgroundWorkerProcess ( )    (MyBackendType == B_BG_WORKER)

Definition at line 373 of file miscadmin.h.

◆ AmBackgroundWriterProcess

#define AmBackgroundWriterProcess ( )    (MyBackendType == B_BG_WRITER)

Definition at line 377 of file miscadmin.h.

◆ AmCheckpointerProcess

#define AmCheckpointerProcess ( )    (MyBackendType == B_CHECKPOINTER)

Definition at line 378 of file miscadmin.h.

◆ AmLogicalSlotSyncWorkerProcess

#define AmLogicalSlotSyncWorkerProcess ( )    (MyBackendType == B_SLOTSYNC_WORKER)

Definition at line 375 of file miscadmin.h.

◆ AmStartupProcess

#define AmStartupProcess ( )    (MyBackendType == B_STARTUP)

Definition at line 379 of file miscadmin.h.

◆ AmWalReceiverProcess

#define AmWalReceiverProcess ( )    (MyBackendType == B_WAL_RECEIVER)

Definition at line 380 of file miscadmin.h.

◆ AmWalSenderProcess

#define AmWalSenderProcess ( )    (MyBackendType == B_WAL_SENDER)

Definition at line 374 of file miscadmin.h.

◆ AmWalSummarizerProcess

#define AmWalSummarizerProcess ( )    (MyBackendType == B_WAL_SUMMARIZER)

Definition at line 381 of file miscadmin.h.

◆ AmWalWriterProcess

#define AmWalWriterProcess ( )    (MyBackendType == B_WAL_WRITER)

Definition at line 382 of file miscadmin.h.

◆ BACKEND_NUM_TYPES

#define BACKEND_NUM_TYPES   (B_LOGGER + 1)

Definition at line 367 of file miscadmin.h.

◆ CHECK_FOR_INTERRUPTS

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

Definition at line 122 of file miscadmin.h.

◆ DATEORDER_DMY

#define DATEORDER_DMY   1

Definition at line 243 of file miscadmin.h.

◆ DATEORDER_MDY

#define DATEORDER_MDY   2

Definition at line 244 of file miscadmin.h.

◆ DATEORDER_YMD

#define DATEORDER_YMD   0

Definition at line 242 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:44

Definition at line 151 of file miscadmin.h.

◆ GetProcessingMode

#define GetProcessingMode ( )    Mode

Definition at line 455 of file miscadmin.h.

◆ HOLD_CANCEL_INTERRUPTS

#define HOLD_CANCEL_INTERRUPTS ( )    (QueryCancelHoldoffCount++)

Definition at line 141 of file miscadmin.h.

◆ HOLD_INTERRUPTS

#define HOLD_INTERRUPTS ( )    (InterruptHoldoffCount++)

Definition at line 133 of file miscadmin.h.

◆ INIT_PG_LOAD_SESSION_LIBS

#define INIT_PG_LOAD_SESSION_LIBS   0x0001

Definition at line 473 of file miscadmin.h.

◆ INIT_PG_OVERRIDE_ALLOW_CONNS

#define INIT_PG_OVERRIDE_ALLOW_CONNS   0x0002

Definition at line 474 of file miscadmin.h.

◆ INIT_PG_OVERRIDE_ROLE_LOGIN

#define INIT_PG_OVERRIDE_ROLE_LOGIN   0x0004

Definition at line 475 of file miscadmin.h.

◆ INTERRUPTS_CAN_BE_PROCESSED

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

Definition at line 129 of file miscadmin.h.

◆ INTERRUPTS_PENDING_CONDITION

#define INTERRUPTS_PENDING_CONDITION ( )     (unlikely(InterruptPending))

Definition at line 113 of file miscadmin.h.

◆ INTSTYLE_ISO_8601

#define INTSTYLE_ISO_8601   3

Definition at line 259 of file miscadmin.h.

◆ INTSTYLE_POSTGRES

#define INTSTYLE_POSTGRES   0

Definition at line 256 of file miscadmin.h.

◆ INTSTYLE_POSTGRES_VERBOSE

#define INTSTYLE_POSTGRES_VERBOSE   1

Definition at line 257 of file miscadmin.h.

◆ INTSTYLE_SQL_STANDARD

#define INTSTYLE_SQL_STANDARD   2

Definition at line 258 of file miscadmin.h.

◆ InvalidPid

#define InvalidPid   (-1)

Definition at line 32 of file miscadmin.h.

◆ IsBootstrapProcessingMode

#define IsBootstrapProcessingMode ( )    (Mode == BootstrapProcessing)

Definition at line 451 of file miscadmin.h.

◆ IsInitProcessingMode

#define IsInitProcessingMode ( )    (Mode == InitProcessing)

Definition at line 452 of file miscadmin.h.

◆ IsNormalProcessingMode

#define IsNormalProcessingMode ( )    (Mode == NormalProcessing)

Definition at line 453 of file miscadmin.h.

◆ MAX_BAS_VAC_RING_SIZE_KB

#define MAX_BAS_VAC_RING_SIZE_KB   (16 * 1024 * 1024)

Definition at line 278 of file miscadmin.h.

◆ MAXTZLEN

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

Definition at line 263 of file miscadmin.h.

◆ MIN_BAS_VAC_RING_SIZE_KB

#define MIN_BAS_VAC_RING_SIZE_KB   128

Definition at line 277 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:43

Definition at line 143 of file miscadmin.h.

◆ RESUME_INTERRUPTS

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

Definition at line 135 of file miscadmin.h.

◆ SECURITY_LOCAL_USERID_CHANGE

#define SECURITY_LOCAL_USERID_CHANGE   0x0001

Definition at line 311 of file miscadmin.h.

◆ SECURITY_NOFORCE_RLS

#define SECURITY_NOFORCE_RLS   0x0004

Definition at line 313 of file miscadmin.h.

◆ SECURITY_RESTRICTED_OPERATION

#define SECURITY_RESTRICTED_OPERATION   0x0002

Definition at line 312 of file miscadmin.h.

◆ SetProcessingMode

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

Definition at line 457 of file miscadmin.h.

◆ START_CRIT_SECTION

#define START_CRIT_SECTION ( )    (CritSectionCount++)

Definition at line 149 of file miscadmin.h.

◆ USE_GERMAN_DATES

#define USE_GERMAN_DATES   3

Definition at line 238 of file miscadmin.h.

◆ USE_ISO_DATES

#define USE_ISO_DATES   1

Definition at line 236 of file miscadmin.h.

◆ USE_POSTGRES_DATES

#define USE_POSTGRES_DATES   0

Definition at line 235 of file miscadmin.h.

◆ USE_SQL_DATES

#define USE_SQL_DATES   2

Definition at line 237 of file miscadmin.h.

◆ USE_XSD_DATES

#define USE_XSD_DATES   4

Definition at line 239 of file miscadmin.h.

Typedef Documentation

◆ BackendType

typedef enum BackendType BackendType

◆ pg_stack_base_t

typedef char* pg_stack_base_t

Definition at line 293 of file miscadmin.h.

◆ ProcessingMode

◆ shmem_request_hook_type

typedef void(* shmem_request_hook_type) (void)

Definition at line 507 of file miscadmin.h.

Enumeration Type Documentation

◆ BackendType

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

Definition at line 330 of file miscadmin.h.

331 {
332  B_INVALID = 0,
333 
334  /* Backends and other backend-like processes */
335  B_BACKEND,
338  B_BG_WORKER,
339  B_WAL_SENDER,
341 
343 
344  /*
345  * Auxiliary processes. These have PGPROC entries, but they are not
346  * attached to any particular database. There can be only one of each of
347  * these running at a time.
348  *
349  * If you modify these, make sure to update NUM_AUXILIARY_PROCS and the
350  * glossary in the docs.
351  */
352  B_ARCHIVER,
353  B_BG_WRITER,
355  B_STARTUP,
358  B_WAL_WRITER,
359 
360  /*
361  * Logger is not connected to shared memory and does not have a PGPROC
362  * entry.
363  */
364  B_LOGGER,
365 } BackendType;
BackendType
Definition: miscadmin.h:331
@ B_WAL_SUMMARIZER
Definition: miscadmin.h:357
@ B_WAL_WRITER
Definition: miscadmin.h:358
@ B_WAL_RECEIVER
Definition: miscadmin.h:356
@ B_CHECKPOINTER
Definition: miscadmin.h:354
@ B_WAL_SENDER
Definition: miscadmin.h:339
@ B_LOGGER
Definition: miscadmin.h:364
@ B_STARTUP
Definition: miscadmin.h:355
@ B_BG_WORKER
Definition: miscadmin.h:338
@ B_INVALID
Definition: miscadmin.h:332
@ B_STANDALONE_BACKEND
Definition: miscadmin.h:342
@ B_BG_WRITER
Definition: miscadmin.h:353
@ B_BACKEND
Definition: miscadmin.h:335
@ B_ARCHIVER
Definition: miscadmin.h:352
@ B_AUTOVAC_LAUNCHER
Definition: miscadmin.h:336
@ B_SLOTSYNC_WORKER
Definition: miscadmin.h:340
@ B_AUTOVAC_WORKER
Definition: miscadmin.h:337

◆ ProcessingMode

Enumerator
BootstrapProcessing 
InitProcessing 
NormalProcessing 

Definition at line 442 of file miscadmin.h.

443 {
444  BootstrapProcessing, /* bootstrap creation of template database */
445  InitProcessing, /* initializing system */
446  NormalProcessing, /* normal processing */
ProcessingMode
Definition: miscadmin.h:443

Function Documentation

◆ AddToDataDirLockFile()

void AddToDataDirLockFile ( int  target_line,
const char *  str 
)

Definition at line 1511 of file miscinit.c.

1512 {
1513  int fd;
1514  int len;
1515  int lineno;
1516  char *srcptr;
1517  char *destptr;
1518  char srcbuffer[BLCKSZ];
1519  char destbuffer[BLCKSZ];
1520 
1521  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1522  if (fd < 0)
1523  {
1524  ereport(LOG,
1526  errmsg("could not open file \"%s\": %m",
1528  return;
1529  }
1530  pgstat_report_wait_start(WAIT_EVENT_LOCK_FILE_ADDTODATADIR_READ);
1531  len = read(fd, srcbuffer, sizeof(srcbuffer) - 1);
1533  if (len < 0)
1534  {
1535  ereport(LOG,
1537  errmsg("could not read from file \"%s\": %m",
1539  close(fd);
1540  return;
1541  }
1542  srcbuffer[len] = '\0';
1543 
1544  /*
1545  * Advance over lines we are not supposed to rewrite, then copy them to
1546  * destbuffer.
1547  */
1548  srcptr = srcbuffer;
1549  for (lineno = 1; lineno < target_line; lineno++)
1550  {
1551  char *eol = strchr(srcptr, '\n');
1552 
1553  if (eol == NULL)
1554  break; /* not enough lines in file yet */
1555  srcptr = eol + 1;
1556  }
1557  memcpy(destbuffer, srcbuffer, srcptr - srcbuffer);
1558  destptr = destbuffer + (srcptr - srcbuffer);
1559 
1560  /*
1561  * Fill in any missing lines before the target line, in case lines are
1562  * added to the file out of order.
1563  */
1564  for (; lineno < target_line; lineno++)
1565  {
1566  if (destptr < destbuffer + sizeof(destbuffer))
1567  *destptr++ = '\n';
1568  }
1569 
1570  /*
1571  * Write or rewrite the target line.
1572  */
1573  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s\n", str);
1574  destptr += strlen(destptr);
1575 
1576  /*
1577  * If there are more lines in the old file, append them to destbuffer.
1578  */
1579  if ((srcptr = strchr(srcptr, '\n')) != NULL)
1580  {
1581  srcptr++;
1582  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s",
1583  srcptr);
1584  }
1585 
1586  /*
1587  * And rewrite the data. Since we write in a single kernel call, this
1588  * update should appear atomic to onlookers.
1589  */
1590  len = strlen(destbuffer);
1591  errno = 0;
1592  pgstat_report_wait_start(WAIT_EVENT_LOCK_FILE_ADDTODATADIR_WRITE);
1593  if (pg_pwrite(fd, destbuffer, len, 0) != len)
1594  {
1596  /* if write didn't set errno, assume problem is no disk space */
1597  if (errno == 0)
1598  errno = ENOSPC;
1599  ereport(LOG,
1601  errmsg("could not write to file \"%s\": %m",
1603  close(fd);
1604  return;
1605  }
1607  pgstat_report_wait_start(WAIT_EVENT_LOCK_FILE_ADDTODATADIR_SYNC);
1608  if (pg_fsync(fd) != 0)
1609  {
1610  ereport(LOG,
1612  errmsg("could not write to file \"%s\": %m",
1614  }
1616  if (close(fd) != 0)
1617  {
1618  ereport(LOG,
1620  errmsg("could not write to file \"%s\": %m",
1622  }
1623 }
#define PG_BINARY
Definition: c.h:1264
int errcode_for_file_access(void)
Definition: elog.c:876
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define LOG
Definition: elog.h:31
#define ereport(elevel,...)
Definition: elog.h:149
int pg_fsync(int fd)
Definition: fd.c:386
const char * str
#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:85
static void pgstat_report_wait_end(void)
Definition: wait_event.h:101

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 str.

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

◆ BaseInit()

void BaseInit ( void  )

Definition at line 603 of file postinit.c.

604 {
605  Assert(MyProc != NULL);
606 
607  /*
608  * Initialize our input/output/debugging file descriptors.
609  */
610  DebugFileOpen();
611 
612  /*
613  * Initialize file access. Done early so other subsystems can access
614  * files.
615  */
616  InitFileAccess();
617 
618  /*
619  * Initialize statistics reporting. This needs to happen early to ensure
620  * that pgstat's shutdown callback runs after the shutdown callbacks of
621  * all subsystems that can produce stats (like e.g. transaction commits
622  * can).
623  */
625 
626  /* Do local initialization of storage and buffer managers */
627  InitSync();
628  smgrinit();
630 
631  /*
632  * Initialize temporary file access after pgstat, so that the temporary
633  * file shutdown hook can report temporary file statistics.
634  */
636 
637  /*
638  * Initialize local buffers for WAL record construction, in case we ever
639  * try to insert XLOG.
640  */
641  InitXLogInsert();
642 
643  /* Initialize lock manager's local structs */
645 
646  /*
647  * Initialize replication slots after pgstat. The exit hook might need to
648  * drop ephemeral slots, which in turn triggers stats reporting.
649  */
651 }
void InitBufferManagerAccess(void)
Definition: bufmgr.c:3576
#define Assert(condition)
Definition: c.h:849
void DebugFileOpen(void)
Definition: elog.c:2111
void InitFileAccess(void)
Definition: fd.c:903
void InitTemporaryFileAccess(void)
Definition: fd.c:933
void InitLockManagerAccess(void)
Definition: lock.c:501
void pgstat_initialize(void)
Definition: pgstat.c:607
void ReplicationSlotInitialize(void)
Definition: slot.c:224
void smgrinit(void)
Definition: smgr.c:157
PGPROC * MyProc
Definition: proc.c:67
void InitSync(void)
Definition: sync.c:124
void InitXLogInsert(void)
Definition: xloginsert.c:1348

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

Referenced by AutoVacWorkerMain(), AuxiliaryProcessMainCommon(), BackgroundWorkerMain(), BootstrapModeMain(), PostgresMain(), and ReplSlotSyncWorkerMain().

◆ ChangeToDataDir()

void ChangeToDataDir ( void  )

Definition at line 454 of file miscinit.c.

455 {
456  Assert(DataDir);
457 
458  if (chdir(DataDir) < 0)
459  ereport(FATAL,
461  errmsg("could not change directory to \"%s\": %m",
462  DataDir)));
463 }
#define FATAL
Definition: elog.h:41
char * DataDir
Definition: globals.c:70

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

3565 {
3566  if (stack_is_too_deep())
3567  {
3568  ereport(ERROR,
3569  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3570  errmsg("stack depth limit exceeded"),
3571  errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3572  "after ensuring the platform's stack depth limit is adequate.",
3573  max_stack_depth)));
3574  }
3575 }
int errhint(const char *fmt,...)
Definition: elog.c:1317
int errcode(int sqlerrcode)
Definition: elog.c:853
#define ERROR
Definition: elog.h:39
int max_stack_depth
Definition: postgres.c:99
bool stack_is_too_deep(void)
Definition: postgres.c:3578

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

Referenced by _jumbleNode(), AlterTypeRecurse(), apply_scanjoin_target_to_paths(), ATExecAddColumn(), ATExecAlterConstrRecurse(), ATExecDropColumn(), CheckAttributeType(), 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(), eval_const_expressions_mutator(), EventTriggerInvoke(), ExecEndNode(), ExecEvalSubPlan(), ExecInitExprRec(), ExecInitNode(), ExecMakeFunctionResultSet(), ExecProcNodeFirst(), ExecShutdownNode_walker(), execute(), executeAnyItem(), executeBoolItem(), 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(), findDependentObjects(), 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 341 of file miscinit.c.

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

1456 {
1457  CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, "", true, DataDir);
1458 }
static void CreateLockFile(const char *filename, bool amPostmaster, const char *socketDir, bool isDDLock, const char *refName)
Definition: miscinit.c:1150

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

1466 {
1467  char lockfile[MAXPGPATH];
1468 
1469  snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
1470  CreateLockFile(lockfile, amPostmaster, socketDir, false, socketfile);
1471 }
#define MAXPGPATH

References CreateLockFile(), MAXPGPATH, and snprintf.

Referenced by Lock_AF_UNIX().

◆ EstimateClientConnectionInfoSpace()

Size EstimateClientConnectionInfoSpace ( void  )

Definition at line 1027 of file miscinit.c.

1028 {
1029  Size size = 0;
1030 
1032 
1035 
1036  return size;
1037 }
size_t Size
Definition: c.h:596
ClientConnectionInfo MyClientConnectionInfo
Definition: miscinit.c:1010
Size add_size(Size s1, Size s2)
Definition: shmem.c:493
static pg_noinline void Size size
Definition: slab.c:607
const char * authn_id
Definition: libpq-be.h:103

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

Referenced by InitializeParallelDSM().

◆ get_hash_memory_limit()

size_t get_hash_memory_limit ( void  )

Definition at line 3488 of file nodeHash.c.

3489 {
3490  double mem_limit;
3491 
3492  /* Do initial calculation in double arithmetic */
3493  mem_limit = (double) work_mem * hash_mem_multiplier * 1024.0;
3494 
3495  /* Clamp in case it doesn't fit in size_t */
3496  mem_limit = Min(mem_limit, (double) SIZE_MAX);
3497 
3498  return (size_t) mem_limit;
3499 }
#define Min(x, y)
Definition: c.h:995
double hash_mem_multiplier
Definition: globals.c:131
int work_mem
Definition: globals.c:130

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

584 {
586  return AuthenticatedUserId;
587 }
#define OidIsValid(objectId)
Definition: c.h:766
static Oid AuthenticatedUserId
Definition: miscinit.c:494

References Assert, AuthenticatedUserId, and OidIsValid.

Referenced by check_session_authorization(), and InitializeParallelDSM().

◆ GetBackendTypeDesc()

const char* GetBackendTypeDesc ( BackendType  backendType)

Definition at line 263 of file miscinit.c.

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

References B_ARCHIVER, B_AUTOVAC_LAUNCHER, B_AUTOVAC_WORKER, B_BACKEND, B_BG_WORKER, B_BG_WRITER, B_CHECKPOINTER, B_INVALID, B_LOGGER, B_SLOTSYNC_WORKER, B_STANDALONE_BACKEND, B_STARTUP, B_WAL_RECEIVER, B_WAL_SENDER, B_WAL_SUMMARIZER, 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 924 of file miscinit.c.

925 {
926  if (SetRoleIsActive)
927  return OuterUserId;
928  else
929  return InvalidOid;
930 }
static Oid OuterUserId
Definition: miscinit.c:496
static bool SetRoleIsActive
Definition: miscinit.c:506
#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 525 of file miscinit.c.

526 {
528  return OuterUserId;
529 }

References Assert, OidIsValid, and OuterUserId.

Referenced by DropRole(), and RenameRole().

◆ GetSessionUserId()

Oid GetSessionUserId ( void  )

Definition at line 548 of file miscinit.c.

549 {
551  return SessionUserId;
552 }
static Oid SessionUserId
Definition: miscinit.c:495

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

575 {
576  return SystemUser;
577 }
static const char * SystemUser
Definition: miscinit.c:498

References SystemUser.

Referenced by system_user().

◆ GetUserId()

Oid GetUserId ( void  )

Definition at line 514 of file miscinit.c.

515 {
517  return CurrentUserId;
518 }
static Oid CurrentUserId
Definition: miscinit.c:497

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(), ATExecChangeOwner(), ATPrepAlterColumnType(), ATPrepSetTableSpace(), ATSimplePermissions(), bbsink_server_new(), be_lo_unlink(), binary_upgrade_create_empty_extension(), binary_upgrade_logical_slot_has_caught_up(), brin_desummarize_range(), BuildCachedPlan(), BuildDescForRelation(), BuildIndexValueDescription(), calculate_database_size(), calculate_tablespace_size(), call_pltcl_start_proc(), check_enable_rls(), check_search_path(), 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(), fmgr_security_definer(), 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_largeobject_privilege_id(), 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_get_sequence_data(), pg_has_role_id(), pg_has_role_name(), pg_import_system_collations(), pg_prewarm(), pg_sequence_last_value(), pg_sequence_parameters(), pg_signal_backend(), pg_stat_get_wal_receiver(), pg_stat_get_wal_senders(), pg_stat_statements_internal(), pgrowlocks(), pgss_store(), pgstat_get_backend_current_activity(), pltcl_fetch_interp(), postgresBeginDirectModify(), postgresBeginForeignScan(), postgresExecForeignTruncate(), postgresGetForeignRelSize(), postgresImportForeignSchema(), PrepareTempTablespaces(), PrepareTransaction(), PublicationAddTables(), RangeVarCallbackForAlterRelation(), RangeVarCallbackForDropRelation(), RangeVarCallbackForLockTable(), RangeVarCallbackForPolicy(), RangeVarCallbackForReindexIndex(), RangeVarCallbackForRenameRule(), RangeVarCallbackForRenameTrigger(), RangeVarCallbackMaintainsTable(), RangeVarCallbackOwnsRelation(), RangeVarGetAndCheckCreationNamespace(), ReassignOwnedObjects(), recomputeNamespacePath(), REGRESS_exec_check_perms(), REGRESS_object_access_hook(), REGRESS_object_access_hook_str(), REGRESS_utility_command(), ReindexMultipleInternal(), ReindexMultipleTables(), RemoveObjects(), renameatt_check(), RenameDatabase(), RenameRole(), RenameSchema(), RenameTableSpace(), RenameType(), RevalidateCachedQuery(), RI_Initial_Check(), ri_ReportViolation(), select_perl_context(), set_config_option(), set_foreign_rel_properties(), shell_check_detail(), standard_ProcessUtility(), statext_is_compatible_clause(), stats_lock_check_privileges(), superuser(), TargetPrivilegesCheck(), TerminateOtherDBBackends(), transformTableLikeClause(), truncate_check_perms(), user_mapping_ddl_aclcheck(), vacuum_is_permitted_for_relation(), validate_option_array_item(), ValidateJoinEstimator(), ValidateOperatorReference(), and ValidateRestrictionEstimator().

◆ GetUserIdAndContext()

void GetUserIdAndContext ( Oid userid,
bool sec_def_context 
)

Definition at line 684 of file miscinit.c.

685 {
686  *userid = CurrentUserId;
687  *sec_def_context = InLocalUserIdChange();
688 }
bool InLocalUserIdChange(void)
Definition: miscinit.c:653

References CurrentUserId, and InLocalUserIdChange().

◆ GetUserIdAndSecContext()

◆ GetUserNameFromId()

char* GetUserNameFromId ( Oid  roleid,
bool  noerr 
)

Definition at line 980 of file miscinit.c.

981 {
982  HeapTuple tuple;
983  char *result;
984 
985  tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
986  if (!HeapTupleIsValid(tuple))
987  {
988  if (!noerr)
989  ereport(ERROR,
990  (errcode(ERRCODE_UNDEFINED_OBJECT),
991  errmsg("invalid role OID: %u", roleid)));
992  result = NULL;
993  }
994  else
995  {
996  result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
997  ReleaseSysCache(tuple);
998  }
999  return result;
1000 }
#define NameStr(name)
Definition: c.h:737
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
char * pstrdup(const char *in)
Definition: mcxt.c:1696
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:269
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:221

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

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

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

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

◆ InitializeFastPathLocks()

void InitializeFastPathLocks ( void  )

Definition at line 574 of file postinit.c.

575 {
576  /* Should be initialized only once. */
578 
579  /* we need at least one group */
581 
583  {
584  /* stop once we exceed max_locks_per_xact */
586  break;
587 
589  }
590 
592 }
int max_locks_per_xact
Definition: lock.c:53
int FastPathLockGroupsPerBackend
Definition: lock.c:201
#define FP_LOCK_GROUPS_PER_BACKEND_MAX
Definition: proc.h:83
#define FP_LOCK_SLOTS_PER_GROUP
Definition: proc.h:84

References Assert, FastPathLockGroupsPerBackend, FP_LOCK_GROUPS_PER_BACKEND_MAX, FP_LOCK_SLOTS_PER_GROUP, and max_locks_per_xact.

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

◆ InitializeMaxBackends()

void InitializeMaxBackends ( void  )

Definition at line 542 of file postinit.c.

543 {
544  Assert(MaxBackends == 0);
545 
546  /* the extra unit accounts for the autovacuum launcher */
549 
551  ereport(ERROR,
552  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
553  errmsg("too many server processes configured"),
554  errdetail("\"max_connections\" (%d) plus \"autovacuum_max_workers\" (%d) plus \"max_worker_processes\" (%d) plus \"max_wal_senders\" (%d) must be less than %d.",
557  MAX_BACKENDS)));
558 }
int autovacuum_max_workers
Definition: autovacuum.c:118
int MaxConnections
Definition: globals.c:142
int MaxBackends
Definition: globals.c:145
int max_worker_processes
Definition: globals.c:143
#define MAX_BACKENDS
Definition: postmaster.h:92
int max_wal_senders
Definition: walsender.c:121

References Assert, autovacuum_max_workers, ereport, errcode(), errdetail(), errmsg(), 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,
bool  bypass_login_check 
)

Definition at line 733 of file miscinit.c.

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

References AcceptInvalidationMessages(), Assert, AuthenticatedUserId, 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 837 of file miscinit.c.

838 {
839  /*
840  * This function should only be called in single-user mode, in autovacuum
841  * workers, in slot sync worker and in background workers.
842  */
845 
846  /* call only once */
848 
849  AuthenticatedUserId = BOOTSTRAP_SUPERUSERID;
850  SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
851 
852  /*
853  * XXX This should set SetConfigOption("session_authorization"), too.
854  * Since we don't, C code will get NULL, and current_setting() will get an
855  * empty string.
856  */
857  SetConfigOption("is_superuser", "on",
859 }
#define AmAutoVacuumWorkerProcess()
Definition: miscadmin.h:372
#define AmBackgroundWorkerProcess()
Definition: miscadmin.h:373
#define AmLogicalSlotSyncWorkerProcess()
Definition: miscadmin.h:375

References AmAutoVacuumWorkerProcess, AmBackgroundWorkerProcess, AmLogicalSlotSyncWorkerProcess, Assert, AuthenticatedUserId, IsUnderPostmaster, OidIsValid, PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT, SetConfigOption(), and SetSessionUserId().

Referenced by InitPostgres().

◆ InitializeSystemUser()

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

Definition at line 867 of file miscinit.c.

868 {
869  char *system_user;
870 
871  /* call only once */
872  Assert(SystemUser == NULL);
873 
874  /*
875  * InitializeSystemUser should be called only when authn_id is not NULL,
876  * meaning that auth_method is valid.
877  */
878  Assert(authn_id != NULL);
879 
880  system_user = psprintf("%s:%s", auth_method, authn_id);
881 
882  /* Store SystemUser in long-lived storage */
885 }
void pfree(void *pointer)
Definition: mcxt.c:1521
MemoryContext TopMemoryContext
Definition: mcxt.c:149
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1683
Datum system_user(PG_FUNCTION_ARGS)
Definition: miscinit.c:891
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,
bits32  flags,
char *  out_dbname 
)

Definition at line 697 of file postinit.c.

701 {
702  bool bootstrap = IsBootstrapProcessingMode();
703  bool am_superuser;
704  char *fullpath;
705  char dbname[NAMEDATALEN];
706  int nfree = 0;
707 
708  elog(DEBUG3, "InitPostgres");
709 
710  /*
711  * Add my PGPROC struct to the ProcArray.
712  *
713  * Once I have done this, I am visible to other backends!
714  */
716 
717  /*
718  * Initialize my entry in the shared-invalidation manager's array of
719  * per-backend data.
720  */
721  SharedInvalBackendInit(false);
722 
724 
725  /*
726  * Also set up timeout handlers needed for backend operation. We need
727  * these in every case except bootstrap.
728  */
729  if (!bootstrap)
730  {
741  }
742 
743  /*
744  * If this is either a bootstrap process or a standalone backend, start up
745  * the XLOG machinery, and register to have it closed down at exit. In
746  * other cases, the startup process is responsible for starting up the
747  * XLOG machinery, and the checkpointer for closing it down.
748  */
749  if (!IsUnderPostmaster)
750  {
751  /*
752  * We don't yet have an aux-process resource owner, but StartupXLOG
753  * and ShutdownXLOG will need one. Hence, create said resource owner
754  * (and register a callback to clean it up after ShutdownXLOG runs).
755  */
757 
758  StartupXLOG();
759  /* Release (and warn about) any buffer pins leaked in StartupXLOG */
761  /* Reset CurrentResourceOwner to nothing for the moment */
762  CurrentResourceOwner = NULL;
763 
764  /*
765  * Use before_shmem_exit() so that ShutdownXLOG() can rely on DSM
766  * segments etc to work (which in turn is required for pgstats).
767  */
770  }
771 
772  /*
773  * Initialize the relation cache and the system catalog caches. Note that
774  * no catalog access happens here; we only set up the hashtable structure.
775  * We must do this before starting a transaction because transaction abort
776  * would try to touch these hashtables.
777  */
780  InitPlanCache();
781 
782  /* Initialize portal manager */
784 
785  /* Initialize status reporting */
786  pgstat_beinit();
787 
788  /*
789  * Load relcache entries for the shared system catalogs. This must create
790  * at least entries for pg_database and catalogs used for authentication.
791  */
793 
794  /*
795  * Set up process-exit callback to do pre-shutdown cleanup. This is the
796  * one of the first before_shmem_exit callbacks we register; thus, this
797  * will be one the last things we do before low-level modules like the
798  * buffer manager begin to close down. We need to have this in place
799  * before we begin our first transaction --- if we fail during the
800  * initialization transaction, as is entirely possible, we need the
801  * AbortTransaction call to clean up.
802  */
804 
805  /* The autovacuum launcher is done here */
807  {
808  /* report this backend in the PgBackendStatus array */
809  pgstat_bestart();
810 
811  return;
812  }
813 
814  /*
815  * Start a new transaction here before first access to db, and get a
816  * snapshot. We don't have a use for the snapshot itself, but we're
817  * interested in the secondary effect that it sets RecentGlobalXmin. (This
818  * is critical for anything that reads heap pages, because HOT may decide
819  * to prune them even if the process doesn't attempt to modify any
820  * tuples.)
821  *
822  * FIXME: This comment is inaccurate / the code buggy. A snapshot that is
823  * not pushed/active does not reliably prevent HOT pruning (->xmin could
824  * e.g. be cleared when cache invalidations are processed).
825  */
826  if (!bootstrap)
827  {
828  /* statement_timestamp must be set for timeouts to work correctly */
831 
832  /*
833  * transaction_isolation will have been set to the default by the
834  * above. If the default is "serializable", and we are in hot
835  * standby, we will fail if we don't change it to something lower.
836  * Fortunately, "read committed" is plenty good enough.
837  */
839 
840  (void) GetTransactionSnapshot();
841  }
842 
843  /*
844  * Perform client authentication if necessary, then figure out our
845  * postgres user ID, and see if we are a superuser.
846  *
847  * In standalone mode, autovacuum worker processes and slot sync worker
848  * process, we use a fixed ID, otherwise we figure it out from the
849  * authenticated user name.
850  */
852  {
854  am_superuser = true;
855  }
856  else if (!IsUnderPostmaster)
857  {
859  am_superuser = true;
860  if (!ThereIsAtLeastOneRole())
862  (errcode(ERRCODE_UNDEFINED_OBJECT),
863  errmsg("no roles are defined in this database system"),
864  errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
865  username != NULL ? username : "postgres")));
866  }
867  else if (AmBackgroundWorkerProcess())
868  {
869  if (username == NULL && !OidIsValid(useroid))
870  {
872  am_superuser = true;
873  }
874  else
875  {
877  (flags & INIT_PG_OVERRIDE_ROLE_LOGIN) != 0);
878  am_superuser = superuser();
879  }
880  }
881  else
882  {
883  /* normal multiuser case */
884  Assert(MyProcPort != NULL);
886  InitializeSessionUserId(username, useroid, false);
887  /* ensure that auth_method is actually valid, aka authn_id is not NULL */
891  am_superuser = superuser();
892  }
893 
894  /*
895  * Binary upgrades only allowed super-user connections
896  */
897  if (IsBinaryUpgrade && !am_superuser)
898  {
899  ereport(FATAL,
900  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
901  errmsg("must be superuser to connect in binary upgrade mode")));
902  }
903 
904  /*
905  * The last few connection slots are reserved for superusers and roles
906  * with privileges of pg_use_reserved_connections. Replication
907  * connections are drawn from slots reserved with max_wal_senders and are
908  * not limited by max_connections, superuser_reserved_connections, or
909  * reserved_connections.
910  *
911  * Note: At this point, the new backend has already claimed a proc struct,
912  * so we must check whether the number of free slots is strictly less than
913  * the reserved connection limits.
914  */
915  if (!am_superuser && !am_walsender &&
918  {
919  if (nfree < SuperuserReservedConnections)
920  ereport(FATAL,
921  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
922  errmsg("remaining connection slots are reserved for roles with the %s attribute",
923  "SUPERUSER")));
924 
925  if (!has_privs_of_role(GetUserId(), ROLE_PG_USE_RESERVED_CONNECTIONS))
926  ereport(FATAL,
927  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
928  errmsg("remaining connection slots are reserved for roles with privileges of the \"%s\" role",
929  "pg_use_reserved_connections")));
930  }
931 
932  /* Check replication permissions needed for walsender processes. */
933  if (am_walsender)
934  {
935  Assert(!bootstrap);
936 
938  ereport(FATAL,
939  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
940  errmsg("permission denied to start WAL sender"),
941  errdetail("Only roles with the %s attribute may start a WAL sender process.",
942  "REPLICATION")));
943  }
944 
945  /*
946  * If this is a plain walsender only supporting physical replication, we
947  * don't want to connect to any particular database. Just finish the
948  * backend startup by processing any options from the startup packet, and
949  * we're done.
950  */
952  {
953  /* process any options passed in the startup packet */
954  if (MyProcPort != NULL)
955  process_startup_options(MyProcPort, am_superuser);
956 
957  /* Apply PostAuthDelay as soon as we've read all options */
958  if (PostAuthDelay > 0)
959  pg_usleep(PostAuthDelay * 1000000L);
960 
961  /* initialize client encoding */
963 
964  /* report this backend in the PgBackendStatus array */
965  pgstat_bestart();
966 
967  /* close the transaction we started above */
969 
970  return;
971  }
972 
973  /*
974  * Set up the global variables holding database id and default tablespace.
975  * But note we won't actually try to touch the database just yet.
976  *
977  * We take a shortcut in the bootstrap case, otherwise we have to look up
978  * the db's entry in pg_database.
979  */
980  if (bootstrap)
981  {
982  dboid = Template1DbOid;
983  MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
984  }
985  else if (in_dbname != NULL)
986  {
987  HeapTuple tuple;
988  Form_pg_database dbform;
989 
990  tuple = GetDatabaseTuple(in_dbname);
991  if (!HeapTupleIsValid(tuple))
992  ereport(FATAL,
993  (errcode(ERRCODE_UNDEFINED_DATABASE),
994  errmsg("database \"%s\" does not exist", in_dbname)));
995  dbform = (Form_pg_database) GETSTRUCT(tuple);
996  dboid = dbform->oid;
997  }
998  else if (!OidIsValid(dboid))
999  {
1000  /*
1001  * If this is a background worker not bound to any particular
1002  * database, we're done now. Everything that follows only makes sense
1003  * if we are bound to a specific database. We do need to close the
1004  * transaction we started before returning.
1005  */
1006  if (!bootstrap)
1007  {
1008  pgstat_bestart();
1010  }
1011  return;
1012  }
1013 
1014  /*
1015  * Now, take a writer's lock on the database we are trying to connect to.
1016  * If there is a concurrently running DROP DATABASE on that database, this
1017  * will block us until it finishes (and has committed its update of
1018  * pg_database).
1019  *
1020  * Note that the lock is not held long, only until the end of this startup
1021  * transaction. This is OK since we will advertise our use of the
1022  * database in the ProcArray before dropping the lock (in fact, that's the
1023  * next thing to do). Anyone trying a DROP DATABASE after this point will
1024  * see us in the array once they have the lock. Ordering is important for
1025  * this because we don't want to advertise ourselves as being in this
1026  * database until we have the lock; otherwise we create what amounts to a
1027  * deadlock with CountOtherDBBackends().
1028  *
1029  * Note: use of RowExclusiveLock here is reasonable because we envision
1030  * our session as being a concurrent writer of the database. If we had a
1031  * way of declaring a session as being guaranteed-read-only, we could use
1032  * AccessShareLock for such sessions and thereby not conflict against
1033  * CREATE DATABASE.
1034  */
1035  if (!bootstrap)
1036  LockSharedObject(DatabaseRelationId, dboid, 0, RowExclusiveLock);
1037 
1038  /*
1039  * Recheck pg_database to make sure the target database hasn't gone away.
1040  * If there was a concurrent DROP DATABASE, this ensures we will die
1041  * cleanly without creating a mess.
1042  */
1043  if (!bootstrap)
1044  {
1045  HeapTuple tuple;
1046  Form_pg_database datform;
1047 
1048  tuple = GetDatabaseTupleByOid(dboid);
1049  if (HeapTupleIsValid(tuple))
1050  datform = (Form_pg_database) GETSTRUCT(tuple);
1051 
1052  if (!HeapTupleIsValid(tuple) ||
1053  (in_dbname && namestrcmp(&datform->datname, in_dbname)))
1054  {
1055  if (in_dbname)
1056  ereport(FATAL,
1057  (errcode(ERRCODE_UNDEFINED_DATABASE),
1058  errmsg("database \"%s\" does not exist", in_dbname),
1059  errdetail("It seems to have just been dropped or renamed.")));
1060  else
1061  ereport(FATAL,
1062  (errcode(ERRCODE_UNDEFINED_DATABASE),
1063  errmsg("database %u does not exist", dboid)));
1064  }
1065 
1066  strlcpy(dbname, NameStr(datform->datname), sizeof(dbname));
1067 
1068  if (database_is_invalid_form(datform))
1069  {
1070  ereport(FATAL,
1071  errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1072  errmsg("cannot connect to invalid database \"%s\"", dbname),
1073  errhint("Use DROP DATABASE to drop invalid databases."));
1074  }
1075 
1076  MyDatabaseTableSpace = datform->dattablespace;
1077  MyDatabaseHasLoginEventTriggers = datform->dathasloginevt;
1078  /* pass the database name back to the caller */
1079  if (out_dbname)
1080  strcpy(out_dbname, dbname);
1081  }
1082 
1083  /*
1084  * Now that we rechecked, we are certain to be connected to a database and
1085  * thus can set MyDatabaseId.
1086  *
1087  * It is important that MyDatabaseId only be set once we are sure that the
1088  * target database can no longer be concurrently dropped or renamed. For
1089  * example, without this guarantee, pgstat_update_dbstats() could create
1090  * entries for databases that were just dropped in the pgstat shutdown
1091  * callback, which could confuse other code paths like the autovacuum
1092  * scheduler.
1093  */
1094  MyDatabaseId = dboid;
1095 
1096  /*
1097  * Now we can mark our PGPROC entry with the database ID.
1098  *
1099  * We assume this is an atomic store so no lock is needed; though actually
1100  * things would work fine even if it weren't atomic. Anyone searching the
1101  * ProcArray for this database's ID should hold the database lock, so they
1102  * would not be executing concurrently with this store. A process looking
1103  * for another database's ID could in theory see a chance match if it read
1104  * a partially-updated databaseId value; but as long as all such searches
1105  * wait and retry, as in CountOtherDBBackends(), they will certainly see
1106  * the correct value on their next try.
1107  */
1109 
1110  /*
1111  * We established a catalog snapshot while reading pg_authid and/or
1112  * pg_database; but until we have set up MyDatabaseId, we won't react to
1113  * incoming sinval messages for unshared catalogs, so we won't realize it
1114  * if the snapshot has been invalidated. Assume it's no good anymore.
1115  */
1117 
1118  /*
1119  * Now we should be able to access the database directory safely. Verify
1120  * it's there and looks reasonable.
1121  */
1123 
1124  if (!bootstrap)
1125  {
1126  if (access(fullpath, F_OK) == -1)
1127  {
1128  if (errno == ENOENT)
1129  ereport(FATAL,
1130  (errcode(ERRCODE_UNDEFINED_DATABASE),
1131  errmsg("database \"%s\" does not exist",
1132  dbname),
1133  errdetail("The database subdirectory \"%s\" is missing.",
1134  fullpath)));
1135  else
1136  ereport(FATAL,
1138  errmsg("could not access directory \"%s\": %m",
1139  fullpath)));
1140  }
1141 
1142  ValidatePgVersion(fullpath);
1143  }
1144 
1145  SetDatabasePath(fullpath);
1146  pfree(fullpath);
1147 
1148  /*
1149  * It's now possible to do real access to the system catalogs.
1150  *
1151  * Load relcache entries for the system catalogs. This must create at
1152  * least the minimum set of "nailed-in" cache entries.
1153  */
1155 
1156  /* set up ACL framework (so CheckMyDatabase can check permissions) */
1157  initialize_acl();
1158 
1159  /*
1160  * Re-read the pg_database row for our database, check permissions and set
1161  * up database-specific GUC settings. We can't do this until all the
1162  * database-access infrastructure is up. (Also, it wants to know if the
1163  * user is a superuser, so the above stuff has to happen first.)
1164  */
1165  if (!bootstrap)
1166  CheckMyDatabase(dbname, am_superuser,
1167  (flags & INIT_PG_OVERRIDE_ALLOW_CONNS) != 0);
1168 
1169  /*
1170  * Now process any command-line switches and any additional GUC variable
1171  * settings passed in the startup packet. We couldn't do this before
1172  * because we didn't know if client is a superuser.
1173  */
1174  if (MyProcPort != NULL)
1175  process_startup_options(MyProcPort, am_superuser);
1176 
1177  /* Process pg_db_role_setting options */
1179 
1180  /* Apply PostAuthDelay as soon as we've read all options */
1181  if (PostAuthDelay > 0)
1182  pg_usleep(PostAuthDelay * 1000000L);
1183 
1184  /*
1185  * Initialize various default states that can't be set up until we've
1186  * selected the active user and gotten the right GUC settings.
1187  */
1188 
1189  /* set default namespace search path */
1191 
1192  /* initialize client encoding */
1194 
1195  /* Initialize this backend's session state. */
1197 
1198  /*
1199  * If this is an interactive session, load any libraries that should be
1200  * preloaded at backend start. Since those are determined by GUCs, this
1201  * can't happen until GUC settings are complete, but we want it to happen
1202  * during the initial transaction in case anything that requires database
1203  * access needs to be done.
1204  */
1205  if ((flags & INIT_PG_LOAD_SESSION_LIBS) != 0)
1207 
1208  /* report this backend in the PgBackendStatus array */
1209  if (!bootstrap)
1210  pgstat_bestart();
1211 
1212  /* close the transaction we started above */
1213  if (!bootstrap)
1215 }
void initialize_acl(void)
Definition: acl.c:5024
bool has_privs_of_role(Oid member, Oid role)
Definition: acl.c:5268
void pgstat_beinit(void)
void pgstat_bestart(void)
bool database_is_invalid_form(Form_pg_database datform)
Definition: dbcommands.c:3211
#define DEBUG3
Definition: elog.h:28
#define WARNING
Definition: elog.h:36
#define elog(elevel,...)
Definition: elog.h:225
bool MyDatabaseHasLoginEventTriggers
Definition: globals.c:97
bool IsBinaryUpgrade
Definition: globals.c:120
int32 MyCancelKey
Definition: globals.c:52
Oid MyDatabaseTableSpace
Definition: globals.c:95
bool MyCancelKeyValid
Definition: globals.c:51
struct Port * MyProcPort
Definition: globals.c:50
Oid MyDatabaseId
Definition: globals.c:93
const char * hba_authname(UserAuth auth_method)
Definition: hba.c:3065
static char * username
Definition: initdb.c:153
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:337
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1073
#define RowExclusiveLock
Definition: lockdefs.h:38
void InitializeClientEncoding(void)
Definition: mbutils.c:281
#define INIT_PG_LOAD_SESSION_LIBS
Definition: miscadmin.h:473
#define AmAutoVacuumLauncherProcess()
Definition: miscadmin.h:371
#define INIT_PG_OVERRIDE_ROLE_LOGIN
Definition: miscadmin.h:475
#define INIT_PG_OVERRIDE_ALLOW_CONNS
Definition: miscadmin.h:474
void InitializeSessionUserId(const char *rolename, Oid roleid, bool bypass_login_check)
Definition: miscinit.c:733
void InitializeSystemUser(const char *authn_id, const char *auth_method)
Definition: miscinit.c:867
void InitializeSessionUserIdStandalone(void)
Definition: miscinit.c:837
void process_session_preload_libraries(void)
Definition: miscinit.c:1857
Oid GetUserId(void)
Definition: miscinit.c:514
Oid GetSessionUserId(void)
Definition: miscinit.c:548
void SetDatabasePath(const char *path)
Definition: miscinit.c:328
bool has_rolreplication(Oid roleid)
Definition: miscinit.c:711
int namestrcmp(Name name, const char *str)
Definition: name.c:247
void InitializeSearchPath(void)
Definition: namespace.c:4736
#define NAMEDATALEN
FormData_pg_database * Form_pg_database
Definition: pg_database.h:96
void pgstat_before_server_shutdown(int code, Datum arg)
Definition: pgstat.c:532
void InitPlanCache(void)
Definition: plancache.c:155
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
void EnablePortalManager(void)
Definition: portalmem.c:104
int PostAuthDelay
Definition: postgres.c:102
static void ShutdownPostgres(int code, Datum arg)
Definition: postinit.c:1321
static void IdleInTransactionSessionTimeoutHandler(void)
Definition: postinit.c:1378
static void LockTimeoutHandler(void)
Definition: postinit.c:1360
static void IdleStatsUpdateTimeoutHandler(void)
Definition: postinit.c:1394
static void process_settings(Oid databaseid, Oid roleid)
Definition: postinit.c:1287
static void IdleSessionTimeoutHandler(void)
Definition: postinit.c:1386
static void process_startup_options(Port *port, bool am_superuser)
Definition: postinit.c:1222
static void StatementTimeoutHandler(void)
Definition: postinit.c:1338
static void CheckMyDatabase(const char *name, bool am_superuser, bool override_allow_connections)
Definition: postinit.c:313
static bool ThereIsAtLeastOneRole(void)
Definition: postinit.c:1413
static void PerformAuthentication(Port *port)
Definition: postinit.c:190
static void ClientCheckTimeoutHandler(void)
Definition: postinit.c:1402
static HeapTuple GetDatabaseTuple(const char *dbname)
Definition: postinit.c:101
static HeapTuple GetDatabaseTupleByOid(Oid dboid)
Definition: postinit.c:144
static void TransactionTimeoutHandler(void)
Definition: postinit.c:1370
int ReservedConnections
Definition: postmaster.c:213
int SuperuserReservedConnections
Definition: postmaster.c:212
short access
Definition: preproc-type.c:36
void ProcSignalInit(bool cancel_key_valid, int32 cancel_key)
Definition: procsignal.c:166
void RelationCacheInitializePhase3(void)
Definition: relcache.c:4100
void RelationCacheInitialize(void)
Definition: relcache.c:3995
void RelationCacheInitializePhase2(void)
Definition: relcache.c:4041
char * GetDatabasePath(Oid dbOid, Oid spcOid)
Definition: relpath.c:110
void ReleaseAuxProcessResources(bool isCommit)
Definition: resowner.c:1002
ResourceOwner CurrentResourceOwner
Definition: resowner.c:165
void CreateAuxProcessResourceOwner(void)
Definition: resowner.c:982
void InitializeSession(void)
Definition: session.c:54
void pg_usleep(long microsec)
Definition: signal.c:53
void SharedInvalBackendInit(bool sendOnly)
Definition: sinvaladt.c:272
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:216
void InvalidateCatalogSnapshot(void)
Definition: snapmgr.c:422
bool HaveNFreeProcs(int n, int *nfree)
Definition: proc.c:734
void CheckDeadLockAlert(void)
Definition: proc.c:1880
void InitProcessPhase2(void)
Definition: proc.c:535
char * dbname
Definition: streamutil.c:52
UserAuth auth_method
Definition: libpq-be.h:109
Oid databaseId
Definition: proc.h:207
bool superuser(void)
Definition: superuser.c:46
void InitCatalogCache(void)
Definition: syscache.c:110
TimeoutId RegisterTimeout(TimeoutId id, timeout_handler_proc handler)
Definition: timeout.c:505
@ IDLE_SESSION_TIMEOUT
Definition: timeout.h:35
@ 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
@ TRANSACTION_TIMEOUT
Definition: timeout.h:34
@ IDLE_STATS_UPDATE_TIMEOUT
Definition: timeout.h:36
@ CLIENT_CONNECTION_CHECK_TIMEOUT
Definition: timeout.h:37
bool am_walsender
Definition: walsender.c:115
bool am_db_walsender
Definition: walsender.c:118
void StartTransactionCommand(void)
Definition: xact.c:3039
int XactIsoLevel
Definition: xact.c:78
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:913
void CommitTransactionCommand(void)
Definition: xact.c:3137
#define XACT_READ_COMMITTED
Definition: xact.h:37
void StartupXLOG(void)
Definition: xlog.c:5422
void ShutdownXLOG(int code, Datum arg)
Definition: xlog.c:6601

References am_db_walsender, am_walsender, AmAutoVacuumLauncherProcess, AmAutoVacuumWorkerProcess, AmBackgroundWorkerProcess, AmLogicalSlotSyncWorkerProcess, 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(), INIT_PG_LOAD_SESSION_LIBS, INIT_PG_OVERRIDE_ALLOW_CONNS, INIT_PG_OVERRIDE_ROLE_LOGIN, InitCatalogCache(), initialize_acl(), InitializeClientEncoding(), InitializeSearchPath(), InitializeSession(), InitializeSessionUserId(), InitializeSessionUserIdStandalone(), InitializeSystemUser(), InitPlanCache(), InitProcessPhase2(), InvalidateCatalogSnapshot(), IsBinaryUpgrade, IsBootstrapProcessingMode, IsUnderPostmaster, LOCK_TIMEOUT, LockSharedObject(), LockTimeoutHandler(), MyCancelKey, MyCancelKeyValid, MyClientConnectionInfo, MyDatabaseHasLoginEventTriggers, 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(), TRANSACTION_TIMEOUT, TransactionTimeoutHandler(), username, ValidatePgVersion(), WARNING, XACT_READ_COMMITTED, and XactIsoLevel.

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

◆ 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 better to keep the depth
111  * logic the same with and without that build option.
112  */
113  (void) set_stack_base();
114 
116 
117  /*
118  * make sure stderr is in binary mode before anything can possibly be
119  * written to it, in case it's actually the syslogger pipe, so the pipe
120  * chunking protocol isn't disturbed. Non-logpipe data gets translated on
121  * redirection (e.g. via pg_ctl -l) anyway.
122  */
123 #ifdef WIN32
124  _setmode(fileno(stderr), _O_BINARY);
125 #endif
126 
127  /* We don't want the postmaster's proc_exit() handlers */
128  on_exit_reset();
129 
130  /* In EXEC_BACKEND case we will not have inherited BlockSig etc values */
131 #ifdef EXEC_BACKEND
132  pqinitmask();
133 #endif
134 
135  /* Initialize process-local latch support */
139 
140  /*
141  * If possible, make this process a group leader, so that the postmaster
142  * can signal any child processes too. Not all processes will have
143  * children, but for consistency we make all postmaster child processes do
144  * this.
145  */
146 #ifdef HAVE_SETSID
147  if (setsid() < 0)
148  elog(FATAL, "setsid() failed: %m");
149 #endif
150 
151  /*
152  * Every postmaster child process is expected to respond promptly to
153  * SIGQUIT at all times. Therefore we centrally remove SIGQUIT from
154  * BlockSig and install a suitable signal handler. (Client-facing
155  * processes may choose to replace this default choice of handler with
156  * quickdie().) All other blockable signals remain blocked for now.
157  */
159 
160  sigdelset(&BlockSig, SIGQUIT);
161  sigprocmask(SIG_SETMASK, &BlockSig, NULL);
162 
163  /* Request a signal if the postmaster dies, if possible. */
165 
166  /* Don't give the pipe to subprograms that we execute. */
167 #ifndef WIN32
168  if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFD, FD_CLOEXEC) < 0)
169  ereport(FATAL,
171  errmsg_internal("could not set postmaster death monitoring pipe to FD_CLOEXEC mode: %m")));
172 #endif
173 }
void pqinitmask(void)
Definition: pqsignal.c:41
sigset_t BlockSig
Definition: pqsignal.c:23
int errcode_for_socket_access(void)
Definition: elog.c:953
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1157
void SignalHandlerForCrashExit(SIGNAL_ARGS)
Definition: interrupt.c:73
void on_exit_reset(void)
Definition: ipc.c:416
void InitializeLatchWaitSet(void)
Definition: latch.c:346
void InitializeLatchSupport(void)
Definition: latch.c:232
void InitProcessLocalLatch(void)
Definition: miscinit.c:241
void PostmasterDeathSignalInit(void)
Definition: pmsignal.c:446
pqsigfunc pqsignal(int signo, pqsigfunc func)
pg_stack_base_t set_stack_base(void)
Definition: postgres.c:3514
void InitProcessGlobals(void)
Definition: postmaster.c:1899
int postmaster_alive_fds[2]
Definition: postmaster.c:453
#define POSTMASTER_FD_WATCH
Definition: postmaster.h:48
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 postmaster_child_launch().

◆ InitProcessLocalLatch()

void InitProcessLocalLatch ( void  )

Definition at line 241 of file miscinit.c.

242 {
245 }
struct Latch * MyLatch
Definition: globals.c:62
void InitLatch(Latch *latch)
Definition: latch.c:394
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 181 of file miscinit.c.

182 {
184 
186 
187  /*
188  * Start our win32 signal implementation
189  */
190 #ifdef WIN32
192 #endif
193 
195 
196  /* Initialize process-local latch support */
200 
201  /*
202  * For consistency with InitPostmasterChild, initialize signal mask here.
203  * But we don't unblock SIGQUIT or provide a default handler for it.
204  */
205  pqinitmask();
206  sigprocmask(SIG_SETMASK, &BlockSig, NULL);
207 
208  /* Compute paths, no postmaster to inherit from */
209  if (my_exec_path[0] == '\0')
210  {
211  if (find_my_exec(argv0, my_exec_path) < 0)
212  elog(FATAL, "%s: could not locate my own executable path",
213  argv0);
214  }
215 
216  if (pkglib_path[0] == '\0')
218 }
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:160
char pkglib_path[MAXPGPATH]
Definition: globals.c:81
bool IsPostmasterEnvironment
Definition: globals.c:118
char my_exec_path[MAXPGPATH]
Definition: globals.c:80
BackendType MyBackendType
Definition: miscinit.c:63
static char * argv0
Definition: pg_ctl.c:93
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 653 of file miscinit.c.

654 {
656 }
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:311

References SECURITY_LOCAL_USERID_CHANGE, and SecurityRestrictionContext.

Referenced by GetUserIdAndContext(), and set_config_with_handle().

◆ InNoForceRLSOperation()

bool InNoForceRLSOperation ( void  )

Definition at line 671 of file miscinit.c.

672 {
674 }
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:313

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

1881 {
1882 #ifdef ENABLE_NLS
1883  if (my_exec_path[0] != '\0')
1884  {
1885  char locale_path[MAXPGPATH];
1886 
1887  get_locale_path(my_exec_path, locale_path);
1888  bindtextdomain(domain, locale_path);
1889  pg_bind_textdomain_codeset(domain);
1890  }
1891 #endif
1892 }
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 484 of file postinit.c.

485 {
486  StringInfoData s;
487 
488  initStringInfo(&s);
489 
490  while (*optstr)
491  {
492  bool last_was_escape = false;
493 
494  resetStringInfo(&s);
495 
496  /* skip over leading space */
497  while (isspace((unsigned char) *optstr))
498  optstr++;
499 
500  if (*optstr == '\0')
501  break;
502 
503  /*
504  * Parse a single option, stopping at the first space, unless it's
505  * escaped.
506  */
507  while (*optstr)
508  {
509  if (isspace((unsigned char) *optstr) && !last_was_escape)
510  break;
511 
512  if (!last_was_escape && *optstr == '\\')
513  last_was_escape = true;
514  else
515  {
516  last_was_escape = false;
517  appendStringInfoChar(&s, *optstr);
518  }
519 
520  optstr++;
521  }
522 
523  /* now store the option in the next argv[] position */
524  argv[(*argcp)++] = pstrdup(s.data);
525  }
526 
527  pfree(s.data);
528 }
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:78
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:194
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 441 of file utility.c.

442 {
443  if (RecoveryInProgress())
444  ereport(ERROR,
445  (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
446  /* translator: %s is name of a SQL command, eg CREATE */
447  errmsg("cannot execute %s during recovery",
448  cmdname)));
449 }
bool RecoveryInProgress(void)
Definition: xlog.c:6333

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 422 of file utility.c.

423 {
424  if (IsInParallelMode())
425  ereport(ERROR,
426  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
427  /* translator: %s is name of a SQL command, eg CREATE */
428  errmsg("cannot execute %s during a parallel operation",
429  cmdname)));
430 }
bool IsInParallelMode(void)
Definition: xact.c:1088

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 404 of file utility.c.

405 {
406  if (XactReadOnly)
407  ereport(ERROR,
408  (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
409  /* translator: %s is name of a SQL command, eg CREATE */
410  errmsg("cannot execute %s in a read-only transaction",
411  cmdname)));
412 }
bool XactReadOnly
Definition: xact.c:81

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

1858 {
1860  "session_preload_libraries",
1861  false);
1863  "local_preload_libraries",
1864  true);
1865 }
char * session_preload_libraries_string
Definition: miscinit.c:1773
char * local_preload_libraries_string
Definition: miscinit.c:1775
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1791

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

1844 {
1847  "shared_preload_libraries",
1848  false);
1851 }
bool process_shared_preload_libraries_done
Definition: miscinit.c:1779
char * shared_preload_libraries_string
Definition: miscinit.c:1774
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1778

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

1872 {
1874  if (shmem_request_hook)
1877 }
bool process_shmem_requests_in_progress
Definition: miscinit.c:1782
shmem_request_hook_type shmem_request_hook
Definition: miscinit.c:1781

References process_shmem_requests_in_progress, and shmem_request_hook.

Referenced by PostgresSingleUserMain(), and PostmasterMain().

◆ ProcessInterrupts()

void ProcessInterrupts ( void  )

Definition at line 3277 of file postgres.c.

3278 {
3279  /* OK to accept any interrupts now? */
3280  if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
3281  return;
3282  InterruptPending = false;
3283 
3284  if (ProcDiePending)
3285  {
3286  ProcDiePending = false;
3287  QueryCancelPending = false; /* ProcDie trumps QueryCancel */
3288  LockErrorCleanup();
3289  /* As in quickdie, don't risk sending to client during auth */
3293  ereport(FATAL,
3294  (errcode(ERRCODE_QUERY_CANCELED),
3295  errmsg("canceling authentication due to timeout")));
3296  else if (AmAutoVacuumWorkerProcess())
3297  ereport(FATAL,
3298  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3299  errmsg("terminating autovacuum process due to administrator command")));
3300  else if (IsLogicalWorker())
3301  ereport(FATAL,
3302  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3303  errmsg("terminating logical replication worker due to administrator command")));
3304  else if (IsLogicalLauncher())
3305  {
3306  ereport(DEBUG1,
3307  (errmsg_internal("logical replication launcher shutting down")));
3308 
3309  /*
3310  * The logical replication launcher can be stopped at any time.
3311  * Use exit status 1 so the background worker is restarted.
3312  */
3313  proc_exit(1);
3314  }
3315  else if (AmBackgroundWorkerProcess())
3316  ereport(FATAL,
3317  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3318  errmsg("terminating background worker \"%s\" due to administrator command",
3320  else
3321  ereport(FATAL,
3322  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3323  errmsg("terminating connection due to administrator command")));
3324  }
3325 
3327  {
3329 
3330  /*
3331  * Check for lost connection and re-arm, if still configured, but not
3332  * if we've arrived back at DoingCommandRead state. We don't want to
3333  * wake up idle sessions, and they already know how to detect lost
3334  * connections.
3335  */
3337  {
3338  if (!pq_check_connection())
3339  ClientConnectionLost = true;
3340  else
3343  }
3344  }
3345 
3347  {
3348  QueryCancelPending = false; /* lost connection trumps QueryCancel */
3349  LockErrorCleanup();
3350  /* don't send to client, we already know the connection to be dead. */
3352  ereport(FATAL,
3353  (errcode(ERRCODE_CONNECTION_FAILURE),
3354  errmsg("connection to client lost")));
3355  }
3356 
3357  /*
3358  * Don't allow query cancel interrupts while reading input from the
3359  * client, because we might lose sync in the FE/BE protocol. (Die
3360  * interrupts are OK, because we won't read any further messages from the
3361  * client in that case.)
3362  *
3363  * See similar logic in ProcessRecoveryConflictInterrupts().
3364  */
3366  {
3367  /*
3368  * Re-arm InterruptPending so that we process the cancel request as
3369  * soon as we're done reading the message. (XXX this is seriously
3370  * ugly: it complicates INTERRUPTS_CAN_BE_PROCESSED(), and it means we
3371  * can't use that macro directly as the initial test in this function,
3372  * meaning that this code also creates opportunities for other bugs to
3373  * appear.)
3374  */
3375  InterruptPending = true;
3376  }
3377  else if (QueryCancelPending)
3378  {
3379  bool lock_timeout_occurred;
3380  bool stmt_timeout_occurred;
3381 
3382  QueryCancelPending = false;
3383 
3384  /*
3385  * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
3386  * need to clear both, so always fetch both.
3387  */
3388  lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
3389  stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
3390 
3391  /*
3392  * If both were set, we want to report whichever timeout completed
3393  * earlier; this ensures consistent behavior if the machine is slow
3394  * enough that the second timeout triggers before we get here. A tie
3395  * is arbitrarily broken in favor of reporting a lock timeout.
3396  */
3397  if (lock_timeout_occurred && stmt_timeout_occurred &&
3399  lock_timeout_occurred = false; /* report stmt timeout */
3400 
3401  if (lock_timeout_occurred)
3402  {
3403  LockErrorCleanup();
3404  ereport(ERROR,
3405  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
3406  errmsg("canceling statement due to lock timeout")));
3407  }
3408  if (stmt_timeout_occurred)
3409  {
3410  LockErrorCleanup();
3411  ereport(ERROR,
3412  (errcode(ERRCODE_QUERY_CANCELED),
3413  errmsg("canceling statement due to statement timeout")));
3414  }
3416  {
3417  LockErrorCleanup();
3418  ereport(ERROR,
3419  (errcode(ERRCODE_QUERY_CANCELED),
3420  errmsg("canceling autovacuum task")));
3421  }
3422 
3423  /*
3424  * If we are reading a command from the client, just ignore the cancel
3425  * request --- sending an extra error message won't accomplish
3426  * anything. Otherwise, go ahead and throw the error.
3427  */
3428  if (!DoingCommandRead)
3429  {
3430  LockErrorCleanup();
3431  ereport(ERROR,
3432  (errcode(ERRCODE_QUERY_CANCELED),
3433  errmsg("canceling statement due to user request")));
3434  }
3435  }
3436 
3439 
3441  {
3442  /*
3443  * If the GUC has been reset to zero, ignore the signal. This is
3444  * important because the GUC update itself won't disable any pending
3445  * interrupt. We need to unset the flag before the injection point,
3446  * otherwise we could loop in interrupts checking.
3447  */
3450  {
3451  INJECTION_POINT("idle-in-transaction-session-timeout");
3452  ereport(FATAL,
3453  (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
3454  errmsg("terminating connection due to idle-in-transaction timeout")));
3455  }
3456  }
3457 
3459  {
3460  /* As above, ignore the signal if the GUC has been reset to zero. */
3461  TransactionTimeoutPending = false;
3462  if (TransactionTimeout > 0)
3463  {
3464  INJECTION_POINT("transaction-timeout");
3465  ereport(FATAL,
3466  (errcode(ERRCODE_TRANSACTION_TIMEOUT),
3467  errmsg("terminating connection due to transaction timeout")));
3468  }
3469  }
3470 
3472  {
3473  /* As above, ignore the signal if the GUC has been reset to zero. */
3474  IdleSessionTimeoutPending = false;
3475  if (IdleSessionTimeout > 0)
3476  {
3477  INJECTION_POINT("idle-session-timeout");
3478  ereport(FATAL,
3479  (errcode(ERRCODE_IDLE_SESSION_TIMEOUT),
3480  errmsg("terminating connection due to idle-session timeout")));
3481  }
3482  }
3483 
3484  /*
3485  * If there are pending stats updates and we currently are truly idle
3486  * (matching the conditions in PostgresMain(), report stats now.
3487  */
3490  {
3492  pgstat_report_stat(true);
3493  }
3494 
3497 
3500 
3503 
3506 }
volatile sig_atomic_t ParallelApplyMessagePending
void HandleParallelApplyMessages(void)
void HandleParallelMessages(void)
Definition: parallel.c:1027
volatile sig_atomic_t ParallelMessagePending
Definition: parallel.c:115
bool IsLogicalWorker(void)
Definition: worker.c:4843
@ DestRemote
Definition: dest.h:89
@ DestNone
Definition: dest.h:87
#define DEBUG1
Definition: elog.h:30
volatile sig_atomic_t IdleStatsUpdateTimeoutPending
Definition: globals.c:41
volatile sig_atomic_t LogMemoryContextPending
Definition: globals.c:40
volatile sig_atomic_t ProcSignalBarrierPending
Definition: globals.c:39
volatile sig_atomic_t InterruptPending
Definition: globals.c:31
volatile sig_atomic_t IdleSessionTimeoutPending
Definition: globals.c:38
volatile uint32 QueryCancelHoldoffCount
Definition: globals.c:43
volatile sig_atomic_t IdleInTransactionSessionTimeoutPending
Definition: globals.c:36
volatile uint32 InterruptHoldoffCount
Definition: globals.c:42
volatile sig_atomic_t TransactionTimeoutPending
Definition: globals.c:37
volatile sig_atomic_t ClientConnectionLost
Definition: globals.c:35
volatile uint32 CritSectionCount
Definition: globals.c:44
volatile sig_atomic_t QueryCancelPending
Definition: globals.c:32
volatile sig_atomic_t ProcDiePending
Definition: globals.c:33
volatile sig_atomic_t CheckClientConnectionPending
Definition: globals.c:34
#define INJECTION_POINT(name)
void proc_exit(int code)
Definition: ipc.c:104
bool IsLogicalLauncher(void)
Definition: launcher.c:1249
void ProcessLogMemoryContextInterrupt(void)
Definition: mcxt.c:1289
long pgstat_report_stat(bool force)
Definition: pgstat.c:660
int client_connection_check_interval
Definition: postgres.c:105
CommandDest whereToSendOutput
Definition: postgres.c:91
static volatile sig_atomic_t RecoveryConflictPending
Definition: postgres.c:170
static bool DoingCommandRead
Definition: postgres.c:148
static void ProcessRecoveryConflictInterrupts(void)
Definition: postgres.c:3238
bool ClientAuthInProgress
Definition: postmaster.c:346
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:181
bool pq_check_connection(void)
Definition: pqcomm.c:2054
void ProcessProcSignalBarrier(void)
Definition: procsignal.c:496
int IdleSessionTimeout
Definition: proc.c:63
int IdleInTransactionSessionTimeout
Definition: proc.c:61
int TransactionTimeout
Definition: proc.c:62
void LockErrorCleanup(void)
Definition: proc.c:777
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:92
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:560
TimestampTz get_timeout_finish_time(TimeoutId id)
Definition: timeout.c:827
bool get_timeout_indicator(TimeoutId id, bool reset_indicator)
Definition: timeout.c:793
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4982

References AmAutoVacuumWorkerProcess, AmBackgroundWorkerProcess, 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, INJECTION_POINT, InterruptHoldoffCount, InterruptPending, 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, TransactionTimeout, TransactionTimeoutPending, and whereToSendOutput.

Referenced by die().

◆ RecheckDataDirLockFile()

bool RecheckDataDirLockFile ( void  )

Definition at line 1638 of file miscinit.c.

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

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

3548 {
3549  stack_base_ptr = base;
3550 }
static char * stack_base_ptr
Definition: postgres.c:135

References stack_base_ptr.

◆ RestoreClientConnectionInfo()

void RestoreClientConnectionInfo ( char *  conninfo)

Definition at line 1075 of file miscinit.c.

1076 {
1077  SerializedClientConnectionInfo serialized;
1078 
1079  memcpy(&serialized, conninfo, sizeof(serialized));
1080 
1081  /* Copy the fields back into place */
1084 
1085  if (serialized.authn_id_len >= 0)
1086  {
1087  char *authn_id;
1088 
1089  authn_id = conninfo + sizeof(serialized);
1091  authn_id);
1092  }
1093 }

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

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

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

3515 {
3516 #ifndef HAVE__BUILTIN_FRAME_ADDRESS
3517  char stack_base;
3518 #endif
3519  pg_stack_base_t old;
3520 
3521  old = stack_base_ptr;
3522 
3523  /*
3524  * Set up reference point for stack depth checking. On recent gcc we use
3525  * __builtin_frame_address() to avoid a warning about storing a local
3526  * variable's address in a long-lived variable.
3527  */
3528 #ifdef HAVE__BUILTIN_FRAME_ADDRESS
3529  stack_base_ptr = __builtin_frame_address(0);
3530 #else
3531  stack_base_ptr = &stack_base;
3532 #endif
3533 
3534  return old;
3535 }
char * pg_stack_base_t
Definition: miscadmin.h:293

References stack_base_ptr.

Referenced by InitPostmasterChild(), and PostmasterMain().

◆ SetCurrentRoleId()

void SetCurrentRoleId ( Oid  roleid,
bool  is_superuser 
)

Definition at line 945 of file miscinit.c.

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

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

329 {
330  /* This should happen only once per process */
333 }
char * DatabasePath
Definition: globals.c:103

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

Referenced by InitPostgres().

◆ SetDataDir()

void SetDataDir ( const char *  dir)

Definition at line 434 of file miscinit.c.

435 {
436  char *new;
437 
438  Assert(dir);
439 
440  /* If presented path is relative, convert to absolute */
441  new = make_absolute_path(dir);
442 
443  free(DataDir);
444  DataDir = new;
445 }
#define free(a)
Definition: header.h:65
char * make_absolute_path(const char *path)
Definition: path.c:730

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

Referenced by SelectConfigFiles().

◆ SetSessionAuthorization()

void SetSessionAuthorization ( Oid  userid,
bool  is_superuser 
)

Definition at line 908 of file miscinit.c.

909 {
911 
912  SetConfigOption("is_superuser",
913  is_superuser ? "on" : "off",
915 }

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

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

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

3579 {
3580  char stack_top_loc;
3581  long stack_depth;
3582 
3583  /*
3584  * Compute distance from reference point to my local variables
3585  */
3586  stack_depth = (long) (stack_base_ptr - &stack_top_loc);
3587 
3588  /*
3589  * Take abs value, since stacks grow up on some machines, down on others
3590  */
3591  if (stack_depth < 0)
3592  stack_depth = -stack_depth;
3593 
3594  /*
3595  * Trouble?
3596  *
3597  * The test on stack_base_ptr prevents us from erroring out if called
3598  * during process setup or in a non-backend process. Logically it should
3599  * be done first, but putting it here avoids wasting cycles during normal
3600  * cases.
3601  */
3602  if (stack_depth > max_stack_depth_bytes &&
3603  stack_base_ptr != NULL)
3604  return true;
3605 
3606  return false;
3607 }
static long max_stack_depth_bytes
Definition: postgres.c:129

References max_stack_depth_bytes, and stack_base_ptr.

Referenced by check_stack_depth(), MemoryContextStatsInternal(), rstacktoodeep(), and ShowTransactionStateRec().

◆ 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_buffercache_evict(), pg_import_system_collations(), pg_nextoid(), pg_relpages(), pg_relpagesbyid(), 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(), 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:1516
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 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(), check_conn_params(), check_object_ownership(), check_role_grantor(), check_role_membership_authorization(), check_session_authorization(), CreateRole(), CreateSubscription(), DropSubscription(), emit_audit_message(), GetSubscription(), has_bypassrls_privilege(), has_createrole_privilege(), has_privs_of_role(), has_rolreplication(), is_admin_of_role(), is_member_of_role(), LockGXact(), member_can_set_role(), object_aclmask_ext(), object_ownercheck(), pg_class_aclmask_ext(), pg_largeobject_aclmask_snapshot(), pg_namespace_aclmask_ext(), pg_parameter_acl_aclmask(), pg_parameter_aclmask(), pg_signal_backend(), pg_type_aclmask_ext(), pgfdw_security_check(), REGRESS_exec_check_perms(), REGRESS_object_access_hook(), REGRESS_object_access_hook_str(), REGRESS_utility_command(), select_best_grantor(), superuser(), and TerminateOtherDBBackends().

◆ SwitchBackToLocalLatch()

void SwitchBackToLocalLatch ( void  )

Definition at line 248 of file miscinit.c.

249 {
251  Assert(MyProc != NULL && MyLatch == &MyProc->procLatch);
252 
254 
255  if (FeBeWaitSet)
257  MyLatch);
258 
259  SetLatch(MyLatch);
260 }
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:1049
void SetLatch(Latch *latch)
Definition: latch.c:632
#define WL_LATCH_SET
Definition: latch.h:127
#define FeBeWaitSetLatchPos
Definition: libpq.h:64
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:166
Latch procLatch
Definition: proc.h:169

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

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

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

1483 {
1484  ListCell *l;
1485 
1486  foreach(l, lock_files)
1487  {
1488  char *socketLockFile = (char *) lfirst(l);
1489 
1490  /* No need to touch the data directory lock file, we trust */
1491  if (strcmp(socketLockFile, DIRECTORY_LOCK_FILE) == 0)
1492  continue;
1493 
1494  /* we just ignore any error here */
1495  (void) utime(socketLockFile, NULL);
1496  }
1497 }
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().

◆ ValidatePgVersion()

void ValidatePgVersion ( const char *  path)

Definition at line 1710 of file miscinit.c.

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

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 34 of file globals.c.

Referenced by ClientCheckTimeoutHandler(), and ProcessInterrupts().

◆ ClientConnectionLost

PGDLLIMPORT volatile sig_atomic_t ClientConnectionLost
extern

Definition at line 35 of file globals.c.

Referenced by internal_flush_buffer(), and ProcessInterrupts().

◆ commit_timestamp_buffers

PGDLLIMPORT int commit_timestamp_buffers
extern

Definition at line 160 of file globals.c.

Referenced by CommitTsShmemBuffers(), and CommitTsShmemInit().

◆ CritSectionCount

◆ data_directory_mode

PGDLLIMPORT int data_directory_mode
extern

Definition at line 76 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 122 of file globals.c.

Referenced by BeginInternalSubTransaction(), errstart(), and HandleCheckpointerInterrupts().

◆ hash_mem_multiplier

PGDLLIMPORT double hash_mem_multiplier
extern

Definition at line 131 of file globals.c.

Referenced by get_hash_memory_limit().

◆ IdleInTransactionSessionTimeoutPending

PGDLLIMPORT volatile sig_atomic_t IdleInTransactionSessionTimeoutPending
extern

Definition at line 36 of file globals.c.

Referenced by IdleInTransactionSessionTimeoutHandler(), and ProcessInterrupts().

◆ IdleSessionTimeoutPending

PGDLLIMPORT volatile sig_atomic_t IdleSessionTimeoutPending
extern

Definition at line 38 of file globals.c.

Referenced by IdleSessionTimeoutHandler(), and ProcessInterrupts().

◆ IdleStatsUpdateTimeoutPending

PGDLLIMPORT volatile sig_atomic_t IdleStatsUpdateTimeoutPending
extern

Definition at line 41 of file globals.c.

Referenced by IdleStatsUpdateTimeoutHandler(), and ProcessInterrupts().

◆ IgnoreSystemIndexes

◆ InterruptHoldoffCount

◆ InterruptPending

◆ IntervalStyle

PGDLLIMPORT int IntervalStyle
extern

◆ IsBinaryUpgrade

◆ IsPostmasterEnvironment

◆ IsUnderPostmaster

PGDLLIMPORT bool IsUnderPostmaster
extern

Definition at line 119 of file globals.c.

Referenced by _PG_init(), AdvanceNextFullTransactionIdPastXid(), AutoVacuumShmemInit(), AuxiliaryProcessMainCommon(), BackgroundWorkerShmemInit(), bootstrap_signals(), BootstrapModeMain(), BTreeShmemInit(), CheckMyDatabase(), CheckRecoveryConsistency(), CommitTsShmemInit(), createdb(), CreateLWLocks(), CreateOrAttachShmemStructs(), 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(), EventTriggerOnLogin(), EventTriggerSQLDrop(), EventTriggerTableRewrite(), ForwardSyncRequest(), get_slru_entry(), GetNewMultiXactId(), GetNewTransactionId(), GetQuitSignalReason(), HandleStartupProcInterrupts(), init_ps_display(), InitAuxiliaryProcess(), InitializeLatchSupport(), InitializeLatchWaitSet(), InitializeSessionUserId(), InitializeSessionUserIdStandalone(), InitPostgres(), InitPostmasterChild(), InitProcess(), InitSync(), InjectionPointShmemInit(), LWLockAcquire(), MaintainLatestCompletedXidRecovery(), MultiXactShmemInit(), parallel_vacuum_compute_workers(), PerformRecoveryXLogAction(), PerformWalRecovery(), PGSemaphoreCreate(), PGSharedMemoryNoReAttach(), PGSharedMemoryReAttach(), pgss_shmem_startup(), pgstat_fetch_entry(), pgstat_read_statsfile(), pgstat_report_autovac(), pgstat_report_recovery_conflict(), pgstat_shutdown_hook(), pgstat_wal_flush_cb(), pgstat_write_statsfile(), plan_create_index_workers(), PostgresMain(), PostgresSingleUserMain(), postmaster_child_launch(), PredicateLockShmemInit(), process_postgres_switches(), process_settings(), ProcessConfigFileInternal(), readRecoverySignalFile(), RegisterBackgroundWorker(), RegisterDynamicBackgroundWorker(), ReplicationSlotAcquire(), SendPostmasterSignal(), SerialInit(), set_config_sourcefile(), set_config_with_handle(), SetMultiXactIdLimit(), SetTransactionIdLimit(), ShmemInitStruct(), SimpleLruInit(), standard_planner(), start_xact_command(), StatsShmemInit(), superuser_arg(), SyncScanShmemInit(), TwoPhaseShmemInit(), vacuum_delay_point(), VarsupShmemInit(), verify_dictoptions(), WaitLatch(), WaitLatchOrSocket(), XLogArchiveNotify(), XLogPageRead(), XLogPrefetchIncrement(), XLogRecGetFullXid(), and XLogWrite().

◆ local_preload_libraries_string

PGDLLIMPORT char* local_preload_libraries_string
extern

Definition at line 1775 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 133 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 144 of file globals.c.

Referenced by RegisterDynamicBackgroundWorker().

◆ max_worker_processes

◆ MaxBackends

◆ MaxConnections

◆ Mode

Definition at line 61 of file miscinit.c.

◆ multixact_member_buffers

PGDLLIMPORT int multixact_member_buffers
extern

Definition at line 161 of file globals.c.

Referenced by MultiXactShmemInit(), and MultiXactShmemSize().

◆ multixact_offset_buffers

PGDLLIMPORT int multixact_offset_buffers
extern

Definition at line 162 of file globals.c.

Referenced by MultiXactShmemInit(), and MultiXactShmemSize().

◆ my_exec_path

◆ MyBackendType

◆ MyCancelKey

PGDLLIMPORT int32 MyCancelKey
extern

Definition at line 52 of file globals.c.

Referenced by InitPostgres(), and PostgresMain().

◆ MyCancelKeyValid

PGDLLIMPORT bool MyCancelKeyValid
extern

Definition at line 51 of file globals.c.

Referenced by InitPostgres(), and PostgresMain().

◆ MyDatabaseHasLoginEventTriggers

PGDLLIMPORT bool MyDatabaseHasLoginEventTriggers
extern

Definition at line 97 of file globals.c.

Referenced by EventTriggerOnLogin(), and InitPostgres().

◆ MyDatabaseId

PGDLLIMPORT Oid MyDatabaseId
extern

Definition at line 93 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(), ConditionalLockDatabaseObject(), CreateDecodingContext(), CreateInitDecodingContext(), CreatePublication(), CreateSchemaCommand(), CreateSubscription(), current_database(), database_to_xml_internal(), DeconstructQualifiedName(), do_analyze_rel(), do_autovacuum(), dropdb(), DropSubscription(), EventTriggerOnLogin(), Exec_ListenPreCommit(), exec_object_restorecon(), exec_replication_command(), ExecuteTruncateGuts(), ExpandColumnRefStar(), ExportSnapshot(), extension_is_trusted(), find_funcstat_entry(), find_tabstat_entry(), get_subscription_oid(), GetCurrentVirtualXIDs(), GetNewRelFileNumber(), GetRunningTransactionData(), heap_vacuum_rel(), IdentifySystem(), ImportSnapshot(), init_database_collation(), 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_ext(), 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(), read_stream_begin_impl(), ReindexMultipleTables(), RelationInitLockInfo(), RelationInitPhysicalAddr(), RelationMapFinishBootstrap(), RenameDatabase(), RenameSchema(), ReplicationSlotCreate(), roles_is_member_of(), ScanPgRelation(), SearchSysCacheLocked1(), sepgsql_schema_post_create(), SetDatabaseHasLoginEventTriggers(), SetLocktagRelationOid(), shdepDropOwned(), shdepReassignOwned(), SignalBackends(), stats_lock_check_privileges(), transformColumnRef(), UnlockApplyTransactionForSession(), UnlockDatabaseObject(), UpdateLogicalMappings(), vac_truncate_clog(), vac_update_datfrozenxid(), vacuum_is_permitted_for_relation(), XactLogAbortRecord(), and XactLogCommitRecord().

◆ MyDatabaseTableSpace

◆ MyLatch

PGDLLIMPORT struct Latch* MyLatch
extern

Definition at line 62 of file globals.c.

Referenced by addLSNWaiter(), ApplyLauncherMain(), autoprewarm_main(), avl_sigusr2_handler(), BackgroundWriterMain(), 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_connect(), libpqrcv_PQgetResult(), libpqsrv_cancel(), libpqsrv_connect_internal(), libpqsrv_get_result(), 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(), pq_check_connection(), pq_init(), ProcessClientReadInterrupt(), ProcessClientWriteInterrupt(), ProcessPendingWrites(), procsignal_sigusr1_handler(), ProcSleep(), ProcWaitForSignal(), ReqCheckpointHandler(), secure_read(), secure_write(), ServerLoop(), shm_mq_receive_bytes(), shm_mq_send_bytes(), shm_mq_wait_internal(), ShutDownSlotSync(), SignalHandlerForConfigReload(), SignalHandlerForShutdownRequest(), sigUsr1Handler(), StatementCancelHandler(), summarizer_wait_for_wal(), SwitchBackToLocalLatch(), SwitchToSharedLatch(), SyncRepWaitForLSN(), SysLoggerMain(), test_shm_mq_pipelined(), throttle(), TransactionTimeoutHandler(), wait_for_relation_state_change(), wait_for_slot_activity(), wait_for_worker_state_change(), wait_for_workers_to_become_ready(), WaitForBackgroundWorkerShutdown(), WaitForBackgroundWorkerStartup(), WaitForLSNReplay(), WaitForParallelWorkersToAttach(), WaitForParallelWorkersToFinish(), WaitForReplicationWorkerAttach(), WalRcvWaitForStartPosition(), WalReceiverMain(), WalSndLastCycleHandler(), WalSndLoop(), WalSndWaitForWal(), WalWriterMain(), and worker_spi_main().

◆ MyPMChildSlot

◆ MyProcPid

PGDLLIMPORT int MyProcPid
extern

Definition at line 46 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(), basic_archive_file(), CheckpointerMain(), CleanupProcSignalState(), DisownLatch(), Exec_ListenPreCommit(), Exec_UnlistenAllCommit(), Exec_UnlistenCommit(), ExportSnapshot(), FileSetInit(), get_backend_type_for_log(), GetSerializableTransactionSnapshotInt(), HandleWalSndInitStopping(), InitAuxiliaryProcess(), initialize_prng(), InitializeLatchSupport(), InitializeParallelDSM(), InitLatch(), InitPostmasterDeathWatchHandle(), InitProcess(), InitProcessGlobals(), InitWalSenderSlot(), injection_point_allowed(), injection_points_attach(), InvalidatePossiblyObsoleteSlot(), IsLogicalLauncher(), LaunchParallelWorkers(), llvm_compile_module(), LockTimeoutHandler(), log_status_format(), logicalrep_worker_launch(), ModifyWaitEvent(), OpenTemporaryFileInTablespace(), OwnLatch(), pg_backend_pid(), pgstat_bestart(), PostgresMain(), PostmasterMain(), proc_exit(), process_pgfdw_appname(), ProcessLogMemoryContextInterrupt(), ProcSignalInit(), ProcSleep(), ReplicationOriginExitCleanup(), ReplicationSlotAcquire(), ReplicationSlotCleanup(), ReplicationSlotCreate(), ReplicationSlotsDropDBSlots(), replorigin_session_setup(), ReplSlotSyncWorkerMain(), 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 141 of file globals.c.

◆ notify_buffers

PGDLLIMPORT int notify_buffers
extern

Definition at line 163 of file globals.c.

Referenced by AsyncShmemInit(), and AsyncShmemSize().

◆ OutputFileName

PGDLLIMPORT char OutputFileName[]
extern

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

◆ process_shmem_requests_in_progress

PGDLLIMPORT bool process_shmem_requests_in_progress
extern

◆ ProcSignalBarrierPending

◆ QueryCancelHoldoffCount

PGDLLIMPORT volatile uint32 QueryCancelHoldoffCount
extern

Definition at line 43 of file globals.c.

Referenced by errfinish(), ProcessInterrupts(), and ProcessRecoveryConflictInterrupt().

◆ QueryCancelPending

PGDLLIMPORT volatile sig_atomic_t QueryCancelPending
extern

◆ serializable_buffers

PGDLLIMPORT int serializable_buffers
extern

Definition at line 164 of file globals.c.

Referenced by PredicateLockShmemSize(), and SerialInit().

◆ session_preload_libraries_string

PGDLLIMPORT char* session_preload_libraries_string
extern

Definition at line 1773 of file miscinit.c.

Referenced by process_session_preload_libraries().

◆ shared_preload_libraries_string

PGDLLIMPORT char* shared_preload_libraries_string
extern

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

Referenced by _PG_init(), and process_shmem_requests().

◆ subtransaction_buffers

PGDLLIMPORT int subtransaction_buffers
extern

Definition at line 165 of file globals.c.

Referenced by SUBTRANSShmemBuffers(), and SUBTRANSShmemInit().

◆ transaction_buffers

PGDLLIMPORT int transaction_buffers
extern

Definition at line 166 of file globals.c.

Referenced by CLOGShmemBuffers(), and CLOGShmemInit().

◆ TransactionTimeoutPending

PGDLLIMPORT volatile sig_atomic_t TransactionTimeoutPending
extern

Definition at line 37 of file globals.c.

Referenced by ProcessInterrupts(), and TransactionTimeoutHandler().

◆ VacuumBufferUsageLimit

PGDLLIMPORT int VacuumBufferUsageLimit
extern

Definition at line 148 of file globals.c.

Referenced by do_autovacuum(), and ExecVacuum().

◆ VacuumCostActive

◆ VacuumCostBalance

◆ VacuumCostDelay

PGDLLIMPORT double VacuumCostDelay
extern

Definition at line 154 of file globals.c.

Referenced by VacuumUpdateCosts().

◆ VacuumCostLimit

PGDLLIMPORT int VacuumCostLimit
extern

Definition at line 153 of file globals.c.

Referenced by AutoVacuumUpdateCostLimit(), and VacuumUpdateCosts().

◆ VacuumCostPageDirty

PGDLLIMPORT int VacuumCostPageDirty
extern

Definition at line 152 of file globals.c.

Referenced by MarkBufferDirty(), and MarkBufferDirtyHint().

◆ VacuumCostPageHit

PGDLLIMPORT int VacuumCostPageHit
extern

Definition at line 150 of file globals.c.

Referenced by PinBufferForBlock().

◆ VacuumCostPageMiss

PGDLLIMPORT int VacuumCostPageMiss
extern

Definition at line 151 of file globals.c.

Referenced by WaitReadBuffers().

◆ work_mem