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

Go to the source code of this file.

Macros

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

Typedefs

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

Enumerations

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

Functions

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

Variables

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

Macro Definition Documentation

◆ AmArchiverProcess

#define AmArchiverProcess ( )    (MyAuxProcType == ArchiverProcess)

Definition at line 442 of file miscadmin.h.

◆ AmBackgroundWriterProcess

#define AmBackgroundWriterProcess ( )    (MyAuxProcType == BgWriterProcess)

Definition at line 441 of file miscadmin.h.

◆ AmCheckpointerProcess

#define AmCheckpointerProcess ( )    (MyAuxProcType == CheckpointerProcess)

Definition at line 443 of file miscadmin.h.

◆ AmStartupProcess

#define AmStartupProcess ( )    (MyAuxProcType == StartupProcess)

Definition at line 440 of file miscadmin.h.

◆ AmWalReceiverProcess

#define AmWalReceiverProcess ( )    (MyAuxProcType == WalReceiverProcess)

Definition at line 445 of file miscadmin.h.

◆ AmWalWriterProcess

#define AmWalWriterProcess ( )    (MyAuxProcType == WalWriterProcess)

Definition at line 444 of file miscadmin.h.

◆ CHECK_FOR_INTERRUPTS

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

Definition at line 121 of file miscadmin.h.

◆ DATEORDER_DMY

#define DATEORDER_DMY   1

Definition at line 237 of file miscadmin.h.

◆ DATEORDER_MDY

#define DATEORDER_MDY   2

Definition at line 238 of file miscadmin.h.

◆ DATEORDER_YMD

#define DATEORDER_YMD   0

Definition at line 236 of file miscadmin.h.

◆ END_CRIT_SECTION

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

Definition at line 150 of file miscadmin.h.

◆ GetProcessingMode

#define GetProcessingMode ( )    Mode

Definition at line 406 of file miscadmin.h.

◆ HOLD_CANCEL_INTERRUPTS

#define HOLD_CANCEL_INTERRUPTS ( )    (QueryCancelHoldoffCount++)

Definition at line 140 of file miscadmin.h.

◆ HOLD_INTERRUPTS

#define HOLD_INTERRUPTS ( )    (InterruptHoldoffCount++)

Definition at line 132 of file miscadmin.h.

◆ INTERRUPTS_CAN_BE_PROCESSED

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

Definition at line 128 of file miscadmin.h.

◆ INTERRUPTS_PENDING_CONDITION

#define INTERRUPTS_PENDING_CONDITION ( )     (unlikely(InterruptPending))

Definition at line 112 of file miscadmin.h.

◆ INTSTYLE_ISO_8601

#define INTSTYLE_ISO_8601   3

Definition at line 253 of file miscadmin.h.

◆ INTSTYLE_POSTGRES

#define INTSTYLE_POSTGRES   0

Definition at line 250 of file miscadmin.h.

◆ INTSTYLE_POSTGRES_VERBOSE

#define INTSTYLE_POSTGRES_VERBOSE   1

Definition at line 251 of file miscadmin.h.

◆ INTSTYLE_SQL_STANDARD

#define INTSTYLE_SQL_STANDARD   2

Definition at line 252 of file miscadmin.h.

◆ InvalidPid

#define InvalidPid   (-1)

Definition at line 32 of file miscadmin.h.

◆ IsBootstrapProcessingMode

#define IsBootstrapProcessingMode ( )    (Mode == BootstrapProcessing)

Definition at line 402 of file miscadmin.h.

◆ IsInitProcessingMode

#define IsInitProcessingMode ( )    (Mode == InitProcessing)

Definition at line 403 of file miscadmin.h.

◆ IsNormalProcessingMode

#define IsNormalProcessingMode ( )    (Mode == NormalProcessing)

Definition at line 404 of file miscadmin.h.

◆ MAXTZLEN

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

Definition at line 257 of file miscadmin.h.

◆ RESUME_CANCEL_INTERRUPTS

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

Definition at line 142 of file miscadmin.h.

◆ RESUME_INTERRUPTS

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

Definition at line 134 of file miscadmin.h.

◆ SECURITY_LOCAL_USERID_CHANGE

#define SECURITY_LOCAL_USERID_CHANGE   0x0001

Definition at line 304 of file miscadmin.h.

◆ SECURITY_NOFORCE_RLS

#define SECURITY_NOFORCE_RLS   0x0004

Definition at line 306 of file miscadmin.h.

◆ SECURITY_RESTRICTED_OPERATION

#define SECURITY_RESTRICTED_OPERATION   0x0002

Definition at line 305 of file miscadmin.h.

◆ SetProcessingMode

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

Definition at line 408 of file miscadmin.h.

◆ START_CRIT_SECTION

#define START_CRIT_SECTION ( )    (CritSectionCount++)

Definition at line 148 of file miscadmin.h.

◆ USE_GERMAN_DATES

#define USE_GERMAN_DATES   3

Definition at line 232 of file miscadmin.h.

◆ USE_ISO_DATES

#define USE_ISO_DATES   1

Definition at line 230 of file miscadmin.h.

◆ USE_POSTGRES_DATES

#define USE_POSTGRES_DATES   0

Definition at line 229 of file miscadmin.h.

◆ USE_SQL_DATES

#define USE_SQL_DATES   2

Definition at line 231 of file miscadmin.h.

◆ USE_XSD_DATES

#define USE_XSD_DATES   4

Definition at line 233 of file miscadmin.h.

Typedef Documentation

◆ BackendType

typedef enum BackendType BackendType

◆ pg_stack_base_t

typedef char* pg_stack_base_t

Definition at line 282 of file miscadmin.h.

◆ ProcessingMode

◆ shmem_request_hook_type

typedef void(* shmem_request_hook_type) (void)

Definition at line 485 of file miscadmin.h.

Enumeration Type Documentation

◆ AuxProcType

Enumerator
NotAnAuxProcess 
StartupProcess 
BgWriterProcess 
ArchiverProcess 
CheckpointerProcess 
WalWriterProcess 
WalReceiverProcess 
NUM_AUXPROCTYPES 

Definition at line 425 of file miscadmin.h.

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

◆ BackendType

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

Definition at line 316 of file miscadmin.h.

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

◆ ProcessingMode

Enumerator
BootstrapProcessing 
InitProcessing 
NormalProcessing 

Definition at line 393 of file miscadmin.h.

394 {
395  BootstrapProcessing, /* bootstrap creation of template database */
396  InitProcessing, /* initializing system */
397  NormalProcessing /* normal processing */
ProcessingMode
Definition: miscadmin.h:394

Function Documentation

◆ AddToDataDirLockFile()

void AddToDataDirLockFile ( int  target_line,
const char *  str 
)

Definition at line 1498 of file miscinit.c.

1499 {
1500  int fd;
1501  int len;
1502  int lineno;
1503  char *srcptr;
1504  char *destptr;
1505  char srcbuffer[BLCKSZ];
1506  char destbuffer[BLCKSZ];
1507 
1508  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1509  if (fd < 0)
1510  {
1511  ereport(LOG,
1513  errmsg("could not open file \"%s\": %m",
1515  return;
1516  }
1518  len = read(fd, srcbuffer, sizeof(srcbuffer) - 1);
1520  if (len < 0)
1521  {
1522  ereport(LOG,
1524  errmsg("could not read from file \"%s\": %m",
1526  close(fd);
1527  return;
1528  }
1529  srcbuffer[len] = '\0';
1530 
1531  /*
1532  * Advance over lines we are not supposed to rewrite, then copy them to
1533  * destbuffer.
1534  */
1535  srcptr = srcbuffer;
1536  for (lineno = 1; lineno < target_line; lineno++)
1537  {
1538  char *eol = strchr(srcptr, '\n');
1539 
1540  if (eol == NULL)
1541  break; /* not enough lines in file yet */
1542  srcptr = eol + 1;
1543  }
1544  memcpy(destbuffer, srcbuffer, srcptr - srcbuffer);
1545  destptr = destbuffer + (srcptr - srcbuffer);
1546 
1547  /*
1548  * Fill in any missing lines before the target line, in case lines are
1549  * added to the file out of order.
1550  */
1551  for (; lineno < target_line; lineno++)
1552  {
1553  if (destptr < destbuffer + sizeof(destbuffer))
1554  *destptr++ = '\n';
1555  }
1556 
1557  /*
1558  * Write or rewrite the target line.
1559  */
1560  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s\n", str);
1561  destptr += strlen(destptr);
1562 
1563  /*
1564  * If there are more lines in the old file, append them to destbuffer.
1565  */
1566  if ((srcptr = strchr(srcptr, '\n')) != NULL)
1567  {
1568  srcptr++;
1569  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s",
1570  srcptr);
1571  }
1572 
1573  /*
1574  * And rewrite the data. Since we write in a single kernel call, this
1575  * update should appear atomic to onlookers.
1576  */
1577  len = strlen(destbuffer);
1578  errno = 0;
1580  if (pg_pwrite(fd, destbuffer, len, 0) != len)
1581  {
1583  /* if write didn't set errno, assume problem is no disk space */
1584  if (errno == 0)
1585  errno = ENOSPC;
1586  ereport(LOG,
1588  errmsg("could not write to file \"%s\": %m",
1590  close(fd);
1591  return;
1592  }
1595  if (pg_fsync(fd) != 0)
1596  {
1597  ereport(LOG,
1599  errmsg("could not write to file \"%s\": %m",
1601  }
1603  if (close(fd) != 0)
1604  {
1605  ereport(LOG,
1607  errmsg("could not write to file \"%s\": %m",
1609  }
1610 }
#define PG_BINARY
Definition: c.h:1209
int errcode_for_file_access(void)
Definition: elog.c:718
int errmsg(const char *fmt,...)
Definition: elog.c:906
#define LOG
Definition: elog.h:27
#define ereport(elevel,...)
Definition: elog.h:145
int pg_fsync(int fd)
Definition: fd.c:356
#define close(a)
Definition: win32.h:12
#define read(a, b, c)
Definition: win32.h:13
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:59
const void size_t len
#define pg_pwrite
Definition: port.h:226
#define snprintf
Definition: port.h:238
static int fd(const char *x, int i)
Definition: preproc-init.c:105
@ WAIT_EVENT_LOCK_FILE_ADDTODATADIR_WRITE
Definition: wait_event.h:186
@ WAIT_EVENT_LOCK_FILE_ADDTODATADIR_READ
Definition: wait_event.h:184
@ WAIT_EVENT_LOCK_FILE_ADDTODATADIR_SYNC
Definition: wait_event.h:185
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:268
static void pgstat_report_wait_end(void)
Definition: wait_event.h:284

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

Referenced by InternalIpcMemoryCreate(), pmdie(), PostmasterMain(), reaper(), and sigusr1_handler().

◆ BaseInit()

void BaseInit ( void  )

Definition at line 623 of file postinit.c.

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

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

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

◆ ChangeToDataDir()

void ChangeToDataDir ( void  )

Definition at line 436 of file miscinit.c.

437 {
438  Assert(DataDir);
439 
440  if (chdir(DataDir) < 0)
441  ereport(FATAL,
443  errmsg("could not change directory to \"%s\": %m",
444  DataDir)));
445 }
#define FATAL
Definition: elog.h:37
char * DataDir
Definition: globals.c:66

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

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

◆ check_stack_depth()

void check_stack_depth ( void  )

Definition at line 3440 of file postgres.c.

3441 {
3442  if (stack_is_too_deep())
3443  {
3444  ereport(ERROR,
3445  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3446  errmsg("stack depth limit exceeded"),
3447  errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3448  "after ensuring the platform's stack depth limit is adequate.",
3449  max_stack_depth)));
3450  }
3451 }
int errhint(const char *fmt,...)
Definition: elog.c:1153
int errcode(int sqlerrcode)
Definition: elog.c:695
#define ERROR
Definition: elog.h:35
int max_stack_depth
Definition: postgres.c:93
bool stack_is_too_deep(void)
Definition: postgres.c:3454

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

Referenced by AlterTypeRecurse(), apply_scanjoin_target_to_paths(), checkCond(), clean_NOT_intree(), clean_stopword_intree(), cntsize(), contains_required_value(), convertJsonbValue(), copyObjectImpl(), Cover(), create_plan_recurse(), datum_to_json(), datum_to_jsonb(), dofindsubquery(), emit_jsp_gin_entries(), equal(), EventTriggerInvoke(), ExecEndNode(), ExecEvalSubPlan(), ExecInitExprRec(), ExecInitNode(), ExecMakeFunctionResultSet(), ExecProcNodeFirst(), ExecShutdownNode_walker(), execute(), executeAnyItem(), executeItemOptUnwrapTarget(), expand_partitioned_rtentry(), expression_tree_mutator_impl(), expression_tree_walker_impl(), extract_jsp_bool_expr(), fillQT(), find_composite_type_dependencies(), find_matching_subplans_recurse(), findoprnd(), findoprnd_recurse(), flatten_grouping_sets(), flattenJsonPathParseItem(), FreePageManagerDumpBtree(), freetree(), generate_partition_qual(), generate_partitionwise_join_paths(), get_query_def(), get_rels_with_domain(), get_rule_expr(), get_setop_query(), get_steps_using_prefix_recurse(), gistSplit(), hash_range(), hash_range_extended(), hash_record(), hash_record_extended(), hk_depth_search(), infix(), inline_set_returning_function(), int_query_opr_selec(), JsonbDeepContains(), JumbleExpr(), lseg_inside_poly(), ltree_execute(), makepol(), maketree(), MatchText(), MultiExecProcNode(), outNode(), parse_array(), parse_object(), parseNodeString(), plainnode(), planstate_tree_walker_impl(), plperl_hash_from_tuple(), plperl_sv_to_datum(), PLy_input_setup_func(), PLy_output_setup_func(), populate_array_dim_jsonb(), populate_record_field(), printJsonPathItem(), 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_recurse(), TS_phrase_execute(), tsquery_opr_selec(), and tsquery_requires_match().

◆ checkDataDir()

void checkDataDir ( void  )

Definition at line 323 of file miscinit.c.

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

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

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

◆ CreateDataDirLockFile()

void CreateDataDirLockFile ( bool  amPostmaster)

Definition at line 1442 of file miscinit.c.

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

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

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

References CreateLockFile(), MAXPGPATH, and snprintf.

Referenced by Lock_AF_UNIX().

◆ EstimateClientConnectionInfoSpace()

Size EstimateClientConnectionInfoSpace ( void  )

Definition at line 1014 of file miscinit.c.

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

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

Referenced by InitializeParallelDSM().

◆ get_hash_memory_limit()

size_t get_hash_memory_limit ( void  )

Definition at line 3390 of file nodeHash.c.

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

References hash_mem_multiplier, Min, and work_mem.

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

◆ GetAuthenticatedUserId()

Oid GetAuthenticatedUserId ( void  )

Definition at line 566 of file miscinit.c.

567 {
569  return AuthenticatedUserId;
570 }
#define OidIsValid(objectId)
Definition: c.h:711
static Oid AuthenticatedUserId
Definition: miscinit.c:476

References Assert(), AuthenticatedUserId, and OidIsValid.

Referenced by InitializeParallelDSM().

◆ GetBackendTypeDesc()

const char* GetBackendTypeDesc ( BackendType  backendType)

Definition at line 251 of file miscinit.c.

252 {
253  const char *backendDesc = "unknown process type";
254 
255  switch (backendType)
256  {
257  case B_INVALID:
258  backendDesc = "not initialized";
259  break;
260  case B_ARCHIVER:
261  backendDesc = "archiver";
262  break;
263  case B_AUTOVAC_LAUNCHER:
264  backendDesc = "autovacuum launcher";
265  break;
266  case B_AUTOVAC_WORKER:
267  backendDesc = "autovacuum worker";
268  break;
269  case B_BACKEND:
270  backendDesc = "client backend";
271  break;
272  case B_BG_WORKER:
273  backendDesc = "background worker";
274  break;
275  case B_BG_WRITER:
276  backendDesc = "background writer";
277  break;
278  case B_CHECKPOINTER:
279  backendDesc = "checkpointer";
280  break;
281  case B_LOGGER:
282  backendDesc = "logger";
283  break;
285  backendDesc = "standalone backend";
286  break;
287  case B_STARTUP:
288  backendDesc = "startup";
289  break;
290  case B_WAL_RECEIVER:
291  backendDesc = "walreceiver";
292  break;
293  case B_WAL_SENDER:
294  backendDesc = "walsender";
295  break;
296  case B_WAL_WRITER:
297  backendDesc = "walwriter";
298  break;
299  }
300 
301  return backendDesc;
302 }

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

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

◆ GetCurrentRoleId()

Oid GetCurrentRoleId ( void  )

Definition at line 911 of file miscinit.c.

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

509 {
511  return OuterUserId;
512 }

References Assert(), OidIsValid, and OuterUserId.

Referenced by DropRole(), and RenameRole().

◆ GetSessionUserId()

Oid GetSessionUserId ( void  )

Definition at line 531 of file miscinit.c.

532 {
534  return SessionUserId;
535 }
static Oid SessionUserId
Definition: miscinit.c:477

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

558 {
559  return SystemUser;
560 }
static const char * SystemUser
Definition: miscinit.c:480

References SystemUser.

Referenced by system_user().

◆ GetUserId()

Oid GetUserId ( void  )

Definition at line 497 of file miscinit.c.

498 {
500  return CurrentUserId;
501 }
static Oid CurrentUserId
Definition: miscinit.c:479

References Assert(), CurrentUserId, and OidIsValid.

Referenced by AddRoleMems(), AggregateCreate(), AlterCollation(), AlterDatabase(), AlterDatabaseOwner(), AlterDatabaseRefreshColl(), AlterDatabaseSet(), AlterEventTrigger(), AlterEventTriggerOwner_internal(), AlterExtensionNamespace(), AlterForeignServer(), AlterForeignServerOwner_internal(), AlterFunction(), AlterObjectNamespace_internal(), AlterObjectOwner_internal(), AlterObjectRename_internal(), AlterOperator(), AlterOpFamilyAdd(), AlterPublication(), AlterPublicationOwner_internal(), AlterRole(), AlterRoleSet(), AlterSchemaOwner_internal(), AlterStatistics(), AlterSubscription(), AlterSubscriptionOwner_internal(), AlterSystemSetConfigFile(), AlterTableMoveAll(), AlterTableSpaceOptions(), AlterTSConfiguration(), AlterTSDictionary(), AlterType(), AlterTypeNamespace_oid(), AlterTypeOwner(), ATExecAddColumn(), ATExecChangeOwner(), ATPrepAlterColumnType(), ATPrepSetTableSpace(), ATSimplePermissions(), bbsink_server_new(), be_lo_put(), be_lo_unlink(), binary_upgrade_create_empty_extension(), brin_desummarize_range(), BuildCachedPlan(), BuildDescForRelation(), BuildIndexValueDescription(), calculate_database_size(), calculate_tablespace_size(), call_pltcl_start_proc(), check_enable_rls(), check_temp_tablespaces(), CheckCachedPlan(), checkDomainOwner(), checkEnumOwner(), checkFkeyPermissions(), CheckFunctionValidatorAccess(), CheckMyDatabase(), CheckSlotPermissions(), CommentObject(), compile_plperl_function(), compile_pltcl_function(), CompleteCachedPlan(), compute_return_type(), convert_and_check_filename(), create_foreign_modify(), CreateCast(), CreateConversionCommand(), createdb(), CreateEventTrigger(), CreateExtensionInternal(), CreateForeignDataWrapper(), CreateForeignServer(), CreateForeignTable(), CreateFunction(), CreateOpFamily(), CreateProceduralLanguage(), CreatePublication(), 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(), DelRoleMems(), 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(), ExecCheckRTEPerms(), ExecGrant_Attribute(), ExecGrant_Database(), ExecGrant_Fdw(), ExecGrant_ForeignServer(), ExecGrant_Function(), ExecGrant_Language(), ExecGrant_Largeobject(), ExecGrant_Namespace(), ExecGrant_Parameter(), ExecGrant_Relation(), ExecGrant_Tablespace(), ExecGrant_Type(), ExecInitAgg(), ExecInitExprRec(), ExecInitFunc(), ExecInitWindowAgg(), ExecReindex(), ExecSecLabelStmt(), execute_extension_script(), ExecuteCallStmt(), ExecuteDoStmt(), ExecuteGrantStmt(), ExecuteTruncateGuts(), extension_is_trusted(), file_fdw_validator(), findRangeCanonicalFunction(), findRangeSubtypeDiffFunction(), FinishPreparedTransaction(), get_connect_string(), get_explain_guc_options(), 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(), GetConfigOption(), GetConfigOptionByName(), GetConfigOptionResetString(), GetConfigOptionValues(), gin_clean_pending_list(), HandleFunctionRequest(), has_any_column_privilege_id(), has_any_column_privilege_name(), has_column_privilege_id_attnum(), has_column_privilege_id_name(), has_column_privilege_name_attnum(), has_column_privilege_name_name(), has_database_privilege_id(), has_database_privilege_name(), has_foreign_data_wrapper_privilege_id(), has_foreign_data_wrapper_privilege_name(), has_function_privilege_id(), has_function_privilege_name(), has_language_privilege_id(), has_language_privilege_name(), has_parameter_privilege_name(), has_schema_privilege_id(), has_schema_privilege_name(), has_sequence_privilege_id(), has_sequence_privilege_name(), has_server_privilege_id(), has_server_privilege_name(), has_table_privilege_id(), has_table_privilege_name(), has_tablespace_privilege_id(), has_tablespace_privilege_name(), has_type_privilege_id(), has_type_privilege_name(), have_createdb_privilege(), have_createrole_privilege(), heap_force_common(), ImportForeignSchema(), init_sexpr(), InitializeSearchPath(), InitPostgres(), InitTempTableNamespace(), inline_function(), inline_set_returning_function(), insert_username(), interpret_function_parameter_list(), inv_create(), inv_open(), LargeObjectCreate(), lastval(), LockViewRecurse(), LogicalRepSyncTableStart(), lookup_agg_function(), LookupCreationNamespace(), LookupExplicitNamespace(), MergeAttributes(), movedb(), nextval_internal(), OperatorCreate(), OperatorShellMake(), pg_has_role_id(), pg_has_role_name(), pg_import_system_collations(), pg_prewarm(), pg_sequence_last_value(), pg_sequence_parameters(), pg_signal_backend(), pg_stat_get_wal_receiver(), pg_stat_get_wal_senders(), pg_stat_statements_internal(), pgrowlocks(), pgss_store(), pgstat_get_backend_current_activity(), pltcl_fetch_interp(), postgresBeginDirectModify(), postgresBeginForeignScan(), postgresExecForeignTruncate(), postgresGetForeignRelSize(), postgresImportForeignSchema(), PrepareTempTablespaces(), PrepareTransaction(), PublicationAddTables(), RangeVarCallbackForAlterRelation(), RangeVarCallbackForDropRelation(), RangeVarCallbackForLockTable(), RangeVarCallbackForPolicy(), RangeVarCallbackForReindexIndex(), RangeVarCallbackForRenameRule(), RangeVarCallbackForRenameTrigger(), RangeVarCallbackOwnsRelation(), RangeVarCallbackOwnsTable(), RangeVarGetAndCheckCreationNamespace(), ReassignOwnedObjects(), recomputeNamespacePath(), REGRESS_exec_check_perms(), REGRESS_object_access_hook(), REGRESS_object_access_hook_str(), REGRESS_utility_command(), ReindexMultipleInternal(), ReindexMultipleTables(), RemoveObjects(), renameatt_check(), RenameDatabase(), RenameSchema(), RenameTableSpace(), RenameType(), RevalidateCachedQuery(), RI_Initial_Check(), ri_ReportViolation(), select_perl_context(), set_config_option(), set_foreign_rel_properties(), shell_check_detail(), ShowAllGUCConfig(), standard_ProcessUtility(), statext_is_compatible_clause(), superuser(), TargetPrivilegesCheck(), TerminateOtherDBBackends(), transformTableLikeClause(), truncate_check_perms(), user_mapping_ddl_aclcheck(), vacuum_is_permitted_for_relation(), validate_option_array_item(), ValidateJoinEstimator(), and ValidateRestrictionEstimator().

◆ GetUserIdAndContext()

void GetUserIdAndContext ( Oid userid,
bool sec_def_context 
)

Definition at line 667 of file miscinit.c.

668 {
669  *userid = CurrentUserId;
670  *sec_def_context = InLocalUserIdChange();
671 }
bool InLocalUserIdChange(void)
Definition: miscinit.c:636

References CurrentUserId, and InLocalUserIdChange().

◆ GetUserIdAndSecContext()

◆ GetUserNameFromId()

char* GetUserNameFromId ( Oid  roleid,
bool  noerr 
)

Definition at line 967 of file miscinit.c.

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

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

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

◆ has_rolreplication()

bool has_rolreplication ( Oid  roleid)

Definition at line 694 of file miscinit.c.

695 {
696  bool result = false;
697  HeapTuple utup;
698 
699  utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
700  if (HeapTupleIsValid(utup))
701  {
702  result = ((Form_pg_authid) GETSTRUCT(utup))->rolreplication;
703  ReleaseSysCache(utup);
704  }
705  return result;
706 }
bool rolreplication
Definition: pg_authid.h:40

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

Referenced by CheckSlotPermissions(), and InitPostgres().

◆ InitializeMaxBackends()

void InitializeMaxBackends ( void  )

Definition at line 553 of file postinit.c.

554 {
555  Assert(MaxBackends == 0);
556 
557  /* the extra unit accounts for the autovacuum launcher */
560 
561  /* internal error because the values were all checked previously */
563  elog(ERROR, "too many backends configured");
564 }
int autovacuum_max_workers
Definition: autovacuum.c:117
int MaxConnections
Definition: globals.c:137
int MaxBackends
Definition: globals.c:140
int max_worker_processes
Definition: globals.c:138
#define MAX_BACKENDS
Definition: postmaster.h:77
int max_wal_senders
Definition: walsender.c:122

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

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

◆ InitializeSessionUserId()

void InitializeSessionUserId ( const char *  rolename,
Oid  roleid 
)

Definition at line 712 of file miscinit.c.

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

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

Referenced by InitPostgres().

◆ InitializeSessionUserIdStandalone()

void InitializeSessionUserIdStandalone ( void  )

Definition at line 815 of file miscinit.c.

816 {
817  /*
818  * This function should only be called in single-user mode, in autovacuum
819  * workers, and in background workers.
820  */
822 
823  /* call only once */
825 
826  AuthenticatedUserId = BOOTSTRAP_SUPERUSERID;
828 
829  SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
830 }
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3314
bool IsBackgroundWorker
Definition: globals.c:115

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

Referenced by InitPostgres().

◆ InitializeSystemUser()

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

Definition at line 838 of file miscinit.c.

839 {
840  char *system_user;
841 
842  /* call only once */
843  Assert(SystemUser == NULL);
844 
845  /*
846  * InitializeSystemUser should be called only when authn_id is not NULL,
847  * meaning that auth_method is valid.
848  */
849  Assert(authn_id != NULL);
850 
851  system_user = psprintf("%s:%s", auth_method, authn_id);
852 
853  /* Store SystemUser in long-lived storage */
856 }
void pfree(void *pointer)
Definition: mcxt.c:1306
MemoryContext TopMemoryContext
Definition: mcxt.c:130
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1470
Datum system_user(PG_FUNCTION_ARGS)
Definition: miscinit.c:862
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46

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

Referenced by InitPostgres(), and ParallelWorkerMain().

◆ InitPostgres()

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

Definition at line 712 of file postinit.c.

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

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

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

◆ InitPostmasterChild()

void InitPostmasterChild ( void  )

Definition at line 95 of file miscinit.c.

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

References BlockSig, elog(), FATAL, InitializeLatchSupport(), InitializeLatchWaitSet(), InitLatch(), InitProcessGlobals(), IsUnderPostmaster, LocalLatchData, MyLatch, on_exit_reset(), PG_SETMASK, pgwin32_signal_initialize(), PostmasterDeathSignalInit(), pqinitmask(), pqsignal(), set_stack_base(), SignalHandlerForCrashExit(), and SIGQUIT.

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

◆ InitStandaloneProcess()

void InitStandaloneProcess ( const char *  argv0)

Definition at line 175 of file miscinit.c.

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

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

Referenced by BootstrapModeMain(), and PostgresSingleUserMain().

◆ InLocalUserIdChange()

bool InLocalUserIdChange ( void  )

Definition at line 636 of file miscinit.c.

637 {
639 }
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:304

References SECURITY_LOCAL_USERID_CHANGE, and SecurityRestrictionContext.

Referenced by GetUserIdAndContext(), and set_config_option_ext().

◆ InNoForceRLSOperation()

bool InNoForceRLSOperation ( void  )

Definition at line 654 of file miscinit.c.

655 {
657 }
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:306

References SECURITY_NOFORCE_RLS, and SecurityRestrictionContext.

Referenced by check_enable_rls().

◆ InSecurityRestrictedOperation()

bool InSecurityRestrictedOperation ( void  )

◆ pg_bindtextdomain()

void pg_bindtextdomain ( const char *  domain)

Definition at line 1867 of file miscinit.c.

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

496 {
497  StringInfoData s;
498 
499  initStringInfo(&s);
500 
501  while (*optstr)
502  {
503  bool last_was_escape = false;
504 
505  resetStringInfo(&s);
506 
507  /* skip over leading space */
508  while (isspace((unsigned char) *optstr))
509  optstr++;
510 
511  if (*optstr == '\0')
512  break;
513 
514  /*
515  * Parse a single option, stopping at the first space, unless it's
516  * escaped.
517  */
518  while (*optstr)
519  {
520  if (isspace((unsigned char) *optstr) && !last_was_escape)
521  break;
522 
523  if (!last_was_escape && *optstr == '\\')
524  last_was_escape = true;
525  else
526  {
527  last_was_escape = false;
528  appendStringInfoChar(&s, *optstr);
529  }
530 
531  optstr++;
532  }
533 
534  /* now store the option in the next argv[] position */
535  argv[(*argcp)++] = pstrdup(s.data);
536  }
537 
538  pfree(s.data);
539 }
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:75
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59

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

Referenced by process_startup_options().

◆ PreventCommandDuringRecovery()

void PreventCommandDuringRecovery ( const char *  cmdname)

Definition at line 448 of file utility.c.

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

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

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

◆ PreventCommandIfParallelMode()

void PreventCommandIfParallelMode ( const char *  cmdname)

Definition at line 429 of file utility.c.

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

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

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

◆ PreventCommandIfReadOnly()

void PreventCommandIfReadOnly ( const char *  cmdname)

Definition at line 411 of file utility.c.

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

1845 {
1847  "session_preload_libraries",
1848  false);
1850  "local_preload_libraries",
1851  true);
1852 }
char * session_preload_libraries_string
Definition: miscinit.c:1760
char * local_preload_libraries_string
Definition: miscinit.c:1762
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1778

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

1831 {
1834  "shared_preload_libraries",
1835  false);
1838 }
bool process_shared_preload_libraries_done
Definition: miscinit.c:1766
char * shared_preload_libraries_string
Definition: miscinit.c:1761
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1765

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

1859 {
1861  if (shmem_request_hook)
1864 }
bool process_shmem_requests_in_progress
Definition: miscinit.c:1769
shmem_request_hook_type shmem_request_hook
Definition: miscinit.c:1768

References process_shmem_requests_in_progress, and shmem_request_hook.

Referenced by PostgresSingleUserMain(), and PostmasterMain().

◆ ProcessInterrupts()

void ProcessInterrupts ( void  )

Definition at line 3131 of file postgres.c.

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

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

Referenced by die().

◆ RecheckDataDirLockFile()

bool RecheckDataDirLockFile ( void  )

Definition at line 1625 of file miscinit.c.

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

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

Referenced by ServerLoop().

◆ restore_stack_base()

void restore_stack_base ( pg_stack_base_t  base)

Definition at line 3423 of file postgres.c.

3424 {
3425  stack_base_ptr = base;
3426 }
static char * stack_base_ptr
Definition: postgres.c:126

References stack_base_ptr.

◆ RestoreClientConnectionInfo()

void RestoreClientConnectionInfo ( char *  conninfo)

Definition at line 1062 of file miscinit.c.

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

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

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

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

3391 {
3392 #ifndef HAVE__BUILTIN_FRAME_ADDRESS
3393  char stack_base;
3394 #endif
3395  pg_stack_base_t old;
3396 
3397  old = stack_base_ptr;
3398 
3399  /*
3400  * Set up reference point for stack depth checking. On recent gcc we use
3401  * __builtin_frame_address() to avoid a warning about storing a local
3402  * variable's address in a long-lived variable.
3403  */
3404 #ifdef HAVE__BUILTIN_FRAME_ADDRESS
3405  stack_base_ptr = __builtin_frame_address(0);
3406 #else
3407  stack_base_ptr = &stack_base;
3408 #endif
3409 
3410  return old;
3411 }
char * pg_stack_base_t
Definition: miscadmin.h:282

References stack_base_ptr.

Referenced by InitPostmasterChild(), and PostmasterMain().

◆ SetCurrentRoleId()

void SetCurrentRoleId ( Oid  roleid,
bool  is_superuser 
)

Definition at line 932 of file miscinit.c.

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

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

311 {
312  /* This should happen only once per process */
315 }
char * DatabasePath
Definition: globals.c:97

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

Referenced by InitPostgres().

◆ SetDataDir()

void SetDataDir ( const char *  dir)

Definition at line 416 of file miscinit.c.

417 {
418  char *new;
419 
420  Assert(dir);
421 
422  /* If presented path is relative, convert to absolute */
423  new = make_absolute_path(dir);
424 
425  free(DataDir);
426  DataDir = new;
427 }
#define free(a)
Definition: header.h:65
char * make_absolute_path(const char *path)
Definition: path.c:729

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

Referenced by SelectConfigFiles().

◆ SetSessionAuthorization()

void SetSessionAuthorization ( Oid  userid,
bool  is_superuser 
)

Definition at line 886 of file miscinit.c.

887 {
888  /* Must have authenticated already, else can't make permission check */
890 
891  if (userid != AuthenticatedUserId &&
893  ereport(ERROR,
894  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
895  errmsg("permission denied to set session authorization")));
896 
898 
899  SetConfigOption("is_superuser",
900  is_superuser ? "on" : "off",
902 }

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

Referenced by assign_session_authorization().

◆ SetUserIdAndContext()

void SetUserIdAndContext ( Oid  userid,
bool  sec_def_context 
)

Definition at line 674 of file miscinit.c.

675 {
676  /* We throw the same error SET ROLE would. */
678  ereport(ERROR,
679  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
680  errmsg("cannot set parameter \"%s\" within security-restricted operation",
681  "role")));
682  CurrentUserId = userid;
683  if (sec_def_context)
685  else
687 }
bool InSecurityRestrictedOperation(void)
Definition: miscinit.c:645

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

3455 {
3456  char stack_top_loc;
3457  long stack_depth;
3458 
3459  /*
3460  * Compute distance from reference point to my local variables
3461  */
3462  stack_depth = (long) (stack_base_ptr - &stack_top_loc);
3463 
3464  /*
3465  * Take abs value, since stacks grow up on some machines, down on others
3466  */
3467  if (stack_depth < 0)
3468  stack_depth = -stack_depth;
3469 
3470  /*
3471  * Trouble?
3472  *
3473  * The test on stack_base_ptr prevents us from erroring out if called
3474  * during process setup or in a non-backend process. Logically it should
3475  * be done first, but putting it here avoids wasting cycles during normal
3476  * cases.
3477  */
3478  if (stack_depth > max_stack_depth_bytes &&
3479  stack_base_ptr != NULL)
3480  return true;
3481 
3482  return false;
3483 }
static long max_stack_depth_bytes
Definition: postgres.c:120

References max_stack_depth_bytes, and stack_base_ptr.

Referenced by check_stack_depth(), and rstacktoodeep().

◆ superuser()

bool superuser ( void  )

Definition at line 46 of file superuser.c.

47 {
48  return superuser_arg(GetUserId());
49 }
bool superuser_arg(Oid roleid)
Definition: superuser.c:56

References GetUserId(), and superuser_arg().

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

◆ superuser_arg()

bool superuser_arg ( Oid  roleid)

Definition at line 56 of file superuser.c.

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

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

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

◆ SwitchBackToLocalLatch()

void SwitchBackToLocalLatch ( void  )

Definition at line 236 of file miscinit.c.

237 {
239  Assert(MyProc != NULL && MyLatch == &MyProc->procLatch);
240 
242 
243  if (FeBeWaitSet)
245  MyLatch);
246 
247  SetLatch(MyLatch);
248 }
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:972
void SetLatch(Latch *latch)
Definition: latch.c:591
#define WL_LATCH_SET
Definition: latch.h:125
#define FeBeWaitSetLatchPos
Definition: libpq.h:64
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:164
Latch procLatch
Definition: proc.h:170

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

Referenced by AuxiliaryProcKill(), and ProcKill().

◆ SwitchToSharedLatch()

void SwitchToSharedLatch ( void  )

Definition at line 216 of file miscinit.c.

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

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

1470 {
1471  ListCell *l;
1472 
1473  foreach(l, lock_files)
1474  {
1475  char *socketLockFile = (char *) lfirst(l);
1476 
1477  /* No need to touch the data directory lock file, we trust */
1478  if (strcmp(socketLockFile, DIRECTORY_LOCK_FILE) == 0)
1479  continue;
1480 
1481  /* we just ignore any error here */
1482  (void) utime(socketLockFile, NULL);
1483  }
1484 }
static List * lock_files
Definition: miscinit.c:66
#define lfirst(lc)
Definition: pg_list.h:170

References DIRECTORY_LOCK_FILE, lfirst, and lock_files.

Referenced by ServerLoop().

◆ trace_recovery()

int trace_recovery ( int  trace_level)

◆ ValidatePgVersion()

void ValidatePgVersion ( const char *  path)

Definition at line 1697 of file miscinit.c.

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

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

Referenced by checkDataDir(), and InitPostgres().

Variable Documentation

◆ allowSystemTableMods

◆ CheckClientConnectionPending

PGDLLIMPORT volatile sig_atomic_t CheckClientConnectionPending
extern

Definition at line 33 of file globals.c.

Referenced by ClientCheckTimeoutHandler(), and ProcessInterrupts().

◆ ClientConnectionLost

PGDLLIMPORT volatile sig_atomic_t ClientConnectionLost
extern

Definition at line 34 of file globals.c.

Referenced by internal_flush(), and ProcessInterrupts().

◆ CritSectionCount

◆ data_directory_mode

PGDLLIMPORT int data_directory_mode
extern

Definition at line 72 of file globals.c.

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

◆ DatabasePath

◆ DataDir

◆ DateOrder

PGDLLIMPORT int DateOrder
extern

◆ DateStyle

◆ enableFsync

◆ ExitOnAnyError

PGDLLIMPORT bool ExitOnAnyError
extern

Definition at line 117 of file globals.c.

Referenced by errstart(), and HandleCheckpointerInterrupts().

◆ hash_mem_multiplier

PGDLLIMPORT double hash_mem_multiplier
extern

Definition at line 126 of file globals.c.

Referenced by get_hash_memory_limit().

◆ IdleInTransactionSessionTimeoutPending

PGDLLIMPORT volatile sig_atomic_t IdleInTransactionSessionTimeoutPending
extern

Definition at line 35 of file globals.c.

Referenced by IdleInTransactionSessionTimeoutHandler(), and ProcessInterrupts().

◆ IdleSessionTimeoutPending

PGDLLIMPORT volatile sig_atomic_t IdleSessionTimeoutPending
extern

Definition at line 36 of file globals.c.

Referenced by IdleSessionTimeoutHandler(), and ProcessInterrupts().

◆ IdleStatsUpdateTimeoutPending

PGDLLIMPORT volatile sig_atomic_t IdleStatsUpdateTimeoutPending
extern

Definition at line 39 of file globals.c.

Referenced by IdleStatsUpdateTimeoutHandler(), and ProcessInterrupts().

◆ IgnoreSystemIndexes

◆ InterruptHoldoffCount

PGDLLIMPORT volatile uint32 InterruptHoldoffCount
extern

◆ InterruptPending

◆ IntervalStyle

PGDLLIMPORT int IntervalStyle
extern

◆ IsBackgroundWorker

◆ IsBinaryUpgrade

◆ IsPostmasterEnvironment

◆ IsUnderPostmaster

PGDLLIMPORT bool IsUnderPostmaster
extern

Definition at line 113 of file globals.c.

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

◆ local_preload_libraries_string

PGDLLIMPORT char* local_preload_libraries_string
extern

Definition at line 1762 of file miscinit.c.

Referenced by process_session_preload_libraries().

◆ LogMemoryContextPending

◆ maintenance_work_mem

◆ max_parallel_maintenance_workers

PGDLLIMPORT int max_parallel_maintenance_workers
extern

Definition at line 128 of file globals.c.

Referenced by parallel_vacuum_compute_workers(), and plan_create_index_workers().

◆ max_parallel_workers

PGDLLIMPORT int max_parallel_workers
extern

Definition at line 139 of file globals.c.

Referenced by RegisterDynamicBackgroundWorker().

◆ max_worker_processes

◆ MaxBackends

◆ MaxConnections

◆ Mode

Definition at line 61 of file miscinit.c.

◆ my_exec_path

◆ MyAuxProcType

PGDLLIMPORT AuxProcType MyAuxProcType
extern

Definition at line 45 of file auxprocess.c.

Referenced by AuxiliaryProcessMain(), and pgstat_beinit().

◆ MyBackendType

◆ MyCancelKey

◆ MyDatabaseId

PGDLLIMPORT Oid MyDatabaseId
extern

Definition at line 89 of file globals.c.

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

◆ MyDatabaseTableSpace

◆ MyLatch

PGDLLIMPORT struct Latch* MyLatch
extern

Definition at line 58 of file globals.c.

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

◆ MyPMChildSlot

◆ MyProcPid

PGDLLIMPORT int MyProcPid
extern

Definition at line 44 of file globals.c.

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

◆ MyProcPort

◆ MyStartTime

◆ MyStartTimestamp

PGDLLIMPORT TimestampTz MyStartTimestamp
extern

◆ NBuffers

PGDLLIMPORT int NBuffers
extern

Definition at line 136 of file globals.c.

◆ OutputFileName

PGDLLIMPORT char OutputFileName[]
extern

Definition at line 74 of file globals.c.

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

◆ pkglib_path

◆ PostmasterPid

◆ ProcDiePending

◆ process_shared_preload_libraries_done

PGDLLIMPORT bool process_shared_preload_libraries_done
extern

◆ process_shared_preload_libraries_in_progress

PGDLLIMPORT bool process_shared_preload_libraries_in_progress
extern

◆ process_shmem_requests_in_progress

PGDLLIMPORT bool process_shmem_requests_in_progress
extern

◆ ProcSignalBarrierPending

◆ QueryCancelHoldoffCount

PGDLLIMPORT volatile uint32 QueryCancelHoldoffCount
extern

Definition at line 41 of file globals.c.

Referenced by errfinish(), and ProcessInterrupts().

◆ QueryCancelPending

◆ session_preload_libraries_string

PGDLLIMPORT char* session_preload_libraries_string
extern

Definition at line 1760 of file miscinit.c.

Referenced by process_session_preload_libraries().

◆ shared_preload_libraries_string

PGDLLIMPORT char* shared_preload_libraries_string
extern

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

Referenced by _PG_init(), and process_shmem_requests().

◆ trace_recovery_messages

PGDLLIMPORT int trace_recovery_messages
extern

Definition at line 495 of file guc_tables.c.

Referenced by PerformWalRecovery(), and trace_recovery().

◆ VacuumCostActive

◆ VacuumCostBalance

◆ VacuumCostDelay

◆ VacuumCostLimit

◆ VacuumCostPageDirty

PGDLLIMPORT int VacuumCostPageDirty
extern

Definition at line 144 of file globals.c.

Referenced by MarkBufferDirty(), and MarkBufferDirtyHint().

◆ VacuumCostPageHit

PGDLLIMPORT int VacuumCostPageHit
extern

Definition at line 142 of file globals.c.

Referenced by ReadBuffer_common().

◆ VacuumCostPageMiss

PGDLLIMPORT int VacuumCostPageMiss
extern

Definition at line 143 of file globals.c.

Referenced by ReadBuffer_common().

◆ VacuumPageDirty

PGDLLIMPORT int64 VacuumPageDirty
extern

◆ VacuumPageHit

PGDLLIMPORT int64 VacuumPageHit
extern

◆ VacuumPageMiss

PGDLLIMPORT int64 VacuumPageMiss
extern

◆ work_mem