PostgreSQL Source Code  git master
miscadmin.h File Reference
#include <signal.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 CHECK_FOR_INTERRUPTS()
 
#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 AmBootstrapProcess()   (MyAuxProcType == BootstrapProcess)
 
#define AmStartupProcess()   (MyAuxProcType == StartupProcess)
 
#define AmBackgroundWriterProcess()   (MyAuxProcType == BgWriterProcess)
 
#define AmCheckpointerProcess()   (MyAuxProcType == CheckpointerProcess)
 
#define AmWalWriterProcess()   (MyAuxProcType == WalWriterProcess)
 
#define AmWalReceiverProcess()   (MyAuxProcType == WalReceiverProcess)
 

Typedefs

typedef char * pg_stack_base_t
 
typedef enum ProcessingMode ProcessingMode
 

Enumerations

enum  ProcessingMode { BootstrapProcessing, InitProcessing, NormalProcessing }
 
enum  AuxProcType {
  NotAnAuxProcess = -1, CheckerProcess = 0, BootstrapProcess, StartupProcess,
  BgWriterProcess, 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 PostgresSigHupHandler (SIGNAL_ARGS)
 
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 SetDatabasePath (const char *path)
 
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 useroid)
 
void InitializeSessionUserIdStandalone (void)
 
void SetSessionAuthorization (Oid userid, bool is_superuser)
 
Oid GetCurrentRoleId (void)
 
void SetCurrentRoleId (Oid roleid, bool is_superuser)
 
void checkDataDir (void)
 
void SetDataDir (const char *dir)
 
void ChangeToDataDir (void)
 
void SwitchToSharedLatch (void)
 
void SwitchBackToLocalLatch (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, char *out_dbname, bool override_allow_connections)
 
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 pg_bindtextdomain (const char *domain)
 
bool has_rolreplication (Oid roleid)
 
bool BackupInProgress (void)
 
void CancelBackup (void)
 

Variables

PGDLLIMPORT volatile bool InterruptPending
 
PGDLLIMPORT volatile bool QueryCancelPending
 
PGDLLIMPORT volatile bool ProcDiePending
 
PGDLLIMPORT volatile bool IdleInTransactionSessionTimeoutPending
 
PGDLLIMPORT volatile sig_atomic_t ConfigReloadPending
 
volatile bool 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 struct PortMyProcPort
 
PGDLLIMPORT struct LatchMyLatch
 
int32 MyCancelKey
 
int MyPMChildSlot
 
char OutputFileName []
 
PGDLLIMPORT char my_exec_path []
 
char pkglib_path []
 
PGDLLIMPORT Oid MyDatabaseId
 
PGDLLIMPORT Oid MyDatabaseTableSpace
 
PGDLLIMPORT int DateStyle
 
PGDLLIMPORT int DateOrder
 
PGDLLIMPORT int IntervalStyle
 
bool enableFsync
 
PGDLLIMPORT bool allowSystemTableMods
 
PGDLLIMPORT int work_mem
 
PGDLLIMPORT int maintenance_work_mem
 
PGDLLIMPORT int max_parallel_maintenance_workers
 
int VacuumCostPageHit
 
int VacuumCostPageMiss
 
int VacuumCostPageDirty
 
int VacuumCostLimit
 
int VacuumCostDelay
 
int VacuumPageHit
 
int VacuumPageMiss
 
int VacuumPageDirty
 
int VacuumCostBalance
 
bool VacuumCostActive
 
double vacuum_cleanup_index_scale_factor
 
int trace_recovery_messages
 
char * DatabasePath
 
ProcessingMode Mode
 
AuxProcType MyAuxProcType
 
bool IgnoreSystemIndexes
 
PGDLLIMPORT bool process_shared_preload_libraries_in_progress
 
char * session_preload_libraries_string
 
char * shared_preload_libraries_string
 
char * local_preload_libraries_string
 

Macro Definition Documentation

◆ AmBackgroundWriterProcess

#define AmBackgroundWriterProcess ( )    (MyAuxProcType == BgWriterProcess)

Definition at line 411 of file miscadmin.h.

Referenced by ForwardFsyncRequest().

◆ AmBootstrapProcess

#define AmBootstrapProcess ( )    (MyAuxProcType == BootstrapProcess)

Definition at line 409 of file miscadmin.h.

◆ AmCheckpointerProcess

#define AmCheckpointerProcess ( )    (MyAuxProcType == CheckpointerProcess)

◆ AmStartupProcess

#define AmStartupProcess ( )    (MyAuxProcType == StartupProcess)

Definition at line 410 of file miscadmin.h.

Referenced by HotStandbyActiveInReplay(), and mdinit().

◆ AmWalReceiverProcess

#define AmWalReceiverProcess ( )    (MyAuxProcType == WalReceiverProcess)

Definition at line 414 of file miscadmin.h.

Referenced by get_sync_bit().

◆ AmWalWriterProcess

#define AmWalWriterProcess ( )    (MyAuxProcType == WalWriterProcess)

Definition at line 413 of file miscadmin.h.

◆ CHECK_FOR_INTERRUPTS

#define CHECK_FOR_INTERRUPTS ( )
Value:
do { \
ProcessInterrupts(); \
} while(0)
PGDLLIMPORT volatile bool InterruptPending
Definition: globals.c:30

Definition at line 98 of file miscadmin.h.

Referenced by _bt_buildadd(), _bt_pagedel(), _bt_readnextpage(), _bt_unlink_halfdead_page(), _bt_walk_left(), _crypt_blowfish_rn(), _hash_init(), _hash_readnext(), _hash_readprev(), add_partial_path(), add_path(), agg_retrieve_hash_table(), analyze_rel(), ApplyLauncherMain(), apw_dump_now(), ATRewriteTable(), autoprewarm_database_main(), backend_read_statsfile(), BipartiteMatch(), BitmapHeapNext(), blgetbitmap(), bloomBuildCallback(), brin_evacuate_page(), brin_getinsertbuffer(), brin_vacuum_scan(), bringetbitmap(), brinGetTupleForHeapBlock(), brininsert(), brinsummarize(), bt_check_level_from_leftmost(), bt_downlink_missing_check(), bt_right_page_check_scankey(), bt_target_page_check(), btree_xlog_delete_get_latestRemovedXid(), BufFileDeleteShared(), BufFileOpenShared(), calculate_database_size(), calculate_relation_size(), calculate_tablespace_size(), check_default_partition_contents(), CheckSCRAMAuth(), ClientAuthentication(), cluster_rel(), collect_corrupt_items(), collect_visibility_data(), ConditionVariableSleep(), copy_file(), copy_heap_data(), copy_messages(), copy_read_data(), copy_relation_data(), copydir(), CopyFrom(), CopyTo(), count_nondeletable_pages(), CountOtherDBBackends(), db_dir_size(), DecodingContextFindStartpoint(), do_autovacuum(), do_des(), do_pg_stop_backup(), dofindsubquery(), dsm_impl_can_resize(), errfinish(), exec_execute_message(), exec_parse_message(), exec_replication_command(), exec_simple_query(), exec_stmt(), exec_stmts(), ExecAgg(), ExecAppend(), ExecCustomScan(), ExecGather(), ExecGatherMerge(), ExecGroup(), ExecHashIncreaseNumBatches(), ExecHashIncreaseNumBuckets(), ExecHashJoinGetSavedTuple(), ExecHashJoinImpl(), ExecHashRemoveNextSkewBucket(), ExecLimit(), ExecLockRows(), ExecMakeTableFunctionResult(), ExecMaterial(), ExecMergeAppend(), ExecMergeJoin(), ExecModifyTable(), ExecNestLoop(), ExecParallelHashIncreaseNumBuckets(), ExecParallelHashJoinPartitionOuter(), ExecParallelHashRepartitionFirst(), ExecParallelHashRepartitionRest(), ExecProjectSet(), ExecRecursiveUnion(), ExecResult(), ExecScanFetch(), ExecScanHashTableForUnmatched(), ExecSetOp(), ExecSort(), ExecSubPlan(), ExecUnique(), ExecWindowAgg(), fetch_input_tuple(), findPartialMatch(), fsm_vacuum_page(), gather_getnext(), gather_merge_init(), gather_readnext(), get_query_def(), get_rule_expr(), get_setop_query(), GetMultiXactIdMembers(), GetNewOidWithIndex(), GetNewRelFileNode(), getNextNearest(), ginbuild(), ginBuildCallback(), gingetbitmap(), gistgetbitmap(), gistgettuple(), gistProcessItup(), gm_readnext_tuple(), HandleFunctionRequest(), hash_xlog_vacuum_get_latestRemovedXid(), heap_lock_updated_tuple_rec(), heap_multi_insert(), heapgetpage(), hypothetical_dense_rank_final(), hypothetical_rank_common(), ident_inet(), IndexBuildHeapRangeScan(), IndexCheckExclusion(), IndexNext(), IndexNextWithReorder(), IndexOnlyNext(), initialize_worker_spi(), interactive_getc(), lazy_truncate_heap(), libpqrcv_connect(), libpqrcv_PQexec(), libpqrcv_processTuples(), logicalrep_worker_stop(), LogicalRepApplyLoop(), lseg_inside_poly(), make_bounded_heap(), mode_final(), mq_putmessage(), MultiExecBitmapIndexScan(), MultiExecProcNode(), nfalsepos_for_missing_strings(), numeric_fac(), OpenTableList(), pg_logical_replication_slot_advance(), pg_logical_slot_get_changes_guts(), pg_prewarm(), pg_sleep(), pg_visibility_map_summary(), pgfdw_get_cleanup_result(), pgfdw_get_result(), PGSemaphoreLock(), pgstat_collect_oids(), pgstat_get_backend_current_activity(), pgstat_heap(), pgstat_index(), pgstat_read_current_status(), pgstat_vacuum_stat(), pgstathashindex(), pgstatindex_impl(), plperl_spi_prepare(), populate_with_dummy_strings(), PortalRunMulti(), postgresAcquireSampleRowsFunc(), PostgresMain(), predicate_implied_by_simple_clause(), predicate_refuted_by_simple_clause(), process_ordered_aggregate_multi(), ProcessClientReadInterrupt(), ProcessClientWriteInterrupt(), ProcessWalRcvInterrupts(), ProcSleep(), ProcWaitForSignal(), puttuple_common(), random_relative_prime(), RE_compile_and_cache(), RE_wchar_execute(), read_local_xlog_page(), refresh_matview_datafill(), regexp_fixed_prefix(), replace_text(), replace_text_regexp(), replorigin_create(), RequestCheckpoint(), revmap_extend_and_get_blkno(), sendAuthRequest(), sendDir(), set_rtable_names(), setop_retrieve_hash_table(), shm_mq_receive_bytes(), shm_mq_send_bytes(), shm_mq_wait_internal(), spgdoinsert(), spgWalk(), statapprox_heap(), storeQueryResult(), summarize_range(), tablesample_getnext(), test_shm_mq_pipelined(), text_to_array_internal(), tfuncLoadRows(), throttle(), TidNext(), toast_save_datum(), tuplesort_heap_insert(), tuplesort_heap_replace_top(), tuplesort_skiptuples(), tuplestore_skiptuples(), vacuum_delay_point(), vacuum_rel(), validate_index_heapscan(), wait_for_relation_state_change(), wait_for_worker_state_change(), wait_for_workers_to_become_ready(), wait_pid(), WaitExceedsMaxStandbyDelay(), WaitForBackgroundWorkerShutdown(), WaitForBackgroundWorkerStartup(), WaitForParallelWorkersToAttach(), WaitForParallelWorkersToFinish(), WaitForReplicationWorkerAttach(), walkdir(), WalSndLoop(), WalSndWaitForWal(), WalSndWriteData(), and window_gettupleslot().

◆ DATEORDER_DMY

#define DATEORDER_DMY   1

◆ DATEORDER_MDY

#define DATEORDER_MDY   2

Definition at line 220 of file miscadmin.h.

Referenced by check_datestyle(), locale_date_order(), and setup_config().

◆ DATEORDER_YMD

#define DATEORDER_YMD   0

Definition at line 218 of file miscadmin.h.

Referenced by check_datestyle(), DecodeNumber(), locale_date_order(), and setup_config().

◆ END_CRIT_SECTION

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

Definition at line 133 of file miscadmin.h.

Referenced by _bt_delitems_delete(), _bt_delitems_vacuum(), _bt_getroot(), _bt_insertonpg(), _bt_mark_page_halfdead(), _bt_newroot(), _bt_split(), _bt_unlink_halfdead_page(), _bt_update_meta_cleanup_info(), _hash_addovflpage(), _hash_doinsert(), _hash_expandtable(), _hash_freeovflpage(), _hash_splitbucket(), _hash_squeezebucket(), _hash_vacuum_one_page(), AbsorbFsyncRequests(), addLeafTuple(), brin_doinsert(), brin_doupdate(), brin_initialize_empty_new_buffer(), brinbuildempty(), brinRevmapDesummarizeRange(), CreateCheckPoint(), CreateEndOfRecoveryRecord(), createPostingTree(), CreateSlotOnDisk(), do_setval(), doPickSplit(), EndPrepare(), fill_seq_with_data(), FreeSpaceMapTruncateRel(), GenericXLogFinish(), ginbuild(), ginbuildempty(), ginbulkdelete(), ginDeletePage(), ginHeapTupleFastInsert(), ginPlaceToPage(), ginUpdateStats(), ginVacuumPostingTreeLeaf(), gistbuild(), gistbuildempty(), gistbulkdelete(), gistplacetopage(), gistvacuumpage(), hashbucketcleanup(), hashbulkdelete(), heap_abort_speculative(), heap_delete(), heap_finish_speculative(), heap_inplace_update(), heap_insert(), heap_lock_tuple(), heap_lock_updated_tuple_rec(), heap_multi_insert(), heap_page_prune(), heap_update(), lazy_scan_heap(), lazy_vacuum_page(), moveLeafs(), MultiXactIdCreateFromMembers(), nextval_internal(), PostPrepare_Locks(), RecordTransactionAbort(), RecordTransactionAbortPrepared(), RecordTransactionCommit(), RecordTransactionCommitPrepared(), ReplicationSlotDropPtr(), RestoreSlotFromDisk(), revmap_physical_extend(), SaveSlotToPath(), shiftList(), SlruPhysicalWritePage(), spgAddNodeAction(), spgbuild(), spgSplitNodeAction(), TruncateMultiXact(), UpdateFullPageWrites(), vacuumLeafPage(), vacuumLeafRoot(), vacuumRedirectAndPlaceholder(), visibilitymap_set(), visibilitymap_truncate(), write_relmap_file(), writeListPage(), XLogBackgroundFlush(), XLogFlush(), and XLogInsertRecord().

◆ GetProcessingMode

#define GetProcessingMode ( )    Mode

Definition at line 376 of file miscadmin.h.

◆ HOLD_CANCEL_INTERRUPTS

#define HOLD_CANCEL_INTERRUPTS ( )    (QueryCancelHoldoffCount++)

Definition at line 123 of file miscadmin.h.

Referenced by CopyGetData(), and SocketBackend().

◆ HOLD_INTERRUPTS

◆ INTSTYLE_ISO_8601

#define INTSTYLE_ISO_8601   3

Definition at line 235 of file miscadmin.h.

Referenced by EncodeInterval().

◆ INTSTYLE_POSTGRES

#define INTSTYLE_POSTGRES   0

Definition at line 232 of file miscadmin.h.

Referenced by EncodeInterval(), and set_transmission_modes().

◆ INTSTYLE_POSTGRES_VERBOSE

#define INTSTYLE_POSTGRES_VERBOSE   1

Definition at line 233 of file miscadmin.h.

Referenced by DecodeInterval(), EncodeInterval(), and PGTYPESinterval_to_asc().

◆ INTSTYLE_SQL_STANDARD

#define INTSTYLE_SQL_STANDARD   2

Definition at line 234 of file miscadmin.h.

Referenced by DecodeInterval(), and EncodeInterval().

◆ InvalidPid

◆ IsBootstrapProcessingMode

◆ IsInitProcessingMode

#define IsInitProcessingMode ( )    (Mode == InitProcessing)

◆ IsNormalProcessingMode

#define IsNormalProcessingMode ( )    (Mode == NormalProcessing)

◆ MAXTZLEN

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

Definition at line 239 of file miscadmin.h.

Referenced by abstime2tm(), and EncodeDateTime().

◆ RESUME_CANCEL_INTERRUPTS

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

Definition at line 125 of file miscadmin.h.

Referenced by CopyGetData(), and SocketBackend().

◆ RESUME_INTERRUPTS

◆ SECURITY_LOCAL_USERID_CHANGE

◆ SECURITY_NOFORCE_RLS

#define SECURITY_NOFORCE_RLS   0x0004

Definition at line 299 of file miscadmin.h.

Referenced by InNoForceRLSOperation(), ri_PerformCheck(), and ri_PlanCheck().

◆ SECURITY_RESTRICTED_OPERATION

#define SECURITY_RESTRICTED_OPERATION   0x0002

◆ SetProcessingMode

#define SetProcessingMode (   mode)

◆ START_CRIT_SECTION

#define START_CRIT_SECTION ( )    (CritSectionCount++)

Definition at line 131 of file miscadmin.h.

Referenced by _bt_delitems_delete(), _bt_delitems_vacuum(), _bt_getroot(), _bt_insertonpg(), _bt_mark_page_halfdead(), _bt_newroot(), _bt_split(), _bt_unlink_halfdead_page(), _bt_update_meta_cleanup_info(), _hash_addovflpage(), _hash_doinsert(), _hash_expandtable(), _hash_freeovflpage(), _hash_splitbucket(), _hash_squeezebucket(), _hash_vacuum_one_page(), AbsorbFsyncRequests(), addLeafTuple(), brin_doinsert(), brin_doupdate(), brin_initialize_empty_new_buffer(), brinbuildempty(), brinRevmapDesummarizeRange(), CreateCheckPoint(), CreateEndOfRecoveryRecord(), createPostingTree(), CreateSlotOnDisk(), do_setval(), doPickSplit(), EndPrepare(), fill_seq_with_data(), FreeSpaceMapTruncateRel(), GenericXLogFinish(), GetNewMultiXactId(), ginbuild(), ginbuildempty(), ginbulkdelete(), ginDeletePage(), ginHeapTupleFastInsert(), ginPlaceToPage(), ginUpdateStats(), ginVacuumPostingTreeLeaf(), gistbuild(), gistbuildempty(), gistbulkdelete(), gistplacetopage(), gistvacuumpage(), hashbucketcleanup(), hashbulkdelete(), heap_abort_speculative(), heap_delete(), heap_finish_speculative(), heap_inplace_update(), heap_insert(), heap_lock_tuple(), heap_lock_updated_tuple_rec(), heap_multi_insert(), heap_page_prune(), heap_update(), lazy_scan_heap(), lazy_vacuum_page(), moveLeafs(), nextval_internal(), PostPrepare_Locks(), RecordTransactionAbort(), RecordTransactionAbortPrepared(), RecordTransactionCommit(), RecordTransactionCommitPrepared(), ReplicationSlotDropPtr(), RestoreSlotFromDisk(), revmap_physical_extend(), SaveSlotToPath(), shiftList(), SlruPhysicalWritePage(), spgAddNodeAction(), spgbuild(), spgSplitNodeAction(), TruncateMultiXact(), UpdateFullPageWrites(), vacuumLeafPage(), vacuumLeafRoot(), vacuumRedirectAndPlaceholder(), visibilitymap_set(), visibilitymap_truncate(), write_relmap_file(), writeListPage(), XLogBackgroundFlush(), XLogFlush(), and XLogInsertRecord().

◆ USE_GERMAN_DATES

#define USE_GERMAN_DATES   3

Definition at line 214 of file miscadmin.h.

Referenced by check_datestyle(), EncodeDateOnly(), and EncodeDateTime().

◆ USE_ISO_DATES

#define USE_ISO_DATES   1

◆ USE_POSTGRES_DATES

#define USE_POSTGRES_DATES   0

Definition at line 211 of file miscadmin.h.

Referenced by check_datestyle(), EncodeDateOnly(), and EncodeDateTime().

◆ USE_SQL_DATES

#define USE_SQL_DATES   2

Definition at line 213 of file miscadmin.h.

Referenced by check_datestyle(), EncodeDateOnly(), and EncodeDateTime().

◆ USE_XSD_DATES

#define USE_XSD_DATES   4

Typedef Documentation

◆ pg_stack_base_t

Definition at line 272 of file miscadmin.h.

◆ ProcessingMode

Enumeration Type Documentation

◆ AuxProcType

Enumerator
NotAnAuxProcess 
CheckerProcess 
BootstrapProcess 
StartupProcess 
BgWriterProcess 
CheckpointerProcess 
WalWriterProcess 
WalReceiverProcess 
NUM_AUXPROCTYPES 

Definition at line 393 of file miscadmin.h.

◆ ProcessingMode

Enumerator
BootstrapProcessing 
InitProcessing 
NormalProcessing 

Definition at line 363 of file miscadmin.h.

364 {
365  BootstrapProcessing, /* bootstrap creation of template database */
366  InitProcessing, /* initializing system */
367  NormalProcessing /* normal processing */
ProcessingMode
Definition: miscadmin.h:363

Function Documentation

◆ AddToDataDirLockFile()

void AddToDataDirLockFile ( int  target_line,
const char *  str 
)

Definition at line 1270 of file miscinit.c.

References close, DIRECTORY_LOCK_FILE, ereport, errcode_for_file_access(), errmsg(), fd(), LOG, PG_BINARY, pg_fsync(), pgstat_report_wait_end(), pgstat_report_wait_start(), read, snprintf(), WAIT_EVENT_LOCK_FILE_ADDTODATADIR_READ, WAIT_EVENT_LOCK_FILE_ADDTODATADIR_SYNC, WAIT_EVENT_LOCK_FILE_ADDTODATADIR_WRITE, and write.

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

1271 {
1272  int fd;
1273  int len;
1274  int lineno;
1275  char *srcptr;
1276  char *destptr;
1277  char srcbuffer[BLCKSZ];
1278  char destbuffer[BLCKSZ];
1279 
1280  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1281  if (fd < 0)
1282  {
1283  ereport(LOG,
1285  errmsg("could not open file \"%s\": %m",
1287  return;
1288  }
1290  len = read(fd, srcbuffer, sizeof(srcbuffer) - 1);
1292  if (len < 0)
1293  {
1294  ereport(LOG,
1296  errmsg("could not read from file \"%s\": %m",
1298  close(fd);
1299  return;
1300  }
1301  srcbuffer[len] = '\0';
1302 
1303  /*
1304  * Advance over lines we are not supposed to rewrite, then copy them to
1305  * destbuffer.
1306  */
1307  srcptr = srcbuffer;
1308  for (lineno = 1; lineno < target_line; lineno++)
1309  {
1310  char *eol = strchr(srcptr, '\n');
1311 
1312  if (eol == NULL)
1313  break; /* not enough lines in file yet */
1314  srcptr = eol + 1;
1315  }
1316  memcpy(destbuffer, srcbuffer, srcptr - srcbuffer);
1317  destptr = destbuffer + (srcptr - srcbuffer);
1318 
1319  /*
1320  * Fill in any missing lines before the target line, in case lines are
1321  * added to the file out of order.
1322  */
1323  for (; lineno < target_line; lineno++)
1324  {
1325  if (destptr < destbuffer + sizeof(destbuffer))
1326  *destptr++ = '\n';
1327  }
1328 
1329  /*
1330  * Write or rewrite the target line.
1331  */
1332  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s\n", str);
1333  destptr += strlen(destptr);
1334 
1335  /*
1336  * If there are more lines in the old file, append them to destbuffer.
1337  */
1338  if ((srcptr = strchr(srcptr, '\n')) != NULL)
1339  {
1340  srcptr++;
1341  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s",
1342  srcptr);
1343  }
1344 
1345  /*
1346  * And rewrite the data. Since we write in a single kernel call, this
1347  * update should appear atomic to onlookers.
1348  */
1349  len = strlen(destbuffer);
1350  errno = 0;
1352  if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
1353  (int) write(fd, destbuffer, len) != len)
1354  {
1356  /* if write didn't set errno, assume problem is no disk space */
1357  if (errno == 0)
1358  errno = ENOSPC;
1359  ereport(LOG,
1361  errmsg("could not write to file \"%s\": %m",
1363  close(fd);
1364  return;
1365  }
1368  if (pg_fsync(fd) != 0)
1369  {
1370  ereport(LOG,
1372  errmsg("could not write to file \"%s\": %m",
1374  }
1376  if (close(fd) != 0)
1377  {
1378  ereport(LOG,
1380  errmsg("could not write to file \"%s\": %m",
1382  }
1383 }
#define write(a, b, c)
Definition: win32.h:14
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:58
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define LOG
Definition: elog.h:26
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PG_BINARY
Definition: c.h:1139
int errcode_for_file_access(void)
Definition: elog.c:598
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1261
#define ereport(elevel, rest)
Definition: elog.h:141
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1237
int errmsg(const char *fmt,...)
Definition: elog.c:797
int pg_fsync(int fd)
Definition: fd.c:341
#define close(a)
Definition: win32.h:12
#define read(a, b, c)
Definition: win32.h:13

◆ BackupInProgress()

bool BackupInProgress ( void  )

Definition at line 11636 of file xlog.c.

References BACKUP_LABEL_FILE, and stat.

Referenced by pg_is_in_backup(), and PostmasterStateMachine().

11637 {
11638  struct stat stat_buf;
11639 
11640  return (stat(BACKUP_LABEL_FILE, &stat_buf) == 0);
11641 }
struct stat stat_buf
Definition: pg_standby.c:102
#define stat(a, b)
Definition: win32_port.h:266
#define BACKUP_LABEL_FILE
Definition: xlog.h:322

◆ BaseInit()

void BaseInit ( void  )

Definition at line 524 of file postinit.c.

References DebugFileOpen(), InitBufferPoolAccess(), InitCommunication(), InitFileAccess(), and smgrinit().

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

525 {
526  /*
527  * Attach to shared memory and semaphores, and initialize our
528  * input/output/debugging file descriptors.
529  */
531  DebugFileOpen();
532 
533  /* Do local initialization of file, storage and buffer managers */
534  InitFileAccess();
535  smgrinit();
537 }
static void InitCommunication(void)
Definition: postinit.c:416
void InitBufferPoolAccess(void)
Definition: bufmgr.c:2437
void DebugFileOpen(void)
Definition: elog.c:1863
void smgrinit(void)
Definition: smgr.c:117
void InitFileAccess(void)
Definition: fd.c:772

◆ CancelBackup()

void CancelBackup ( void  )

Definition at line 11656 of file xlog.c.

References BACKUP_LABEL_FILE, BACKUP_LABEL_OLD, DEBUG1, durable_rename(), ereport, errcode_for_file_access(), errdetail(), errmsg(), LOG, stat, TABLESPACE_MAP, TABLESPACE_MAP_OLD, and WARNING.

Referenced by PostmasterStateMachine().

11657 {
11658  struct stat stat_buf;
11659 
11660  /* if the backup_label file is not there, return */
11661  if (stat(BACKUP_LABEL_FILE, &stat_buf) < 0)
11662  return;
11663 
11664  /* remove leftover file from previously canceled backup if it exists */
11665  unlink(BACKUP_LABEL_OLD);
11666 
11668  {
11669  ereport(WARNING,
11671  errmsg("online backup mode was not canceled"),
11672  errdetail("File \"%s\" could not be renamed to \"%s\": %m.",
11674  return;
11675  }
11676 
11677  /* if the tablespace_map file is not there, return */
11678  if (stat(TABLESPACE_MAP, &stat_buf) < 0)
11679  {
11680  ereport(LOG,
11681  (errmsg("online backup mode canceled"),
11682  errdetail("File \"%s\" was renamed to \"%s\".",
11684  return;
11685  }
11686 
11687  /* remove leftover file from previously canceled backup if it exists */
11688  unlink(TABLESPACE_MAP_OLD);
11689 
11691  {
11692  ereport(LOG,
11693  (errmsg("online backup mode canceled"),
11694  errdetail("Files \"%s\" and \"%s\" were renamed to "
11695  "\"%s\" and \"%s\", respectively.",
11698  }
11699  else
11700  {
11701  ereport(WARNING,
11703  errmsg("online backup mode canceled"),
11704  errdetail("File \"%s\" was renamed to \"%s\", but "
11705  "file \"%s\" could not be renamed to \"%s\": %m.",
11708  }
11709 }
#define DEBUG1
Definition: elog.h:25
#define LOG
Definition: elog.h:26
#define BACKUP_LABEL_OLD
Definition: xlog.h:323
#define TABLESPACE_MAP
Definition: xlog.h:325
struct stat stat_buf
Definition: pg_standby.c:102
int errdetail(const char *fmt,...)
Definition: elog.c:873
int errcode_for_file_access(void)
Definition: elog.c:598
#define ereport(elevel, rest)
Definition: elog.h:141
int durable_rename(const char *oldfile, const char *newfile, int elevel)
Definition: fd.c:601
#define WARNING
Definition: elog.h:40
#define stat(a, b)
Definition: win32_port.h:266
#define TABLESPACE_MAP_OLD
Definition: xlog.h:326
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define BACKUP_LABEL_FILE
Definition: xlog.h:322

◆ ChangeToDataDir()

void ChangeToDataDir ( void  )

Definition at line 213 of file miscinit.c.

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

Referenced by AuxiliaryProcessMain(), PostgresMain(), and PostmasterMain().

214 {
216 
217  if (chdir(DataDir) < 0)
218  ereport(FATAL,
220  errmsg("could not change directory to \"%s\": %m",
221  DataDir)));
222 }
#define AssertState(condition)
Definition: c.h:735
#define FATAL
Definition: elog.h:52
int errcode_for_file_access(void)
Definition: elog.c:598
#define ereport(elevel, rest)
Definition: elog.h:141
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * DataDir
Definition: globals.c:61

◆ check_stack_depth()

void check_stack_depth ( void  )

Definition at line 3226 of file postgres.c.

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

Referenced by apply_scanjoin_target_to_paths(), clean_NOT_intree(), clean_stopword_intree(), cntsize(), contains_required_value(), convertJsonbValue(), copyObjectImpl(), Cover(), create_plan_recurse(), datum_to_json(), datum_to_jsonb(), dofindsubquery(), EventTriggerInvoke(), ExecEndNode(), ExecEvalAlternativeSubPlan(), ExecEvalSubPlan(), ExecInitExprRec(), ExecInitNode(), ExecMakeFunctionResultSet(), ExecProcNodeFirst(), ExecShutdownNode(), execute(), expand_partitioned_rtentry(), expression_tree_mutator(), expression_tree_walker(), fillQT(), find_composite_type_dependencies(), find_matching_subplans_recurse(), findoprnd(), findoprnd_recurse(), flatten_grouping_sets(), FreePageManagerDumpBtree(), freetree(), generate_partition_qual(), generate_partitionwise_join_paths(), get_partition_dispatch_recurse(), get_query_def(), get_rels_with_domain(), get_rule_expr(), get_setop_query(), get_steps_using_prefix_recurse(), gistSplit(), hash_range(), hash_range_extended(), hk_depth_search(), infix(), inline_set_returning_function(), int_query_opr_selec(), JsonbDeepContains(), JumbleExpr(), ltree_execute(), makepol(), maketree(), MatchText(), MultiExecProcNode(), parse_array(), parse_object(), plainnode(), plperl_hash_from_tuple(), plperl_sv_to_datum(), PLy_input_setup_func(), PLy_output_setup_func(), populate_array_dim_jsonb(), populate_record_field(), QT2QTN(), QTNBinary(), QTNClearFlags(), QTNCopy(), QTNFree(), QTNodeCompare(), QTNSort(), QTNTernary(), range_cmp(), range_in(), range_out(), range_recv(), range_send(), raw_expression_tree_walker(), record_cmp(), record_eq(), record_in(), record_out(), record_recv(), record_send(), recurse_set_operations(), set_append_rel_size(), setPath(), split_array(), transformExprRecurse(), transformSetOperationTree(), traverse_lacons(), try_partitionwise_join(), TS_execute(), TS_execute_ternary(), TS_phrase_execute(), tsquery_opr_selec(), and tsquery_requires_match().

3227 {
3228  if (stack_is_too_deep())
3229  {
3230  ereport(ERROR,
3231  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3232  errmsg("stack depth limit exceeded"),
3233  errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3234  "after ensuring the platform's stack depth limit is adequate.",
3235  max_stack_depth)));
3236  }
3237 }
int errhint(const char *fmt,...)
Definition: elog.c:987
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
int max_stack_depth
Definition: postgres.c:98
int errmsg(const char *fmt,...)
Definition: elog.c:797
bool stack_is_too_deep(void)
Definition: postgres.c:3240

◆ checkDataDir()

void checkDataDir ( void  )

Definition at line 99 of file miscinit.c.

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, and ValidatePgVersion().

Referenced by AuxiliaryProcessMain(), BackendRun(), PostgresMain(), and PostmasterMain().

100 {
101  struct stat stat_buf;
102 
103  Assert(DataDir);
104 
105  if (stat(DataDir, &stat_buf) != 0)
106  {
107  if (errno == ENOENT)
108  ereport(FATAL,
110  errmsg("data directory \"%s\" does not exist",
111  DataDir)));
112  else
113  ereport(FATAL,
115  errmsg("could not read permissions of directory \"%s\": %m",
116  DataDir)));
117  }
118 
119  /* eventual chdir would fail anyway, but let's test ... */
120  if (!S_ISDIR(stat_buf.st_mode))
121  ereport(FATAL,
122  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
123  errmsg("specified data directory \"%s\" is not a directory",
124  DataDir)));
125 
126  /*
127  * Check that the directory belongs to my userid; if not, reject.
128  *
129  * This check is an essential part of the interlock that prevents two
130  * postmasters from starting in the same directory (see CreateLockFile()).
131  * Do not remove or weaken it.
132  *
133  * XXX can we safely enable this check on Windows?
134  */
135 #if !defined(WIN32) && !defined(__CYGWIN__)
136  if (stat_buf.st_uid != geteuid())
137  ereport(FATAL,
138  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
139  errmsg("data directory \"%s\" has wrong ownership",
140  DataDir),
141  errhint("The server must be started by the user that owns the data directory.")));
142 #endif
143 
144  /*
145  * Check if the directory has correct permissions. If not, reject.
146  *
147  * Only two possible modes are allowed, 0700 and 0750. The latter mode
148  * indicates that group read/execute should be allowed on all newly
149  * created files and directories.
150  *
151  * XXX temporarily suppress check when on Windows, because there may not
152  * be proper support for Unix-y file permissions. Need to think of a
153  * reasonable check to apply on Windows.
154  */
155 #if !defined(WIN32) && !defined(__CYGWIN__)
156  if (stat_buf.st_mode & PG_MODE_MASK_GROUP)
157  ereport(FATAL,
158  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
159  errmsg("data directory \"%s\" has invalid permissions",
160  DataDir),
161  errdetail("Permissions should be u=rwx (0700) or u=rwx,g=rx (0750).")));
162 #endif
163 
164  /*
165  * Reset creation modes and mask based on the mode of the data directory.
166  *
167  * The mask was set earlier in startup to disallow group permissions on
168  * newly created files and directories. However, if group read/execute
169  * are present on the data directory then modify the create modes and mask
170  * to allow group read/execute on newly created files and directories and
171  * set the data_directory_mode GUC.
172  *
173  * Suppress when on Windows, because there may not be proper support for
174  * Unix-y file permissions.
175  */
176 #if !defined(WIN32) && !defined(__CYGWIN__)
178 
179  umask(pg_mode_mask);
181 #endif
182 
183  /* Check for PG_VERSION */
185 }
int errhint(const char *fmt,...)
Definition: elog.c:987
void ValidatePgVersion(const char *path)
Definition: miscinit.c:1470
int errcode(int sqlerrcode)
Definition: elog.c:575
#define PG_MODE_MASK_GROUP
Definition: file_perm.h:29
struct stat stat_buf
Definition: pg_standby.c:102
#define FATAL
Definition: elog.h:52
int errdetail(const char *fmt,...)
Definition: elog.c:873
int errcode_for_file_access(void)
Definition: elog.c:598
#define ereport(elevel, rest)
Definition: elog.h:141
#define stat(a, b)
Definition: win32_port.h:266
int pg_dir_create_mode
Definition: file_perm.c:18
#define Assert(condition)
Definition: c.h:732
#define S_ISDIR(m)
Definition: win32_port.h:307
int errmsg(const char *fmt,...)
Definition: elog.c:797
int data_directory_mode
Definition: globals.c:67
void SetDataDirectoryCreatePerm(int dataDirMode)
Definition: file_perm.c:34
char * DataDir
Definition: globals.c:61
int pg_mode_mask
Definition: file_perm.c:25

◆ CreateDataDirLockFile()

void CreateDataDirLockFile ( bool  amPostmaster)

Definition at line 1193 of file miscinit.c.

References CreateLockFile(), DataDir, and DIRECTORY_LOCK_FILE.

Referenced by AuxiliaryProcessMain(), PostgresMain(), and PostmasterMain().

1194 {
1195  CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, "", true, DataDir);
1196 }
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:58
static void CreateLockFile(const char *filename, bool amPostmaster, const char *socketDir, bool isDDLock, const char *refName)
Definition: miscinit.c:884
char * DataDir
Definition: globals.c:61

◆ CreateSocketLockFile()

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

Definition at line 1202 of file miscinit.c.

References CreateLockFile(), MAXPGPATH, and snprintf().

Referenced by StreamServerPort().

1204 {
1205  char lockfile[MAXPGPATH];
1206 
1207  snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
1208  CreateLockFile(lockfile, amPostmaster, socketDir, false, socketfile);
1209 }
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
static void CreateLockFile(const char *filename, bool amPostmaster, const char *socketDir, bool isDDLock, const char *refName)
Definition: miscinit.c:884
#define MAXPGPATH

◆ GetAuthenticatedUserId()

Oid GetAuthenticatedUserId ( void  )

Definition at line 451 of file miscinit.c.

References AssertState, AuthenticatedUserId, and OidIsValid.

Referenced by InitializeParallelDSM().

452 {
454  return AuthenticatedUserId;
455 }
#define AssertState(condition)
Definition: c.h:735
#define OidIsValid(objectId)
Definition: c.h:638
static Oid AuthenticatedUserId
Definition: miscinit.c:253

◆ GetCurrentRoleId()

Oid GetCurrentRoleId ( void  )

Definition at line 751 of file miscinit.c.

References InvalidOid, OuterUserId, and SetRoleIsActive.

Referenced by InitializeParallelDSM(), and show_role().

752 {
753  if (SetRoleIsActive)
754  return OuterUserId;
755  else
756  return InvalidOid;
757 }
static Oid OuterUserId
Definition: miscinit.c:255
#define InvalidOid
Definition: postgres_ext.h:36
static bool SetRoleIsActive
Definition: miscinit.c:265

◆ GetOuterUserId()

Oid GetOuterUserId ( void  )

Definition at line 403 of file miscinit.c.

References AssertState, OidIsValid, and OuterUserId.

Referenced by DropRole(), and RenameRole().

404 {
406  return OuterUserId;
407 }
#define AssertState(condition)
Definition: c.h:735
static Oid OuterUserId
Definition: miscinit.c:255
#define OidIsValid(objectId)
Definition: c.h:638

◆ GetSessionUserId()

Oid GetSessionUserId ( void  )

Definition at line 426 of file miscinit.c.

References AssertState, OidIsValid, and SessionUserId.

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

427 {
429  return SessionUserId;
430 }
#define AssertState(condition)
Definition: c.h:735
static Oid SessionUserId
Definition: miscinit.c:254
#define OidIsValid(objectId)
Definition: c.h:638

◆ GetUserId()

Oid GetUserId ( void  )

Definition at line 392 of file miscinit.c.

References AssertState, CurrentUserId, and OidIsValid.

Referenced by AddRoleMems(), AggregateCreate(), AlterCollation(), AlterDatabase(), AlterDatabaseOwner(), AlterDatabaseSet(), AlterEventTrigger(), AlterEventTriggerOwner_internal(), AlterExtensionNamespace(), AlterForeignServer(), AlterForeignServerOwner_internal(), AlterFunction(), AlterObjectNamespace_internal(), AlterObjectOwner_internal(), AlterObjectRename_internal(), AlterOperator(), AlterOpFamilyAdd(), AlterPublication(), AlterPublicationOwner_internal(), AlterRole(), AlterRoleSet(), AlterSchemaOwner_internal(), AlterSubscription(), AlterSubscriptionOwner_internal(), AlterTableMoveAll(), AlterTableSpaceOptions(), AlterTSConfiguration(), AlterTSDictionary(), AlterTypeNamespace_oid(), AlterTypeOwner(), ATExecAddColumn(), ATExecChangeOwner(), ATPrepAlterColumnType(), ATPrepSetStatistics(), ATPrepSetTableSpace(), ATSimplePermissions(), be_lo_put(), be_lo_unlink(), binary_upgrade_create_empty_extension(), brin_desummarize_range(), brin_summarize_range(), BuildCachedPlan(), BuildDescForRelation(), BuildIndexValueDescription(), calculate_database_size(), calculate_tablespace_size(), call_pltcl_start_proc(), check_enable_rls(), check_permissions(), check_temp_tablespaces(), CheckCachedPlan(), checkDomainOwner(), checkEnumOwner(), checkFkeyPermissions(), CheckFunctionValidatorAccess(), CheckMyDatabase(), cluster_rel(), 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(), CreateRole(), CreateStatistics(), CreateSubscription(), CreateTableSpace(), CreateTransform(), CreateTrigger(), current_user(), currtid_byrelname(), currtid_byreloid(), 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(), EnableDisableRule(), examine_simple_variable(), examine_variable(), ExecAlterDefaultPrivilegesStmt(), ExecAlterExtensionContentsStmt(), ExecAlterExtensionStmt(), ExecBuildGroupingEqual(), ExecBuildSlotPartitionKeyDescription(), ExecBuildSlotValueDescription(), ExecCheckRTEPerms(), ExecGrant_Attribute(), ExecGrant_Database(), ExecGrant_Fdw(), ExecGrant_ForeignServer(), ExecGrant_Function(), ExecGrant_Language(), ExecGrant_Largeobject(), ExecGrant_Namespace(), ExecGrant_Relation(), ExecGrant_Tablespace(), ExecGrant_Type(), ExecInitAgg(), ExecInitExprRec(), ExecInitFunc(), ExecInitWindowAgg(), ExecSecLabelStmt(), ExecuteCallStmt(), ExecuteDoStmt(), ExecuteTruncateGuts(), file_fdw_validator(), findRangeCanonicalFunction(), findRangeSubtypeDiffFunction(), FinishPreparedTransaction(), get_connect_string(), get_other_operator(), get_rel_from_relname(), get_rolespec_oid(), get_rolespec_tuple(), get_row_security_policies(), get_tables_to_cluster(), GetConfigOption(), GetConfigOptionByName(), GetConfigOptionByNum(), GetConfigOptionResetString(), gin_clean_pending_list(), GrantRole(), HandleFunctionRequest(), has_any_column_privilege_id(), has_any_column_privilege_name(), has_column_privilege_id_attnum(), has_column_privilege_id_name(), has_column_privilege_name_attnum(), has_column_privilege_name_name(), has_database_privilege_id(), has_database_privilege_name(), has_foreign_data_wrapper_privilege_id(), has_foreign_data_wrapper_privilege_name(), has_function_privilege_id(), has_function_privilege_name(), has_language_privilege_id(), has_language_privilege_name(), has_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(), ImportForeignSchema(), init_sexpr(), InitializeSearchPath(), InitPostgres(), InitTempTableNamespace(), inline_function(), inline_set_returning_function(), insert_username(), interpret_function_parameter_list(), inv_create(), inv_open(), LargeObjectCreate(), lastval(), LockTableCommand(), 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_activity(), pg_stat_get_backend_activity(), pg_stat_get_backend_activity_start(), pg_stat_get_backend_client_addr(), pg_stat_get_backend_client_port(), pg_stat_get_backend_start(), pg_stat_get_backend_wait_event(), pg_stat_get_backend_wait_event_type(), pg_stat_get_backend_xact_start(), pg_stat_get_progress_info(), 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(), postgresGetForeignRelSize(), postgresImportForeignSchema(), PrepareTempTablespaces(), PrepareTransaction(), PublicationAddTables(), RangeVarCallbackForAlterRelation(), RangeVarCallbackForDropRelation(), RangeVarCallbackForLockTable(), RangeVarCallbackForPolicy(), RangeVarCallbackForReindexIndex(), RangeVarCallbackForRenameRule(), RangeVarCallbackForRenameTrigger(), RangeVarCallbackOwnsRelation(), RangeVarCallbackOwnsTable(), RangeVarGetAndCheckCreationNamespace(), ReassignOwnedObjects(), recomputeNamespacePath(), ReindexMultipleTables(), RemoveObjects(), RemoveRoleFromObjectPolicy(), renameatt_check(), RenameDatabase(), RenameSchema(), RenameTableSpace(), RenameType(), RevalidateCachedQuery(), RI_Initial_Check(), ri_ReportViolation(), select_perl_context(), set_foreign_rel_properties(), ShowAllGUCConfig(), superuser(), timetravel(), transformTableLikeClause(), truncate_check_rel(), user_mapping_ddl_aclcheck(), vacuum_is_relation_owner(), ValidateJoinEstimator(), and ValidateRestrictionEstimator().

393 {
395  return CurrentUserId;
396 }
#define AssertState(condition)
Definition: c.h:735
#define OidIsValid(objectId)
Definition: c.h:638
static Oid CurrentUserId
Definition: miscinit.c:256

◆ GetUserIdAndContext()

void GetUserIdAndContext ( Oid userid,
bool sec_def_context 
)

Definition at line 546 of file miscinit.c.

References CurrentUserId, and InLocalUserIdChange().

547 {
548  *userid = CurrentUserId;
549  *sec_def_context = InLocalUserIdChange();
550 }
bool InLocalUserIdChange(void)
Definition: miscinit.c:515
static Oid CurrentUserId
Definition: miscinit.c:256

◆ GetUserIdAndSecContext()

void GetUserIdAndSecContext ( Oid userid,
int *  sec_context 
)

◆ GetUserNameFromId()

char* GetUserNameFromId ( Oid  roleid,
bool  noerr 
)

Definition at line 807 of file miscinit.c.

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

Referenced by check_is_member_of_role(), current_user(), getObjectDescription(), getObjectIdentityParts(), insert_username(), regroleout(), RemoveRoleFromObjectPolicy(), session_user(), and timetravel().

808 {
809  HeapTuple tuple;
810  char *result;
811 
812  tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
813  if (!HeapTupleIsValid(tuple))
814  {
815  if (!noerr)
816  ereport(ERROR,
817  (errcode(ERRCODE_UNDEFINED_OBJECT),
818  errmsg("invalid role OID: %u", roleid)));
819  result = NULL;
820  }
821  else
822  {
823  result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
824  ReleaseSysCache(tuple);
825  }
826  return result;
827 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
char * pstrdup(const char *in)
Definition: mcxt.c:1161
int errcode(int sqlerrcode)
Definition: elog.c:575
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:55
#define ObjectIdGetDatum(X)
Definition: postgres.h:492
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define NameStr(name)
Definition: c.h:609

◆ has_rolreplication()

bool has_rolreplication ( Oid  roleid)

Definition at line 573 of file miscinit.c.

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

Referenced by check_permissions(), and InitPostgres().

574 {
575  bool result = false;
576  HeapTuple utup;
577 
578  utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
579  if (HeapTupleIsValid(utup))
580  {
581  result = ((Form_pg_authid) GETSTRUCT(utup))->rolreplication;
582  ReleaseSysCache(utup);
583  }
584  return result;
585 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:55
#define ObjectIdGetDatum(X)
Definition: postgres.h:492
bool rolreplication
Definition: pg_authid.h:39
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
#define HeapTupleIsValid(tuple)
Definition: htup.h:78

◆ InitializeMaxBackends()

void InitializeMaxBackends ( void  )

Definition at line 502 of file postinit.c.

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

Referenced by AuxiliaryProcessMain(), PostgresMain(), and PostmasterMain().

503 {
504  Assert(MaxBackends == 0);
505 
506  /* the extra unit accounts for the autovacuum launcher */
509 
510  /* internal error because the values were all checked previously */
512  elog(ERROR, "too many backends configured");
513 }
#define ERROR
Definition: elog.h:43
#define MAX_BACKENDS
Definition: postmaster.h:75
int MaxBackends
Definition: globals.c:134
int MaxConnections
Definition: globals.c:131
int autovacuum_max_workers
Definition: autovacuum.c:114
#define Assert(condition)
Definition: c.h:732
#define elog(elevel,...)
Definition: elog.h:226
int max_worker_processes
Definition: globals.c:132

◆ InitializeSessionUserId()

void InitializeSessionUserId ( const char *  rolename,
Oid  useroid 
)

Definition at line 591 of file miscinit.c.

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

Referenced by InitPostgres().

592 {
593  HeapTuple roleTup;
594  Form_pg_authid rform;
595  char *rname;
596 
597  /*
598  * Don't do scans if we're bootstrapping, none of the system catalogs
599  * exist yet, and they should be owned by postgres anyway.
600  */
602 
603  /* call only once */
605 
606  /*
607  * Make sure syscache entries are flushed for recent catalog changes.
608  * This allows us to find roles that were created on-the-fly during
609  * authentication.
610  */
612 
613  if (rolename != NULL)
614  {
615  roleTup = SearchSysCache1(AUTHNAME, PointerGetDatum(rolename));
616  if (!HeapTupleIsValid(roleTup))
617  ereport(FATAL,
618  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
619  errmsg("role \"%s\" does not exist", rolename)));
620  }
621  else
622  {
623  roleTup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
624  if (!HeapTupleIsValid(roleTup))
625  ereport(FATAL,
626  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
627  errmsg("role with OID %u does not exist", roleid)));
628  }
629 
630  rform = (Form_pg_authid) GETSTRUCT(roleTup);
631  roleid = HeapTupleGetOid(roleTup);
632  rname = NameStr(rform->rolname);
633 
634  AuthenticatedUserId = roleid;
635  AuthenticatedUserIsSuperuser = rform->rolsuper;
636 
637  /* This sets OuterUserId/CurrentUserId too */
639 
640  /* Also mark our PGPROC entry with the authenticated user id */
641  /* (We assume this is an atomic store so no lock is needed) */
642  MyProc->roleId = roleid;
643 
644  /*
645  * These next checks are not enforced when in standalone mode, so that
646  * there is a way to recover from sillinesses like "UPDATE pg_authid SET
647  * rolcanlogin = false;".
648  */
649  if (IsUnderPostmaster)
650  {
651  /*
652  * Is role allowed to login at all?
653  */
654  if (!rform->rolcanlogin)
655  ereport(FATAL,
656  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
657  errmsg("role \"%s\" is not permitted to log in",
658  rname)));
659 
660  /*
661  * Check connection limit for this role.
662  *
663  * There is a race condition here --- we create our PGPROC before
664  * checking for other PGPROCs. If two backends did this at about the
665  * same time, they might both think they were over the limit, while
666  * ideally one should succeed and one fail. Getting that to work
667  * exactly seems more trouble than it is worth, however; instead we
668  * just document that the connection limit is approximate.
669  */
670  if (rform->rolconnlimit >= 0 &&
672  CountUserBackends(roleid) > rform->rolconnlimit)
673  ereport(FATAL,
674  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
675  errmsg("too many connections for role \"%s\"",
676  rname)));
677  }
678 
679  /* Record username and superuser status as GUC settings too */
680  SetConfigOption("session_authorization", rname,
682  SetConfigOption("is_superuser",
683  AuthenticatedUserIsSuperuser ? "on" : "off",
685 
686  ReleaseSysCache(roleTup);
687 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
#define AssertState(condition)
Definition: c.h:735
void AcceptInvalidationMessages(void)
Definition: inval.c:679
PGPROC * MyProc
Definition: proc.c:67
#define PointerGetDatum(X)
Definition: postgres.h:541
Oid roleId
Definition: proc.h:115
int errcode(int sqlerrcode)
Definition: elog.c:575
#define OidIsValid(objectId)
Definition: c.h:638
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:55
#define ObjectIdGetDatum(X)
Definition: postgres.h:492
#define FATAL
Definition: elog.h:52
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6952
bool IsUnderPostmaster
Definition: globals.c:108
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:259
#define ereport(elevel, rest)
Definition: elog.h:141
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
int CountUserBackends(Oid roleid)
Definition: procarray.c:2842
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:372
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define NameStr(name)
Definition: c.h:609
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:707
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:434
static Oid AuthenticatedUserId
Definition: miscinit.c:253

◆ InitializeSessionUserIdStandalone()

void InitializeSessionUserIdStandalone ( void  )

Definition at line 694 of file miscinit.c.

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

Referenced by InitPostgres().

695 {
696  /*
697  * This function should only be called in single-user mode, in autovacuum
698  * workers, and in background workers.
699  */
701 
702  /* call only once */
704 
705  AuthenticatedUserId = BOOTSTRAP_SUPERUSERID;
707 
708  SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
709 }
#define AssertState(condition)
Definition: c.h:735
#define OidIsValid(objectId)
Definition: c.h:638
bool IsBackgroundWorker
Definition: globals.c:110
bool IsUnderPostmaster
Definition: globals.c:108
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:259
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3285
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:434
static Oid AuthenticatedUserId
Definition: miscinit.c:253

◆ InitPostgres()

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

Definition at line 565 of file postinit.c.

References am_db_walsender, am_walsender, Assert, before_shmem_exit(), CAC_WAITBACKUP, Port::canAcceptConnections, CheckDeadLockAlert(), CheckMyDatabase(), CommitTransactionCommand(), CreateAuxProcessResourceOwner(), CurrentResourceOwner, PGPROC::databaseId, dattablespace, 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(), HeapTupleGetOid, HeapTupleIsValid, IDLE_IN_TRANSACTION_SESSION_TIMEOUT, IdleInTransactionSessionTimeoutHandler(), InitBufferPoolBackend(), InitCatalogCache(), initialize_acl(), InitializeClientEncoding(), InitializeSearchPath(), InitializeSession(), InitializeSessionUserId(), InitializeSessionUserIdStandalone(), InitPlanCache(), InitProcessPhase2(), InvalidateCatalogSnapshot(), InvalidBackendId, IsAutoVacuumLauncherProcess(), IsAutoVacuumWorkerProcess(), IsBackgroundWorker, IsBinaryUpgrade, IsBootstrapProcessingMode, IsUnderPostmaster, LOCK_TIMEOUT, LockSharedObject(), LockTimeoutHandler(), MaxBackends, MyBackendId, MyDatabaseId, MyDatabaseTableSpace, MyProc, MyProcPort, NAMEDATALEN, NameStr, OidIsValid, on_shmem_exit(), PerformAuthentication(), pg_usleep(), pgstat_bestart(), pgstat_initialize(), PostAuthDelay, process_settings(), process_startup_options(), ProcSignalInit(), RecoveryInProgress(), RegisterTimeout(), RelationCacheInitialize(), RelationCacheInitializePhase2(), RelationCacheInitializePhase3(), ReleaseAuxProcessResources(), ReservedBackends, RowExclusiveLock, SetCurrentStatementStartTimestamp(), SetDatabasePath(), SharedInvalBackendInit(), ShutdownPostgres(), ShutdownXLOG(), StartTransactionCommand(), StartupXLOG(), STATEMENT_TIMEOUT, StatementTimeoutHandler(), strlcpy(), superuser(), ThereIsAtLeastOneRole(), ValidatePgVersion(), WARNING, XACT_READ_COMMITTED, and XactIsoLevel.

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

567 {
568  bool bootstrap = IsBootstrapProcessingMode();
569  bool am_superuser;
570  char *fullpath;
571  char dbname[NAMEDATALEN];
572 
573  elog(DEBUG3, "InitPostgres");
574 
575  /*
576  * Add my PGPROC struct to the ProcArray.
577  *
578  * Once I have done this, I am visible to other backends!
579  */
581 
582  /*
583  * Initialize my entry in the shared-invalidation manager's array of
584  * per-backend data.
585  *
586  * Sets up MyBackendId, a unique backend identifier.
587  */
589 
590  SharedInvalBackendInit(false);
591 
592  if (MyBackendId > MaxBackends || MyBackendId <= 0)
593  elog(FATAL, "bad backend ID: %d", MyBackendId);
594 
595  /* Now that we have a BackendId, we can participate in ProcSignal */
597 
598  /*
599  * Also set up timeout handlers needed for backend operation. We need
600  * these in every case except bootstrap.
601  */
602  if (!bootstrap)
603  {
609  }
610 
611  /*
612  * bufmgr needs another initialization call too
613  */
615 
616  /*
617  * Initialize local process's access to XLOG.
618  */
619  if (IsUnderPostmaster)
620  {
621  /*
622  * The postmaster already started the XLOG machinery, but we need to
623  * call InitXLOGAccess(), if the system isn't in hot-standby mode.
624  * This is handled by calling RecoveryInProgress and ignoring the
625  * result.
626  */
627  (void) RecoveryInProgress();
628  }
629  else
630  {
631  /*
632  * We are either a bootstrap process or a standalone backend. Either
633  * way, start up the XLOG machinery, and register to have it closed
634  * down at exit.
635  *
636  * We don't yet have an aux-process resource owner, but StartupXLOG
637  * and ShutdownXLOG will need one. Hence, create said resource owner
638  * (and register a callback to clean it up after ShutdownXLOG runs).
639  */
641 
642  StartupXLOG();
643  /* Release (and warn about) any buffer pins leaked in StartupXLOG */
645  /* Reset CurrentResourceOwner to nothing for the moment */
646  CurrentResourceOwner = NULL;
647 
649  }
650 
651  /*
652  * Initialize the relation cache and the system catalog caches. Note that
653  * no catalog access happens here; we only set up the hashtable structure.
654  * We must do this before starting a transaction because transaction abort
655  * would try to touch these hashtables.
656  */
659  InitPlanCache();
660 
661  /* Initialize portal manager */
663 
664  /* Initialize stats collection --- must happen before first xact */
665  if (!bootstrap)
667 
668  /*
669  * Load relcache entries for the shared system catalogs. This must create
670  * at least entries for pg_database and catalogs used for authentication.
671  */
673 
674  /*
675  * Set up process-exit callback to do pre-shutdown cleanup. This is the
676  * first before_shmem_exit callback we register; thus, this will be the
677  * last thing we do before low-level modules like the buffer manager begin
678  * to close down. We need to have this in place before we begin our first
679  * transaction --- if we fail during the initialization transaction, as is
680  * entirely possible, we need the AbortTransaction call to clean up.
681  */
683 
684  /* The autovacuum launcher is done here */
686  {
687  /* report this backend in the PgBackendStatus array */
688  pgstat_bestart();
689 
690  return;
691  }
692 
693  /*
694  * Start a new transaction here before first access to db, and get a
695  * snapshot. We don't have a use for the snapshot itself, but we're
696  * interested in the secondary effect that it sets RecentGlobalXmin. (This
697  * is critical for anything that reads heap pages, because HOT may decide
698  * to prune them even if the process doesn't attempt to modify any
699  * tuples.)
700  */
701  if (!bootstrap)
702  {
703  /* statement_timestamp must be set for timeouts to work correctly */
706 
707  /*
708  * transaction_isolation will have been set to the default by the
709  * above. If the default is "serializable", and we are in hot
710  * standby, we will fail if we don't change it to something lower.
711  * Fortunately, "read committed" is plenty good enough.
712  */
714 
715  (void) GetTransactionSnapshot();
716  }
717 
718  /*
719  * Perform client authentication if necessary, then figure out our
720  * postgres user ID, and see if we are a superuser.
721  *
722  * In standalone mode and in autovacuum worker processes, we use a fixed
723  * ID, otherwise we figure it out from the authenticated user name.
724  */
725  if (bootstrap || IsAutoVacuumWorkerProcess())
726  {
728  am_superuser = true;
729  }
730  else if (!IsUnderPostmaster)
731  {
733  am_superuser = true;
734  if (!ThereIsAtLeastOneRole())
736  (errcode(ERRCODE_UNDEFINED_OBJECT),
737  errmsg("no roles are defined in this database system"),
738  errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
739  username != NULL ? username : "postgres")));
740  }
741  else if (IsBackgroundWorker)
742  {
743  if (username == NULL && !OidIsValid(useroid))
744  {
746  am_superuser = true;
747  }
748  else
749  {
751  am_superuser = superuser();
752  }
753  }
754  else
755  {
756  /* normal multiuser case */
757  Assert(MyProcPort != NULL);
760  am_superuser = superuser();
761  }
762 
763  /*
764  * If we're trying to shut down, only superusers can connect, and new
765  * replication connections are not allowed.
766  */
767  if ((!am_superuser || am_walsender) &&
768  MyProcPort != NULL &&
770  {
771  if (am_walsender)
772  ereport(FATAL,
773  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
774  errmsg("new replication connections are not allowed during database shutdown")));
775  else
776  ereport(FATAL,
777  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
778  errmsg("must be superuser to connect during database shutdown")));
779  }
780 
781  /*
782  * Binary upgrades only allowed super-user connections
783  */
784  if (IsBinaryUpgrade && !am_superuser)
785  {
786  ereport(FATAL,
787  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
788  errmsg("must be superuser to connect in binary upgrade mode")));
789  }
790 
791  /*
792  * The last few connection slots are reserved for superusers. Although
793  * replication connections currently require superuser privileges, we
794  * don't allow them to consume the reserved slots, which are intended for
795  * interactive use.
796  */
797  if ((!am_superuser || am_walsender) &&
798  ReservedBackends > 0 &&
800  ereport(FATAL,
801  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
802  errmsg("remaining connection slots are reserved for non-replication superuser connections")));
803 
804  /* Check replication permissions needed for walsender processes. */
805  if (am_walsender)
806  {
807  Assert(!bootstrap);
808 
809  if (!superuser() && !has_rolreplication(GetUserId()))
810  ereport(FATAL,
811  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
812  errmsg("must be superuser or replication role to start walsender")));
813  }
814 
815  /*
816  * If this is a plain walsender only supporting physical replication, we
817  * don't want to connect to any particular database. Just finish the
818  * backend startup by processing any options from the startup packet, and
819  * we're done.
820  */
822  {
823  /* process any options passed in the startup packet */
824  if (MyProcPort != NULL)
825  process_startup_options(MyProcPort, am_superuser);
826 
827  /* Apply PostAuthDelay as soon as we've read all options */
828  if (PostAuthDelay > 0)
829  pg_usleep(PostAuthDelay * 1000000L);
830 
831  /* initialize client encoding */
833 
834  /* report this backend in the PgBackendStatus array */
835  pgstat_bestart();
836 
837  /* close the transaction we started above */
839 
840  return;
841  }
842 
843  /*
844  * Set up the global variables holding database id and default tablespace.
845  * But note we won't actually try to touch the database just yet.
846  *
847  * We take a shortcut in the bootstrap case, otherwise we have to look up
848  * the db's entry in pg_database.
849  */
850  if (bootstrap)
851  {
852  MyDatabaseId = TemplateDbOid;
853  MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
854  }
855  else if (in_dbname != NULL)
856  {
857  HeapTuple tuple;
858  Form_pg_database dbform;
859 
860  tuple = GetDatabaseTuple(in_dbname);
861  if (!HeapTupleIsValid(tuple))
862  ereport(FATAL,
863  (errcode(ERRCODE_UNDEFINED_DATABASE),
864  errmsg("database \"%s\" does not exist", in_dbname)));
865  dbform = (Form_pg_database) GETSTRUCT(tuple);
866  MyDatabaseId = HeapTupleGetOid(tuple);
867  MyDatabaseTableSpace = dbform->dattablespace;
868  /* take database name from the caller, just for paranoia */
869  strlcpy(dbname, in_dbname, sizeof(dbname));
870  }
871  else if (OidIsValid(dboid))
872  {
873  /* caller specified database by OID */
874  HeapTuple tuple;
875  Form_pg_database dbform;
876 
877  tuple = GetDatabaseTupleByOid(dboid);
878  if (!HeapTupleIsValid(tuple))
879  ereport(FATAL,
880  (errcode(ERRCODE_UNDEFINED_DATABASE),
881  errmsg("database %u does not exist", dboid)));
882  dbform = (Form_pg_database) GETSTRUCT(tuple);
883  MyDatabaseId = HeapTupleGetOid(tuple);
884  MyDatabaseTableSpace = dbform->dattablespace;
885  Assert(MyDatabaseId == dboid);
886  strlcpy(dbname, NameStr(dbform->datname), sizeof(dbname));
887  /* pass the database name back to the caller */
888  if (out_dbname)
889  strcpy(out_dbname, dbname);
890  }
891  else
892  {
893  /*
894  * If this is a background worker not bound to any particular
895  * database, we're done now. Everything that follows only makes sense
896  * if we are bound to a specific database. We do need to close the
897  * transaction we started before returning.
898  */
899  if (!bootstrap)
900  {
901  pgstat_bestart();
903  }
904  return;
905  }
906 
907  /*
908  * Now, take a writer's lock on the database we are trying to connect to.
909  * If there is a concurrently running DROP DATABASE on that database, this
910  * will block us until it finishes (and has committed its update of
911  * pg_database).
912  *
913  * Note that the lock is not held long, only until the end of this startup
914  * transaction. This is OK since we will advertise our use of the
915  * database in the ProcArray before dropping the lock (in fact, that's the
916  * next thing to do). Anyone trying a DROP DATABASE after this point will
917  * see us in the array once they have the lock. Ordering is important for
918  * this because we don't want to advertise ourselves as being in this
919  * database until we have the lock; otherwise we create what amounts to a
920  * deadlock with CountOtherDBBackends().
921  *
922  * Note: use of RowExclusiveLock here is reasonable because we envision
923  * our session as being a concurrent writer of the database. If we had a
924  * way of declaring a session as being guaranteed-read-only, we could use
925  * AccessShareLock for such sessions and thereby not conflict against
926  * CREATE DATABASE.
927  */
928  if (!bootstrap)
929  LockSharedObject(DatabaseRelationId, MyDatabaseId, 0,
931 
932  /*
933  * Now we can mark our PGPROC entry with the database ID.
934  *
935  * We assume this is an atomic store so no lock is needed; though actually
936  * things would work fine even if it weren't atomic. Anyone searching the
937  * ProcArray for this database's ID should hold the database lock, so they
938  * would not be executing concurrently with this store. A process looking
939  * for another database's ID could in theory see a chance match if it read
940  * a partially-updated databaseId value; but as long as all such searches
941  * wait and retry, as in CountOtherDBBackends(), they will certainly see
942  * the correct value on their next try.
943  */
945 
946  /*
947  * We established a catalog snapshot while reading pg_authid and/or
948  * pg_database; but until we have set up MyDatabaseId, we won't react to
949  * incoming sinval messages for unshared catalogs, so we won't realize it
950  * if the snapshot has been invalidated. Assume it's no good anymore.
951  */
953 
954  /*
955  * Recheck pg_database to make sure the target database hasn't gone away.
956  * If there was a concurrent DROP DATABASE, this ensures we will die
957  * cleanly without creating a mess.
958  */
959  if (!bootstrap)
960  {
961  HeapTuple tuple;
962 
963  tuple = GetDatabaseTuple(dbname);
964  if (!HeapTupleIsValid(tuple) ||
965  MyDatabaseId != HeapTupleGetOid(tuple) ||
967  ereport(FATAL,
968  (errcode(ERRCODE_UNDEFINED_DATABASE),
969  errmsg("database \"%s\" does not exist", dbname),
970  errdetail("It seems to have just been dropped or renamed.")));
971  }
972 
973  /*
974  * Now we should be able to access the database directory safely. Verify
975  * it's there and looks reasonable.
976  */
978 
979  if (!bootstrap)
980  {
981  if (access(fullpath, F_OK) == -1)
982  {
983  if (errno == ENOENT)
984  ereport(FATAL,
985  (errcode(ERRCODE_UNDEFINED_DATABASE),
986  errmsg("database \"%s\" does not exist",
987  dbname),
988  errdetail("The database subdirectory \"%s\" is missing.",
989  fullpath)));
990  else
991  ereport(FATAL,
993  errmsg("could not access directory \"%s\": %m",
994  fullpath)));
995  }
996 
997  ValidatePgVersion(fullpath);
998  }
999 
1000  SetDatabasePath(fullpath);
1001 
1002  /*
1003  * It's now possible to do real access to the system catalogs.
1004  *
1005  * Load relcache entries for the system catalogs. This must create at
1006  * least the minimum set of "nailed-in" cache entries.
1007  */
1009 
1010  /* set up ACL framework (so CheckMyDatabase can check permissions) */
1011  initialize_acl();
1012 
1013  /*
1014  * Re-read the pg_database row for our database, check permissions and set
1015  * up database-specific GUC settings. We can't do this until all the
1016  * database-access infrastructure is up. (Also, it wants to know if the
1017  * user is a superuser, so the above stuff has to happen first.)
1018  */
1019  if (!bootstrap)
1020  CheckMyDatabase(dbname, am_superuser, override_allow_connections);
1021 
1022  /*
1023  * Now process any command-line switches and any additional GUC variable
1024  * settings passed in the startup packet. We couldn't do this before
1025  * because we didn't know if client is a superuser.
1026  */
1027  if (MyProcPort != NULL)
1028  process_startup_options(MyProcPort, am_superuser);
1029 
1030  /* Process pg_db_role_setting options */
1032 
1033  /* Apply PostAuthDelay as soon as we've read all options */
1034  if (PostAuthDelay > 0)
1035  pg_usleep(PostAuthDelay * 1000000L);
1036 
1037  /*
1038  * Initialize various default states that can't be set up until we've
1039  * selected the active user and gotten the right GUC settings.
1040  */
1041 
1042  /* set default namespace search path */
1044 
1045  /* initialize client encoding */
1047 
1048  /* Initialize this backend's session state. */
1050 
1051  /* report this backend in the PgBackendStatus array */
1052  if (!bootstrap)
1053  pgstat_bestart();
1054 
1055  /* close the transaction we started above */
1056  if (!bootstrap)
1058 }
int errhint(const char *fmt,...)
Definition: elog.c:987
BackendId MyBackendId
Definition: globals.c:80
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
struct Port * MyProcPort
Definition: globals.c:42
CAC_state canAcceptConnections
Definition: libpq-be.h:129
void SharedInvalBackendInit(bool sendOnly)
Definition: sinvaladt.c:258
#define DEBUG3
Definition: elog.h:23
Oid GetUserId(void)
Definition: miscinit.c:392
FormData_pg_database * Form_pg_database
Definition: pg_database.h:54
PGPROC * MyProc
Definition: proc.c:67
static HeapTuple GetDatabaseTuple(const char *dbname)
Definition: postinit.c:95
ResourceOwner CurrentResourceOwner
Definition: resowner.c:141
void CommitTransactionCommand(void)
Definition: xact.c:2725
void ReleaseAuxProcessResources(bool isCommit)
Definition: resowner.c:854
void InitializeSession(void)
Definition: session.c:54
void ValidatePgVersion(const char *path)
Definition: miscinit.c:1470
void RelationCacheInitializePhase2(void)
Definition: relcache.c:3483
static void PerformAuthentication(Port *port)
Definition: postinit.c:184
static void LockTimeoutHandler(void)
Definition: postinit.c:1203
int errcode(int sqlerrcode)
Definition: elog.c:575
bool superuser(void)
Definition: superuser.c:47
void initialize_acl(void)
Definition: acl.c:4613
bool RecoveryInProgress(void)
Definition: xlog.c:8082
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:304
#define OidIsValid(objectId)
Definition: c.h:638
Oid GetSessionUserId(void)
Definition: miscinit.c:426
bool HaveNFreeProcs(int n)
Definition: proc.c:648
static void CheckMyDatabase(const char *name, bool am_superuser, bool override_allow_connections)
Definition: postinit.c:293
bool IsBinaryUpgrade
Definition: globals.c:109
Oid MyDatabaseTableSpace
Definition: globals.c:86
bool IsBackgroundWorker
Definition: globals.c:110
void RelationCacheInitializePhase3(void)
Definition: relcache.c:3542
#define NAMEDATALEN
bool am_walsender
Definition: walsender.c:114
void pg_usleep(long microsec)
Definition: signal.c:53
int ReservedBackends
Definition: postmaster.c:212
#define FATAL
Definition: elog.h:52
void InitializeSearchPath(void)
Definition: namespace.c:4203
int MaxBackends
Definition: globals.c:134
void on_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:361
bool IsUnderPostmaster
Definition: globals.c:108
#define RowExclusiveLock
Definition: lockdefs.h:38
int errdetail(const char *fmt,...)
Definition: elog.c:873
int errcode_for_file_access(void)
Definition: elog.c:598
static void IdleInTransactionSessionTimeoutHandler(void)
Definition: postinit.c:1213
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:333
Oid databaseId
Definition: proc.h:114
Oid dattablespace
Definition: pg_database.h:42
void pgstat_initialize(void)
Definition: pgstat.c:2745
static bool ThereIsAtLeastOneRole(void)
Definition: postinit.c:1224
void StartupXLOG(void)
Definition: xlog.c:6367
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3285
#define ereport(elevel, rest)
Definition: elog.h:141
void InvalidateCatalogSnapshot(void)
Definition: snapmgr.c:510
char * GetDatabasePath(Oid dbNode, Oid spcNode)
Definition: relpath.c:107
void SetDatabasePath(const char *path)
Definition: miscinit.c:86
#define WARNING
Definition: elog.h:40
void ShutdownXLOG(int code, Datum arg)
Definition: xlog.c:8513
static HeapTuple GetDatabaseTupleByOid(Oid dboid)
Definition: postinit.c:138
#define InvalidBackendId
Definition: backendid.h:23
bool am_db_walsender
Definition: walsender.c:117
Oid MyDatabaseId
Definition: globals.c:84
int PostAuthDelay
Definition: postgres.c:101
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:919
void EnablePortalManager(void)
Definition: portalmem.c:104
static void ShutdownPostgres(int code, Datum arg)
Definition: postinit.c:1164
static char * username
Definition: initdb.c:132
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
TimeoutId RegisterTimeout(TimeoutId id, timeout_handler_proc handler)
Definition: timeout.c:373
bool IsAutoVacuumLauncherProcess(void)
Definition: autovacuum.c:3279
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:732
void InitializeSessionUserIdStandalone(void)
Definition: miscinit.c:694
void StartTransactionCommand(void)
Definition: xact.c:2654
void CreateAuxProcessResourceOwner(void)
Definition: resowner.c:833
#define XACT_READ_COMMITTED
Definition: xact.h:36
void InitializeSessionUserId(const char *rolename, Oid roleid)
Definition: miscinit.c:591
char * dbname
Definition: streamutil.c:51
static void process_startup_options(Port *port, bool am_superuser)
Definition: postinit.c:1065
int XactIsoLevel
Definition: xact.c:73
bool has_rolreplication(Oid roleid)
Definition: miscinit.c:573
void InitializeClientEncoding(void)
Definition: mbutils.c:282
void InitPlanCache(void)
Definition: plancache.c:118
void InitProcessPhase2(void)
Definition: proc.c:457
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:372
void RelationCacheInitialize(void)
Definition: relcache.c:3446
void ProcSignalInit(int pss_idx)
Definition: procsignal.c:105
void InitCatalogCache(void)
Definition: syscache.c:998
static void StatementTimeoutHandler(void)
Definition: postinit.c:1181
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:713
int errmsg(const char *fmt,...)
Definition: elog.c:797
void pgstat_bestart(void)
Definition: pgstat.c:2785
#define elog(elevel,...)
Definition: elog.h:226
#define NameStr(name)
Definition: c.h:609
static void process_settings(Oid databaseid, Oid roleid)
Definition: postinit.c:1130
void CheckDeadLockAlert(void)
Definition: proc.c:1754
void InitBufferPoolBackend(void)
Definition: bufmgr.c:2461
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:707

◆ InitPostmasterChild()

void InitPostmasterChild ( void  )

Definition at line 273 of file miscinit.c.

References elog, FATAL, InitializeLatchSupport(), InitLatch(), IsUnderPostmaster, LocalLatchData, MyLatch, MyProcPid, MyStartTime, on_exit_reset(), and PostmasterDeathSignalInit().

Referenced by BackendRun(), BackendStartup(), do_start_bgworker(), pgarch_start(), pgstat_start(), StartAutoVacLauncher(), StartAutoVacWorker(), StartChildProcess(), and SysLogger_Start().

274 {
275  IsUnderPostmaster = true; /* we are a postmaster subprocess now */
276 
277  MyProcPid = getpid(); /* reset MyProcPid */
278 
279  MyStartTime = time(NULL); /* set our start time in case we call elog */
280 
281  /*
282  * make sure stderr is in binary mode before anything can possibly be
283  * written to it, in case it's actually the syslogger pipe, so the pipe
284  * chunking protocol isn't disturbed. Non-logpipe data gets translated on
285  * redirection (e.g. via pg_ctl -l) anyway.
286  */
287 #ifdef WIN32
288  _setmode(fileno(stderr), _O_BINARY);
289 #endif
290 
291  /* We don't want the postmaster's proc_exit() handlers */
292  on_exit_reset();
293 
294  /* Initialize process-local latch support */
298 
299  /*
300  * If possible, make this process a group leader, so that the postmaster
301  * can signal any child processes too. Not all processes will have
302  * children, but for consistency we make all postmaster child processes do
303  * this.
304  */
305 #ifdef HAVE_SETSID
306  if (setsid() < 0)
307  elog(FATAL, "setsid() failed: %m");
308 #endif
309 
310  /* Request a signal if the postmaster dies, if possible. */
312 }
int MyProcPid
Definition: globals.c:40
pg_time_t MyStartTime
Definition: globals.c:41
void on_exit_reset(void)
Definition: ipc.c:409
static Latch LocalLatchData
Definition: miscinit.c:65
#define FATAL
Definition: elog.h:52
bool IsUnderPostmaster
Definition: globals.c:108
void InitializeLatchSupport(void)
Definition: latch.c:147
void InitLatch(volatile Latch *latch)
Definition: latch.c:220
#define elog(elevel,...)
Definition: elog.h:226
struct Latch * MyLatch
Definition: globals.c:53
void PostmasterDeathSignalInit(void)
Definition: pmsignal.c:370

◆ InitStandaloneProcess()

void InitStandaloneProcess ( const char *  argv0)

Definition at line 320 of file miscinit.c.

References Assert, elog, FATAL, find_my_exec(), get_pkglib_path(), InitializeLatchSupport(), InitLatch(), IsPostmasterEnvironment, LocalLatchData, my_exec_path, MyLatch, MyProcPid, MyStartTime, pkglib_path, and srandom().

Referenced by AuxiliaryProcessMain(), and PostgresMain().

321 {
323 
324  MyProcPid = getpid(); /* reset MyProcPid */
325 
326  MyStartTime = time(NULL); /* set our start time in case we call elog */
327 
328  /*
329  * Initialize random() for the first time, like PostmasterMain() would.
330  * In a regular IsUnderPostmaster backend, BackendRun() computes a
331  * high-entropy seed before any user query. Fewer distinct initial seeds
332  * can occur here.
333  */
334  srandom((unsigned int) (MyProcPid ^ MyStartTime));
335 
336  /* Initialize process-local latch support */
340 
341  /* Compute paths, no postmaster to inherit from */
342  if (my_exec_path[0] == '\0')
343  {
344  if (find_my_exec(argv0, my_exec_path) < 0)
345  elog(FATAL, "%s: could not locate my own executable path",
346  argv0);
347  }
348 
349  if (pkglib_path[0] == '\0')
351 }
bool IsPostmasterEnvironment
Definition: globals.c:107
static char * argv0
Definition: pg_ctl.c:95
int MyProcPid
Definition: globals.c:40
pg_time_t MyStartTime
Definition: globals.c:41
void get_pkglib_path(const char *my_exec_path, char *ret_path)
Definition: path.c:758
static Latch LocalLatchData
Definition: miscinit.c:65
#define FATAL
Definition: elog.h:52
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:119
char my_exec_path[MAXPGPATH]
Definition: globals.c:71
void InitializeLatchSupport(void)
Definition: latch.c:147
#define Assert(condition)
Definition: c.h:732
void InitLatch(volatile Latch *latch)
Definition: latch.c:220
#define elog(elevel,...)
Definition: elog.h:226
void srandom(unsigned int seed)
Definition: srandom.c:22
struct Latch * MyLatch
Definition: globals.c:53
char pkglib_path[MAXPGPATH]
Definition: globals.c:72

◆ InLocalUserIdChange()

bool InLocalUserIdChange ( void  )

Definition at line 515 of file miscinit.c.

References SECURITY_LOCAL_USERID_CHANGE, and SecurityRestrictionContext.

Referenced by GetUserIdAndContext(), is_admin_of_role(), and set_config_option().

516 {
518 }
static int SecurityRestrictionContext
Definition: miscinit.c:262
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:297

◆ InNoForceRLSOperation()

bool InNoForceRLSOperation ( void  )

Definition at line 533 of file miscinit.c.

References SECURITY_NOFORCE_RLS, and SecurityRestrictionContext.

Referenced by check_enable_rls().

534 {
536 }
static int SecurityRestrictionContext
Definition: miscinit.c:262
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:299

◆ InSecurityRestrictedOperation()

bool InSecurityRestrictedOperation ( void  )

Definition at line 524 of file miscinit.c.

References SECURITY_RESTRICTED_OPERATION, and SecurityRestrictionContext.

Referenced by CheckRestrictedOperation(), DefineRelation(), is_admin_of_role(), set_config_option(), and SetUserIdAndContext().

525 {
527 }
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:298
static int SecurityRestrictionContext
Definition: miscinit.c:262

◆ pg_bindtextdomain()

void pg_bindtextdomain ( const char *  domain)

Definition at line 1623 of file miscinit.c.

References get_locale_path(), MAXPGPATH, and my_exec_path.

Referenced by _PG_init().

1624 {
1625 #ifdef ENABLE_NLS
1626  if (my_exec_path[0] != '\0')
1627  {
1628  char locale_path[MAXPGPATH];
1629 
1630  get_locale_path(my_exec_path, locale_path);
1631  bindtextdomain(domain, locale_path);
1632  pg_bind_textdomain_codeset(domain);
1633  }
1634 #endif
1635 }
#define MAXPGPATH
char my_exec_path[MAXPGPATH]
Definition: globals.c:71
void get_locale_path(const char *my_exec_path, char *ret_path)
Definition: path.c:767

◆ pg_split_opts()

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

Definition at line 443 of file postinit.c.

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

Referenced by BackendRun(), and process_startup_options().

444 {
445  StringInfoData s;
446 
447  initStringInfo(&s);
448 
449  while (*optstr)
450  {
451  bool last_was_escape = false;
452 
453  resetStringInfo(&s);
454 
455  /* skip over leading space */
456  while (isspace((unsigned char) *optstr))
457  optstr++;
458 
459  if (*optstr == '\0')
460  break;
461 
462  /*
463  * Parse a single option, stopping at the first space, unless it's
464  * escaped.
465  */
466  while (*optstr)
467  {
468  if (isspace((unsigned char) *optstr) && !last_was_escape)
469  break;
470 
471  if (!last_was_escape && *optstr == '\\')
472  last_was_escape = true;
473  else
474  {
475  last_was_escape = false;
476  appendStringInfoChar(&s, *optstr);
477  }
478 
479  optstr++;
480  }
481 
482  /* now store the option in the next argv[] position */
483  argv[(*argcp)++] = pstrdup(s.data);
484  }
485 
486  pfree(s.data);
487 }
char * pstrdup(const char *in)
Definition: mcxt.c:1161
void pfree(void *pointer)
Definition: mcxt.c:1031
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:62
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:169
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46

◆ PostgresSigHupHandler()

void PostgresSigHupHandler ( SIGNAL_ARGS  )

Definition at line 2796 of file postgres.c.

References ConfigReloadPending, MyLatch, and SetLatch().

Referenced by PostgresMain(), and WalSndSignals().

2797 {
2798  int save_errno = errno;
2799 
2800  ConfigReloadPending = true;
2801  SetLatch(MyLatch);
2802 
2803  errno = save_errno;
2804 }
volatile sig_atomic_t ConfigReloadPending
Definition: globals.c:35
void SetLatch(volatile Latch *latch)
Definition: latch.c:414
struct Latch * MyLatch
Definition: globals.c:53

◆ PreventCommandDuringRecovery()

void PreventCommandDuringRecovery ( const char *  cmdname)

Definition at line 276 of file utility.c.

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

Referenced by LockTableCommand(), pg_notify(), standard_ProcessUtility(), and txid_current().

277 {
278  if (RecoveryInProgress())
279  ereport(ERROR,
280  (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
281  /* translator: %s is name of a SQL command, eg CREATE */
282  errmsg("cannot execute %s during recovery",
283  cmdname)));
284 }
int errcode(int sqlerrcode)
Definition: elog.c:575
bool RecoveryInProgress(void)
Definition: xlog.c:8082
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
int errmsg(const char *fmt,...)
Definition: elog.c:797

◆ PreventCommandIfParallelMode()

void PreventCommandIfParallelMode ( const char *  cmdname)

Definition at line 257 of file utility.c.

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

Referenced by _SPI_execute_plan(), check_xact_readonly(), do_setval(), DoCopy(), ExecCheckXactReadOnly(), init_execution_state(), nextval_internal(), and SPI_cursor_open_internal().

258 {
259  if (IsInParallelMode())
260  ereport(ERROR,
261  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
262  /* translator: %s is name of a SQL command, eg CREATE */
263  errmsg("cannot execute %s during a parallel operation",
264  cmdname)));
265 }
int errcode(int sqlerrcode)
Definition: elog.c:575
bool IsInParallelMode(void)
Definition: xact.c:886
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
int errmsg(const char *fmt,...)
Definition: elog.c:797

◆ PreventCommandIfReadOnly()

void PreventCommandIfReadOnly ( const char *  cmdname)

Definition at line 239 of file utility.c.

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

Referenced by check_xact_readonly(), do_setval(), DoCopy(), ExecCheckXactReadOnly(), and nextval_internal().

240 {
241  if (XactReadOnly)
242  ereport(ERROR,
243  (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
244  /* translator: %s is name of a SQL command, eg CREATE */
245  errmsg("cannot execute %s in a read-only transaction",
246  cmdname)));
247 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
bool XactReadOnly
Definition: xact.c:76
int errmsg(const char *fmt,...)
Definition: elog.c:797

◆ process_session_preload_libraries()

void process_session_preload_libraries ( void  )

Definition at line 1612 of file miscinit.c.

References load_libraries(), local_preload_libraries_string, and session_preload_libraries_string.

Referenced by PostgresMain().

1613 {
1615  "session_preload_libraries",
1616  false);
1618  "local_preload_libraries",
1619  true);
1620 }
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1547
char * local_preload_libraries_string
Definition: miscinit.c:1535
char * session_preload_libraries_string
Definition: miscinit.c:1533

◆ process_shared_preload_libraries()

void process_shared_preload_libraries ( void  )

Definition at line 1599 of file miscinit.c.

References load_libraries(), process_shared_preload_libraries_in_progress, and shared_preload_libraries_string.

Referenced by BackendRun(), and PostmasterMain().

1600 {
1603  "shared_preload_libraries",
1604  false);
1606 }
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1538
char * shared_preload_libraries_string
Definition: miscinit.c:1534
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1547

◆ ProcessInterrupts()

void ProcessInterrupts ( void  )

Definition at line 2936 of file postgres.c.

References Assert, ClientAuthInProgress, ClientConnectionLost, CritSectionCount, DEBUG1, DestNone, DestRemote, DoingCommandRead, ereport, errcode(), errdetail_recovery_conflict(), errhint(), errmsg(), ERROR, FATAL, get_timeout_finish_time(), get_timeout_indicator(), HandleParallelMessages(), IdleInTransactionSessionTimeout, IdleInTransactionSessionTimeoutPending, InterruptHoldoffCount, InterruptPending, IsAutoVacuumWorkerProcess(), IsLogicalLauncher(), IsLogicalWorker(), LOCK_TIMEOUT, LockErrorCleanup(), ParallelMessagePending, pgstat_report_recovery_conflict(), proc_exit(), ProcDiePending, PROCSIG_RECOVERY_CONFLICT_DATABASE, QueryCancelHoldoffCount, QueryCancelPending, RecoveryConflictPending, RecoveryConflictReason, RecoveryConflictRetryable, STATEMENT_TIMEOUT, and whereToSendOutput.

Referenced by die().

2937 {
2938  /* OK to accept any interrupts now? */
2939  if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
2940  return;
2941  InterruptPending = false;
2942 
2943  if (ProcDiePending)
2944  {
2945  ProcDiePending = false;
2946  QueryCancelPending = false; /* ProcDie trumps QueryCancel */
2947  LockErrorCleanup();
2948  /* As in quickdie, don't risk sending to client during auth */
2952  ereport(FATAL,
2953  (errcode(ERRCODE_QUERY_CANCELED),
2954  errmsg("canceling authentication due to timeout")));
2955  else if (IsAutoVacuumWorkerProcess())
2956  ereport(FATAL,
2957  (errcode(ERRCODE_ADMIN_SHUTDOWN),
2958  errmsg("terminating autovacuum process due to administrator command")));
2959  else if (IsLogicalWorker())
2960  ereport(FATAL,
2961  (errcode(ERRCODE_ADMIN_SHUTDOWN),
2962  errmsg("terminating logical replication worker due to administrator command")));
2963  else if (IsLogicalLauncher())
2964  {
2965  ereport(DEBUG1,
2966  (errmsg("logical replication launcher shutting down")));
2967 
2968  /*
2969  * The logical replication launcher can be stopped at any time.
2970  * Use exit status 1 so the background worker is restarted.
2971  */
2972  proc_exit(1);
2973  }
2975  {
2977  ereport(FATAL,
2978  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2979  errmsg("terminating connection due to conflict with recovery"),
2981  }
2982  else if (RecoveryConflictPending)
2983  {
2984  /* Currently there is only one non-retryable recovery conflict */
2987  ereport(FATAL,
2988  (errcode(ERRCODE_DATABASE_DROPPED),
2989  errmsg("terminating connection due to conflict with recovery"),
2991  }
2992  else
2993  ereport(FATAL,
2994  (errcode(ERRCODE_ADMIN_SHUTDOWN),
2995  errmsg("terminating connection due to administrator command")));
2996  }
2998  {
2999  QueryCancelPending = false; /* lost connection trumps QueryCancel */
3000  LockErrorCleanup();
3001  /* don't send to client, we already know the connection to be dead. */
3003  ereport(FATAL,
3004  (errcode(ERRCODE_CONNECTION_FAILURE),
3005  errmsg("connection to client lost")));
3006  }
3007 
3008  /*
3009  * If a recovery conflict happens while we are waiting for input from the
3010  * client, the client is presumably just sitting idle in a transaction,
3011  * preventing recovery from making progress. Terminate the connection to
3012  * dislodge it.
3013  */
3015  {
3016  QueryCancelPending = false; /* this trumps QueryCancel */
3017  RecoveryConflictPending = false;
3018  LockErrorCleanup();
3020  ereport(FATAL,
3021  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3022  errmsg("terminating connection due to conflict with recovery"),
3024  errhint("In a moment you should be able to reconnect to the"
3025  " database and repeat your command.")));
3026  }
3027 
3028  /*
3029  * Don't allow query cancel interrupts while reading input from the
3030  * client, because we might lose sync in the FE/BE protocol. (Die
3031  * interrupts are OK, because we won't read any further messages from the
3032  * client in that case.)
3033  */
3035  {
3036  /*
3037  * Re-arm InterruptPending so that we process the cancel request as
3038  * soon as we're done reading the message.
3039  */
3040  InterruptPending = true;
3041  }
3042  else if (QueryCancelPending)
3043  {
3044  bool lock_timeout_occurred;
3045  bool stmt_timeout_occurred;
3046 
3047  QueryCancelPending = false;
3048 
3049  /*
3050  * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
3051  * need to clear both, so always fetch both.
3052  */
3053  lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
3054  stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
3055 
3056  /*
3057  * If both were set, we want to report whichever timeout completed
3058  * earlier; this ensures consistent behavior if the machine is slow
3059  * enough that the second timeout triggers before we get here. A tie
3060  * is arbitrarily broken in favor of reporting a lock timeout.
3061  */
3062  if (lock_timeout_occurred && stmt_timeout_occurred &&
3064  lock_timeout_occurred = false; /* report stmt timeout */
3065 
3066  if (lock_timeout_occurred)
3067  {
3068  LockErrorCleanup();
3069  ereport(ERROR,
3070  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
3071  errmsg("canceling statement due to lock timeout")));
3072  }
3073  if (stmt_timeout_occurred)
3074  {
3075  LockErrorCleanup();
3076  ereport(ERROR,
3077  (errcode(ERRCODE_QUERY_CANCELED),
3078  errmsg("canceling statement due to statement timeout")));
3079  }
3081  {
3082  LockErrorCleanup();
3083  ereport(ERROR,
3084  (errcode(ERRCODE_QUERY_CANCELED),
3085  errmsg("canceling autovacuum task")));
3086  }
3088  {
3089  RecoveryConflictPending = false;
3090  LockErrorCleanup();
3092  ereport(ERROR,
3093  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3094  errmsg("canceling statement due to conflict with recovery"),
3096  }
3097 
3098  /*
3099  * If we are reading a command from the client, just ignore the cancel
3100  * request --- sending an extra error message won't accomplish
3101  * anything. Otherwise, go ahead and throw the error.
3102  */
3103  if (!DoingCommandRead)
3104  {
3105  LockErrorCleanup();
3106  ereport(ERROR,
3107  (errcode(ERRCODE_QUERY_CANCELED),
3108  errmsg("canceling statement due to user request")));
3109  }
3110  }
3111 
3113  {
3114  /* Has the timeout setting changed since last we looked? */
3116  ereport(FATAL,
3117  (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
3118  errmsg("terminating connection due to idle-in-transaction timeout")));
3119  else
3121 
3122  }
3123 
3126 }
volatile uint32 InterruptHoldoffCount
Definition: globals.c:36
TimestampTz get_timeout_finish_time(TimeoutId id)
Definition: timeout.c:667
#define DEBUG1
Definition: elog.h:25
int errhint(const char *fmt,...)
Definition: elog.c:987
void pgstat_report_recovery_conflict(int reason)
Definition: pgstat.c:1486
volatile bool IdleInTransactionSessionTimeoutPending
Definition: globals.c:34
volatile uint32 QueryCancelHoldoffCount
Definition: globals.c:37
void proc_exit(int code)
Definition: ipc.c:104
int errcode(int sqlerrcode)
Definition: elog.c:575
volatile bool QueryCancelPending
Definition: globals.c:31
bool IsLogicalWorker(void)
Definition: worker.c:1762
volatile bool ClientConnectionLost
Definition: globals.c:33
volatile bool ParallelMessagePending
Definition: parallel.c:107
bool ClientAuthInProgress
Definition: postmaster.c:350
#define ERROR
Definition: elog.h:43
int IdleInTransactionSessionTimeout
Definition: proc.c:63
#define FATAL
Definition: elog.h:52
void HandleParallelMessages(void)
Definition: parallel.c:964
Definition: dest.h:88
volatile uint32 CritSectionCount
Definition: globals.c:38
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3285
#define ereport(elevel, rest)
Definition: elog.h:141
void LockErrorCleanup(void)
Definition: proc.c:688
static ProcSignalReason RecoveryConflictReason
Definition: postgres.c:168
static bool RecoveryConflictPending
Definition: postgres.c:166
static bool RecoveryConflictRetryable
Definition: postgres.c:167
bool get_timeout_indicator(TimeoutId id, bool reset_indicator)
Definition: timeout.c:633
static int errdetail_recovery_conflict(void)
Definition: postgres.c:2351
volatile bool InterruptPending
Definition: globals.c:30
#define Assert(condition)
Definition: c.h:732
static bool DoingCommandRead
Definition: postgres.c:139
volatile bool ProcDiePending
Definition: globals.c:32
int errmsg(const char *fmt,...)
Definition: elog.c:797
bool IsLogicalLauncher(void)
Definition: launcher.c:1103
CommandDest whereToSendOutput
Definition: postgres.c:90

◆ RecheckDataDirLockFile()

bool RecheckDataDirLockFile ( void  )

Definition at line 1398 of file miscinit.c.

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

Referenced by ServerLoop().

1399 {
1400  int fd;
1401  int len;
1402  long file_pid;
1403  char buffer[BLCKSZ];
1404 
1405  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1406  if (fd < 0)
1407  {
1408  /*
1409  * There are many foreseeable false-positive error conditions. For
1410  * safety, fail only on enumerated clearly-something-is-wrong
1411  * conditions.
1412  */
1413  switch (errno)
1414  {
1415  case ENOENT:
1416  case ENOTDIR:
1417  /* disaster */
1418  ereport(LOG,
1420  errmsg("could not open file \"%s\": %m",
1422  return false;
1423  default:
1424  /* non-fatal, at least for now */
1425  ereport(LOG,
1427  errmsg("could not open file \"%s\": %m; continuing anyway",
1429  return true;
1430  }
1431  }
1433  len = read(fd, buffer, sizeof(buffer) - 1);
1435  if (len < 0)
1436  {
1437  ereport(LOG,
1439  errmsg("could not read from file \"%s\": %m",
1441  close(fd);
1442  return true; /* treat read failure as nonfatal */
1443  }
1444  buffer[len] = '\0';
1445  close(fd);
1446  file_pid = atol(buffer);
1447  if (file_pid == getpid())
1448  return true; /* all is well */
1449 
1450  /* Trouble: someone's overwritten the lock file */
1451  ereport(LOG,
1452  (errmsg("lock file \"%s\" contains wrong PID: %ld instead of %ld",
1453  DIRECTORY_LOCK_FILE, file_pid, (long) getpid())));
1454  return false;
1455 }
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:58
#define LOG
Definition: elog.h:26
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PG_BINARY
Definition: c.h:1139
int errcode_for_file_access(void)
Definition: elog.c:598
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1261
#define ereport(elevel, rest)
Definition: elog.h:141
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:217
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1237
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define close(a)
Definition: win32.h:12
#define read(a, b, c)
Definition: win32.h:13

◆ restore_stack_base()

void restore_stack_base ( pg_stack_base_t  base)

Definition at line 3204 of file postgres.c.

References stack_base_ptr.

3205 {
3206 #if defined(__ia64__) || defined(__ia64)
3207  stack_base_ptr = base.stack_base_ptr;
3208  register_stack_base_ptr = base.register_stack_base_ptr;
3209 #else
3210  stack_base_ptr = base;
3211 #endif
3212 }
char * stack_base_ptr
Definition: postgres.c:119

◆ set_stack_base()

pg_stack_base_t set_stack_base ( void  )

Definition at line 3173 of file postgres.c.

References stack_base_ptr.

Referenced by BackendRun(), and PostmasterMain().

3174 {
3175  char stack_base;
3176  pg_stack_base_t old;
3177 
3178 #if defined(__ia64__) || defined(__ia64)
3179  old.stack_base_ptr = stack_base_ptr;
3180  old.register_stack_base_ptr = register_stack_base_ptr;
3181 #else
3182  old = stack_base_ptr;
3183 #endif
3184 
3185  /* Set up reference point for stack depth checking */
3186  stack_base_ptr = &stack_base;
3187 #if defined(__ia64__) || defined(__ia64)
3188  register_stack_base_ptr = ia64_get_bsp();
3189 #endif
3190 
3191  return old;
3192 }
char * stack_base_ptr
Definition: postgres.c:119
char * pg_stack_base_t
Definition: miscadmin.h:272

◆ SetCurrentRoleId()

void SetCurrentRoleId ( Oid  roleid,
bool  is_superuser 
)

Definition at line 772 of file miscinit.c.

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

Referenced by assign_role(), and ParallelWorkerMain().

773 {
774  /*
775  * Get correct info if it's SET ROLE NONE
776  *
777  * If SessionUserId hasn't been set yet, just do nothing --- the eventual
778  * SetSessionUserId call will fix everything. This is needed since we
779  * will get called during GUC initialization.
780  */
781  if (!OidIsValid(roleid))
782  {
784  return;
785 
786  roleid = SessionUserId;
788 
789  SetRoleIsActive = false;
790  }
791  else
792  SetRoleIsActive = true;
793 
794  SetOuterUserId(roleid);
795 
796  SetConfigOption("is_superuser",
797  is_superuser ? "on" : "off",
799 }
static Oid SessionUserId
Definition: miscinit.c:254
static void SetOuterUserId(Oid userid)
Definition: miscinit.c:411
#define OidIsValid(objectId)
Definition: c.h:638
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6952
static bool SetRoleIsActive
Definition: miscinit.c:265
static bool SessionUserIsSuperuser
Definition: miscinit.c:260
static bool is_superuser(Archive *fout)
Definition: pg_dump.c:4036

◆ SetDatabasePath()

void SetDatabasePath ( const char *  path)

Definition at line 86 of file miscinit.c.

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

Referenced by InitPostgres().

87 {
88  /* This should happen only once per process */
91 }
MemoryContext TopMemoryContext
Definition: mcxt.c:44
char * DatabasePath
Definition: globals.c:92
#define Assert(condition)
Definition: c.h:732
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1148

◆ SetDataDir()

void SetDataDir ( const char *  dir)

Definition at line 192 of file miscinit.c.

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

Referenced by PostmasterMarkPIDForWorkerNotify(), and SelectConfigFiles().

193 {
194  char *new;
195 
196  AssertArg(dir);
197 
198  /* If presented path is relative, convert to absolute */
199  new = make_absolute_path(dir);
200 
201  if (DataDir)
202  free(DataDir);
203  DataDir = new;
204 }
char * make_absolute_path(const char *path)
Definition: path.c:608
#define AssertArg(condition)
Definition: c.h:734
#define free(a)
Definition: header.h:65
char * DataDir
Definition: globals.c:61

◆ SetSessionAuthorization()

void SetSessionAuthorization ( Oid  userid,
bool  is_superuser 
)

Definition at line 726 of file miscinit.c.

References AssertState, AuthenticatedUserId, AuthenticatedUserIsSuperuser, ereport, errcode(), errmsg(), ERROR, OidIsValid, PGC_INTERNAL, PGC_S_OVERRIDE, SetConfigOption(), and SetSessionUserId().

Referenced by assign_session_authorization().

727 {
728  /* Must have authenticated already, else can't make permission check */
730 
731  if (userid != AuthenticatedUserId &&
733  ereport(ERROR,
734  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
735  errmsg("permission denied to set session authorization")));
736 
738 
739  SetConfigOption("is_superuser",
740  is_superuser ? "on" : "off",
742 }
#define AssertState(condition)
Definition: c.h:735
int errcode(int sqlerrcode)
Definition: elog.c:575
#define OidIsValid(objectId)
Definition: c.h:638
#define ERROR
Definition: elog.h:43
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6952
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:259
#define ereport(elevel, rest)
Definition: elog.h:141
static bool is_superuser(Archive *fout)
Definition: pg_dump.c:4036
int errmsg(const char *fmt,...)
Definition: elog.c:797
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:434
static Oid AuthenticatedUserId
Definition: miscinit.c:253

◆ SetUserIdAndContext()

void SetUserIdAndContext ( Oid  userid,
bool  sec_def_context 
)

Definition at line 553 of file miscinit.c.

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

554 {
555  /* We throw the same error SET ROLE would. */
557  ereport(ERROR,
558  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
559  errmsg("cannot set parameter \"%s\" within security-restricted operation",
560  "role")));
561  CurrentUserId = userid;
562  if (sec_def_context)
564  else
566 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
static int SecurityRestrictionContext
Definition: miscinit.c:262
#define ereport(elevel, rest)
Definition: elog.h:141
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:297
static Oid CurrentUserId
Definition: miscinit.c:256
bool InSecurityRestrictedOperation(void)
Definition: miscinit.c:524
int errmsg(const char *fmt,...)
Definition: elog.c:797

◆ SetUserIdAndSecContext()

void SetUserIdAndSecContext ( Oid  userid,
int  sec_context 
)

◆ stack_is_too_deep()

bool stack_is_too_deep ( void  )

Definition at line 3240 of file postgres.c.

References max_stack_depth_bytes, and stack_base_ptr.

Referenced by check_stack_depth(), and rstacktoodeep().

3241 {
3242  char stack_top_loc;
3243  long stack_depth;
3244 
3245  /*
3246  * Compute distance from reference point to my local variables
3247  */
3248  stack_depth = (long) (stack_base_ptr - &stack_top_loc);
3249 
3250  /*
3251  * Take abs value, since stacks grow up on some machines, down on others
3252  */
3253  if (stack_depth < 0)
3254  stack_depth = -stack_depth;
3255 
3256  /*
3257  * Trouble?
3258  *
3259  * The test on stack_base_ptr prevents us from erroring out if called
3260  * during process setup or in a non-backend process. Logically it should
3261  * be done first, but putting it here avoids wasting cycles during normal
3262  * cases.
3263  */
3264  if (stack_depth > max_stack_depth_bytes &&
3265  stack_base_ptr != NULL)
3266  return true;
3267 
3268  /*
3269  * On IA64 there is a separate "register" stack that requires its own
3270  * independent check. For this, we have to measure the change in the
3271  * "BSP" pointer from PostgresMain to here. Logic is just as above,
3272  * except that we know IA64's register stack grows up.
3273  *
3274  * Note we assume that the same max_stack_depth applies to both stacks.
3275  */
3276 #if defined(__ia64__) || defined(__ia64)
3277  stack_depth = (long) (ia64_get_bsp() - register_stack_base_ptr);
3278 
3279  if (stack_depth > max_stack_depth_bytes &&
3280  register_stack_base_ptr != NULL)
3281  return true;
3282 #endif /* IA64 */
3283 
3284  return false;
3285 }
static long max_stack_depth_bytes
Definition: postgres.c:111
char * stack_base_ptr
Definition: postgres.c:119

◆ superuser()

bool superuser ( void  )

Definition at line 47 of file superuser.c.

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(), AlterSystemSetConfigFile(), AlterTypeOwner(), ATExecChangeOwner(), brin_metapage_info(), brin_page_items(), brin_page_type(), brin_revmap_data(), bt_metap(), bt_page_items(), bt_page_items_bytea(), bt_page_stats(), check_encoding_locale_matches(), check_permissions(), 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(), ExecuteDoStmt(), fmgr_security_definer(), fsm_page_contents(), get_raw_page_internal(), gin_leafpage_items(), gin_metapage_info(), gin_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(), InitPostgres(), main(), page_checksum(), page_header(), pg_import_system_collations(), pg_logdir_ls(), pg_read_file(), pg_relpages(), pg_relpagesbyid(), pg_rotate_logfile(), pg_signal_backend(), pgstat_get_backend_current_activity(), pgstatginindex(), pgstatindex(), pgstatindexbyid(), pgstattuple(), pgstattuple_approx(), pgstattuplebyid(), ProcedureCreate(), regress_putenv(), RemoveAccessMethodById(), RenameRole(), replorigin_check_prerequisites(), requireSuperuser(), sepgsql_restorecon(), set_config_by_name(), SetPGVariable(), standard_ProcessUtility(), tuple_data_split(), validate_option_array_item(), and wait_pid().

48 {
49  return superuser_arg(GetUserId());
50 }
Oid GetUserId(void)
Definition: miscinit.c:392
bool superuser_arg(Oid roleid)
Definition: superuser.c:57

◆ superuser_arg()

bool superuser_arg ( Oid  roleid)

Definition at line 57 of file superuser.c.

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(), has_bypassrls_privilege(), has_createrole_privilege(), has_privs_of_role(), is_admin_of_role(), is_member_of_role(), LockGXact(), pg_class_aclmask(), pg_class_ownercheck(), pg_collation_ownercheck(), pg_conversion_ownercheck(), pg_database_aclmask(), pg_database_ownercheck(), pg_event_trigger_ownercheck(), pg_extension_ownercheck(), pg_foreign_data_wrapper_aclmask(), pg_foreign_data_wrapper_ownercheck(), pg_foreign_server_aclmask(), pg_foreign_server_ownercheck(), pg_language_aclmask(), pg_language_ownercheck(), pg_largeobject_aclmask_snapshot(), pg_largeobject_ownercheck(), pg_namespace_aclmask(), pg_namespace_ownercheck(), pg_opclass_ownercheck(), pg_oper_ownercheck(), pg_opfamily_ownercheck(), pg_proc_aclmask(), pg_proc_ownercheck(), pg_publication_ownercheck(), pg_signal_backend(), pg_statistics_object_ownercheck(), pg_subscription_ownercheck(), pg_tablespace_aclmask(), pg_tablespace_ownercheck(), pg_ts_config_ownercheck(), pg_ts_dict_ownercheck(), pg_type_aclmask(), pg_type_ownercheck(), select_best_grantor(), and superuser().

58 {
59  bool result;
60  HeapTuple rtup;
61 
62  /* Quick out for cache hit */
63  if (OidIsValid(last_roleid) && last_roleid == roleid)
64  return last_roleid_is_super;
65 
66  /* Special escape path in case you deleted all your users. */
67  if (!IsUnderPostmaster && roleid == BOOTSTRAP_SUPERUSERID)
68  return true;
69 
70  /* OK, look up the information in pg_authid */
71  rtup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
72  if (HeapTupleIsValid(rtup))
73  {
74  result = ((Form_pg_authid) GETSTRUCT(rtup))->rolsuper;
75  ReleaseSysCache(rtup);
76  }
77  else
78  {
79  /* Report "not superuser" for invalid roleids */
80  result = false;
81  }
82 
83  /* If first time through, set up callback for cache flushes */
85  {
88  (Datum) 0);
90  }
91 
92  /* Cache the result for next time */
93  last_roleid = roleid;
94  last_roleid_is_super = result;
95 
96  return result;
97 }
static Oid last_roleid
Definition: superuser.c:36
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
#define OidIsValid(objectId)
Definition: c.h:638
static void RoleidCallback(Datum arg, int cacheid, uint32 hashvalue)
Definition: superuser.c:104
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:55
static bool last_roleid_is_super
Definition: superuser.c:37
#define ObjectIdGetDatum(X)
Definition: postgres.h:492
bool IsUnderPostmaster
Definition: globals.c:108
bool rolsuper
Definition: pg_authid.h:34
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
void CacheRegisterSyscacheCallback(int cacheid, SyscacheCallbackFunction func, Datum arg)
Definition: inval.c:1407
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
static bool roleid_callback_registered
Definition: superuser.c:38

◆ SwitchBackToLocalLatch()

void SwitchBackToLocalLatch ( void  )

Definition at line 373 of file miscinit.c.

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

Referenced by AuxiliaryProcKill(), and ProcKill().

374 {
376  Assert(MyProc != NULL && MyLatch == &MyProc->procLatch);
377 
379 
380  if (FeBeWaitSet)
382 
383  SetLatch(MyLatch);
384 }
PGPROC * MyProc
Definition: proc.c:67
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:736
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:186
Latch procLatch
Definition: proc.h:104
static Latch LocalLatchData
Definition: miscinit.c:65
void SetLatch(volatile Latch *latch)
Definition: latch.c:414
#define Assert(condition)
Definition: c.h:732
struct Latch * MyLatch
Definition: globals.c:53
#define WL_LATCH_SET
Definition: latch.h:124

◆ SwitchToSharedLatch()

void SwitchToSharedLatch ( void  )

Definition at line 354 of file miscinit.c.

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

Referenced by InitAuxiliaryProcess(), and InitProcess().

355 {
357  Assert(MyProc != NULL);
358 
360 
361  if (FeBeWaitSet)
363 
364  /*
365  * Set the shared latch as the local one might have been set. This
366  * shouldn't normally be necessary as code is supposed to check the
367  * condition before waiting for the latch, but a bit care can't hurt.
368  */
369  SetLatch(MyLatch);
370 }
PGPROC * MyProc
Definition: proc.c:67
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:736
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:186
Latch procLatch
Definition: proc.h:104
static Latch LocalLatchData
Definition: miscinit.c:65
void SetLatch(volatile Latch *latch)
Definition: latch.c:414
#define Assert(condition)
Definition: c.h:732
struct Latch * MyLatch
Definition: globals.c:53
#define WL_LATCH_SET
Definition: latch.h:124

◆ TouchSocketLockFiles()

void TouchSocketLockFiles ( void  )

Definition at line 1220 of file miscinit.c.

References buffer, close, DIRECTORY_LOCK_FILE, fd(), lfirst, PG_BINARY, and read.

Referenced by ServerLoop().

1221 {
1222  ListCell *l;
1223 
1224  foreach(l, lock_files)
1225  {
1226  char *socketLockFile = (char *) lfirst(l);
1227 
1228  /* No need to touch the data directory lock file, we trust */
1229  if (strcmp(socketLockFile, DIRECTORY_LOCK_FILE) == 0)
1230  continue;
1231 
1232  /*
1233  * utime() is POSIX standard, utimes() is a common alternative; if we
1234  * have neither, fall back to actually reading the file (which only
1235  * sets the access time not mod time, but that should be enough in
1236  * most cases). In all paths, we ignore errors.
1237  */
1238 #ifdef HAVE_UTIME
1239  utime(socketLockFile, NULL);
1240 #else /* !HAVE_UTIME */
1241 #ifdef HAVE_UTIMES
1242  utimes(socketLockFile, NULL);
1243 #else /* !HAVE_UTIMES */
1244  int fd;
1245  char buffer[1];
1246 
1247  fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
1248  if (fd >= 0)
1249  {
1250  read(fd, buffer, sizeof(buffer));
1251  close(fd);
1252  }
1253 #endif /* HAVE_UTIMES */
1254 #endif /* HAVE_UTIME */
1255  }
1256 }
static List * lock_files
Definition: miscinit.c:63
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:58
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PG_BINARY
Definition: c.h:1139
#define lfirst(lc)
Definition: pg_list.h:106
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:217
#define close(a)
Definition: win32.h:12
#define read(a, b, c)
Definition: win32.h:13

◆ trace_recovery()

int trace_recovery ( int  trace_level)

Definition at line 3758 of file elog.c.

References LOG, and trace_recovery_messages.

Referenced by KnownAssignedXidsRemove(), KnownAssignedXidsRemovePreceding(), LogCurrentRunningXacts(), ProcArrayApplyRecoveryInfo(), ProcessCommittedInvalidationMessages(), RecordKnownAssignedTransactionIds(), RecoveryRestartPoint(), StandbyAcquireAccessExclusiveLock(), StandbyReleaseAllLocks(), and StandbyReleaseLockList().

3759 {
3760  if (trace_level < LOG &&
3761  trace_level >= trace_recovery_messages)
3762  return LOG;
3763 
3764  return trace_level;
3765 }
#define LOG
Definition: elog.h:26
int trace_recovery_messages
Definition: guc.c:466

◆ ValidatePgVersion()

void ValidatePgVersion ( const char *  path)

Definition at line 1470 of file miscinit.c.

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

Referenced by checkDataDir(), and InitPostgres().

1471 {
1472  char full_path[MAXPGPATH];
1473  FILE *file;
1474  int ret;
1475  long file_major;
1476  long my_major;
1477  char *endptr;
1478  char file_version_string[64];
1479  const char *my_version_string = PG_VERSION;
1480 
1481  my_major = strtol(my_version_string, &endptr, 10);
1482 
1483  snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
1484 
1485  file = AllocateFile(full_path, "r");
1486  if (!file)
1487  {
1488  if (errno == ENOENT)
1489  ereport(FATAL,
1490  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1491  errmsg("\"%s\" is not a valid data directory",
1492  path),
1493  errdetail("File \"%s\" is missing.", full_path)));
1494  else
1495  ereport(FATAL,
1497  errmsg("could not open file \"%s\": %m", full_path)));
1498  }
1499 
1500  file_version_string[0] = '\0';
1501  ret = fscanf(file, "%63s", file_version_string);
1502  file_major = strtol(file_version_string, &endptr, 10);
1503 
1504  if (ret != 1 || endptr == file_version_string)
1505  ereport(FATAL,
1506  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1507  errmsg("\"%s\" is not a valid data directory",
1508  path),
1509  errdetail("File \"%s\" does not contain valid data.",
1510  full_path),
1511  errhint("You might need to initdb.")));
1512 
1513  FreeFile(file);
1514 
1515  if (my_major != file_major)
1516  ereport(FATAL,
1517  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1518  errmsg("database files are incompatible with server"),
1519  errdetail("The data directory was initialized by PostgreSQL version %s, "
1520  "which is not compatible with this version %s.",
1521  file_version_string, my_version_string)));
1522 }
int errhint(const char *fmt,...)
Definition: elog.c:987
int errcode(int sqlerrcode)
Definition: elog.c:575
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define FATAL
Definition: elog.h:52
#define MAXPGPATH
int errdetail(const char *fmt,...)
Definition: elog.c:873
int errcode_for_file_access(void)
Definition: elog.c:598
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2336
#define ereport(elevel, rest)
Definition: elog.h:141
int FreeFile(FILE *file)
Definition: fd.c:2528
int errmsg(const char *fmt,...)
Definition: elog.c:797

Variable Documentation

◆ allowSystemTableMods

◆ ClientConnectionLost

volatile bool ClientConnectionLost

Definition at line 33 of file globals.c.

Referenced by internal_flush(), and ProcessInterrupts().

◆ ConfigReloadPending

PGDLLIMPORT volatile sig_atomic_t ConfigReloadPending

◆ CritSectionCount

◆ data_directory_mode

PGDLLIMPORT int data_directory_mode

Definition at line 67 of file globals.c.

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

◆ DatabasePath

◆ DataDir

◆ DateOrder

PGDLLIMPORT int DateOrder

◆ DateStyle

◆ enableFsync

◆ ExitOnAnyError

PGDLLIMPORT bool ExitOnAnyError

Definition at line 112 of file globals.c.

Referenced by BackgroundWriterMain(), CheckpointerMain(), and errstart().

◆ IdleInTransactionSessionTimeoutPending

PGDLLIMPORT volatile bool IdleInTransactionSessionTimeoutPending

Definition at line 34 of file globals.c.

Referenced by IdleInTransactionSessionTimeoutHandler(), and ProcessInterrupts().

◆ IgnoreSystemIndexes

bool IgnoreSystemIndexes

◆ InterruptHoldoffCount

PGDLLIMPORT volatile uint32 InterruptHoldoffCount

Definition at line 36 of file globals.c.

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

◆ InterruptPending

◆ IntervalStyle

PGDLLIMPORT int IntervalStyle

◆ IsBackgroundWorker

◆ IsBinaryUpgrade

◆ IsPostmasterEnvironment

◆ IsUnderPostmaster

PGDLLIMPORT bool IsUnderPostmaster

Definition at line 108 of file globals.c.

Referenced by _PG_init(), AutoVacuumShmemInit(), AuxiliaryProcessMain(), BackendRandomShmemInit(), BackgroundWorkerShmemInit(), bootstrap_signals(), BootstrapModeMain(), BTreeShmemInit(), CheckMyDatabase(), CheckRecoveryConsistency(), CommitTsShmemInit(), CreateLWLocks(), CreateSharedMemoryAndSemaphores(), DebugFileOpen(), dsm_attach(), dsm_create(), dsm_postmaster_startup(), EventTriggerDDLCommandEnd(), EventTriggerDDLCommandStart(), EventTriggerSQLDrop(), EventTriggerTableRewrite(), ForgetDatabaseFsyncRequests(), ForgetRelationFsyncRequests(), ForwardFsyncRequest(), GetNewMultiXactId(), GetNewTransactionId(), HandleStartupProcInterrupts(), heap_create_with_catalog(), init_ps_display(), InitCommunication(), InitializeLatchSupport(), InitializeSessionUserId(), InitializeSessionUserIdStandalone(), InitPostgres(), InitPostmasterChild(), InitPredicateLocks(), InitProcess(), LWLockAcquire(), mdinit(), MultiXactShmemInit(), OldSerXidInit(), pg_backend_random(), PGSemaphoreCreate(), PGSharedMemoryCreate(), PGSharedMemoryNoReAttach(), PGSharedMemoryReAttach(), pgss_shmem_startup(), PostgresMain(), process_postgres_switches(), process_settings(), ProcKill(), readRecoveryCommandFile(), register_unlink(), RegisterBackgroundWorker(), RegisterDynamicBackgroundWorker(), ReplicationSlotAcquire(), RequestAddinShmemSpace(), RequestNamedLWLockTranche(), SendPostmasterSignal(), set_config_option(), set_config_sourcefile(), set_ps_display(), SetMultiXactIdLimit(), SetTransactionIdLimit(), ShmemInitStruct(), SimpleLruInit(), standard_planner(), StartupXLOG(), superuser_arg(), SyncScanShmemInit(), TwoPhaseShmemInit(), verify_dictoptions(), WaitLatchOrSocket(), XLogArchiveNotify(), and XLogWrite().

◆ local_preload_libraries_string

char* local_preload_libraries_string

Definition at line 1535 of file miscinit.c.

Referenced by process_session_preload_libraries().

◆ maintenance_work_mem

◆ max_parallel_maintenance_workers

PGDLLIMPORT int max_parallel_maintenance_workers

Definition at line 122 of file globals.c.

Referenced by plan_create_index_workers().

◆ max_parallel_workers

PGDLLIMPORT int max_parallel_workers

Definition at line 133 of file globals.c.

Referenced by RegisterDynamicBackgroundWorker().

◆ max_worker_processes

◆ MaxBackends

◆ MaxConnections

◆ Mode

Definition at line 60 of file miscinit.c.

◆ my_exec_path

◆ MyAuxProcType

AuxProcType MyAuxProcType

Definition at line 70 of file bootstrap.c.

Referenced by AuxiliaryProcessMain(), pgstat_bestart(), and pgstat_initialize().

◆ MyCancelKey

◆ MyDatabaseId

PGDLLIMPORT Oid MyDatabaseId

Definition at line 84 of file globals.c.

Referenced by AfterTriggerSetState(), AlterDatabase(), AlterObjectRename_internal(), AlterPublicationOwner_internal(), AlterSchemaOwner_internal(), AlterSubscription(), AlterSubscriptionOwner(), asyncQueueNotificationToEntry(), asyncQueueProcessPageEntries(), AutoVacuumRequestWork(), backend_read_statsfile(), CacheInvalidateCatalog(), CacheInvalidateHeapTuple(), CacheInvalidateRelcache(), CacheInvalidateRelcacheByTuple(), CheckLogicalDecodingRequirements(), CheckMyDatabase(), checkSharedDependencies(), classIdGetDbId(), CreateDecodingContext(), CreateInitDecodingContext(), CreateProceduralLanguage(), 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(), get_subscription_oid(), GetCurrentVirtualXIDs(), GetNewRelFileNode(), GetOldestXmin(), IdentifySystem(), ImportSnapshot(), InitializeParallelDSM(), InitPostgres(), InitTempTableNamespace(), isTempNamespaceInUse(), lazy_vacuum_rel(), libpqrcv_exec(), LocalExecuteInvalidationMessage(), 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(), movedb(), perform_relmap_update(), perform_work_item(), pg_namespace_aclmask(), pg_relation_filepath(), pgss_store(), pgstat_beshutdown_hook(), pgstat_bestart(), pgstat_drop_database(), pgstat_fetch_stat_funcentry(), pgstat_fetch_stat_tabentry(), pgstat_report_analyze(), pgstat_report_deadlock(), pgstat_report_recovery_conflict(), pgstat_report_stat(), pgstat_report_tempfile(), pgstat_report_vacuum(), pgstat_reset_counters(), pgstat_reset_single_counter(), pgstat_send_funcstats(), pgstat_vacuum_stat(), PrepareToInvalidateCacheTuple(), PrepareTransaction(), ProcArrayInstallImportedXmin(), ProcArrayInstallRestoredXmin(), RangeVarGetAndCheckCreationNamespace(), RangeVarGetCreationNamespace(), RangeVarGetRelidExtended(), ReindexMultipleTables(), RelationInitLockInfo(), RelationInitPhysicalAddr(), RelationMapFinishBootstrap(), RenameDatabase(), RenameSchema(), ReplicationSlotCreate(), ScanPgRelation(), sepgsql_schema_post_create(), SetLocktagRelationOid(), shdepDropOwned(), shdepReassignOwned(), table_recheck_autovac(), transformColumnRef(), UnlockDatabaseObject(), UpdateLogicalMappings(), vac_truncate_clog(), vac_update_datfrozenxid(), vacuum_is_relation_owner(), XactLogAbortRecord(), and XactLogCommitRecord().

◆ MyDatabaseTableSpace

◆ MyLatch

PGDLLIMPORT struct Latch* MyLatch

Definition at line 53 of file globals.c.

Referenced by ApplyLauncherMain(), ArchSigHupHandler(), ArchSigTermHandler(), AutoVacLauncherMain(), av_sighup_handler(), avl_sigterm_handler(), avl_sigusr2_handler(), BackgroundWriterMain(), be_tls_open_server(), BgSigHupHandler(), CheckDeadLockAlert(), CheckpointerMain(), ChkptSigHupHandler(), ConditionVariablePrepareToSleep(), ConditionVariableSleep(), copy_read_data(), die(), gather_readnext(), handle_sig_alarm(), handle_sigterm(), HandleCatchupInterrupt(), HandleNotifyInterrupt(), HandleParallelMessageInterrupt(), IdleInTransactionSessionTimeoutHandler(), initialize_worker_spi(), InitPostmasterChild(), InitStandaloneProcess(), libpqrcv_connect(), libpqrcv_PQexec(), logicalrep_launcher_sighup(), logicalrep_worker_sighup(), logicalrep_worker_stop(), LogicalRepApplyLoop(), mq_putmessage(), pg_sleep(), pgarch_MainLoop(), pgarch_waken(), pgarch_waken_stop(), pgfdw_get_cleanup_result(), pgfdw_get_result(), pgstat_exit(), pgstat_sighup_handler(), PgstatCollectorMain(), PostgresSigHupHandler(), pq_init(), procsignal_sigusr1_handler(), ProcSleep(), ProcWaitForSignal(), RecoveryConflictInterrupt(), ReqCheckpointHandler(), ReqShutdownHandler(), secure_read(), secure_write(), shm_mq_receive_bytes(), shm_mq_send_bytes(), shm_mq_wait_internal(), sigHupHandler(), sigUsr1Handler(), StatementCancelHandler(), SwitchBackToLocalLatch(), SwitchToSharedLatch(), SyncRepWaitForLSN(), SysLoggerMain(), test_shm_mq_pipelined(), throttle(), wait_for_relation_state_change(), wait_for_worker_state_change(), wait_for_workers_to_become_ready(), WaitForBackgroundWorkerShutdown(), WaitForBackgroundWorkerStartup(), WaitForParallelWorkersToAttach(), WaitForParallelWorkersToFinish(), WaitForReplicationWorkerAttach(), WalShutdownHandler(), WalSigHupHandler(), WalSndLastCycleHandler(), WalSndLoop(), WalSndWaitForWal(), WalSndWriteData(), WalWriterMain(), worker_spi_sighup(), worker_spi_sigterm(), and write_syslogger_file().

◆ MyPMChildSlot

◆ MyProcPid

PGDLLIMPORT int MyProcPid

Definition at line 40 of file globals.c.

Referenced by AddWaitEventToSet(), ApplyLauncherMain(), apw_detach_shmem(), apw_dump_now(), apw_load_buffers(), apw_start_database_worker(), apw_start_master_worker(), Async_Listen(), Async_Unlisten(), Async_UnlistenAll(), asyncQueueNotificationToEntry(), asyncQueueReadAllNotifications(), asyncQueueUnregister(), autoprewarm_main(), AutoVacLauncherMain(), BackendRun(), CheckpointerMain(), CleanupProcSignalState(), DisownLatch(), Exec_ListenPreCommit(), Exec_UnlistenAllCommit(), Exec_UnlistenCommit(), ExportSnapshot(), GetSerializableTransactionSnapshotInt(), HandleWalSndInitStopping(), InitAuxiliaryProcess(), InitializeLatchSupport(), InitializeParallelDSM(), InitLatch(), InitPostmasterChild(), InitPostmasterDeathWatchHandle(), InitProcess(), InitStandaloneProcess(), InitWalSenderSlot(), IsLogicalLauncher(), LaunchParallelWorkers(), llvm_compile_module(), LockBufferForCleanup(), LockTimeoutHandler(), log_line_prefix(), logicalrep_worker_launch(), OpenTemporaryFileInTablespace(), OwnLatch(), ParallelWorkerMain(), pg_backend_pid(), pgstat_bestart(), PostgresMain(), PostmasterMain(), ProcSignalInit(), ProcSleep(), PublishStartupProcessInformation(), ReplicationOriginExitCleanup(), ReplicationSlotAcquire(), ReplicationSlotCleanup(), ReplicationSlotCreate(), ReplicationSlotsDropDBSlots(), replorigin_session_setup(), ResetLatch(), ServerLoop(), set_ps_display(), SetLatch(), setup_background_workers(), SharedFileSetInit(), SharedInvalBackendInit(), SignalBackends(), SnapBuildSerialize(), StatementTimeoutHandler(), UnlockBuffers(), WalRcvDie(), WalReceiverMain(), worker_spi_launch(), write_csvlog(), write_pipe_chunks(), and write_relcache_init_file().

◆ MyProcPort

◆ MyStartTime

◆ NBuffers

PGDLLIMPORT int NBuffers

Definition at line 130 of file globals.c.

◆ OutputFileName

char OutputFileName[]

Definition at line 69 of file globals.c.

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

◆ pkglib_path

◆ PostmasterPid

◆ ProcDiePending

◆ process_shared_preload_libraries_in_progress

PGDLLIMPORT bool process_shared_preload_libraries_in_progress

◆ QueryCancelHoldoffCount

PGDLLIMPORT volatile uint32 QueryCancelHoldoffCount

Definition at line 37 of file globals.c.

Referenced by errfinish(), and ProcessInterrupts().

◆ QueryCancelPending

◆ session_preload_libraries_string

char* session_preload_libraries_string

Definition at line 1533 of file miscinit.c.

Referenced by process_session_preload_libraries().

◆ shared_preload_libraries_string

char* shared_preload_libraries_string

Definition at line 1534 of file miscinit.c.

Referenced by process_shared_preload_libraries().

◆ trace_recovery_messages

int trace_recovery_messages

Definition at line 466 of file guc.c.

Referenced by StartupXLOG(), and trace_recovery().

◆ vacuum_cleanup_index_scale_factor

double vacuum_cleanup_index_scale_factor

Definition at line 149 of file globals.c.

Referenced by _bt_vacuum_needs_cleanup(), and default_reloptions().

◆ VacuumCostActive

bool VacuumCostActive

◆ VacuumCostBalance

int VacuumCostBalance

◆ VacuumCostDelay

◆ VacuumCostLimit

int VacuumCostLimit

◆ VacuumCostPageDirty

int VacuumCostPageDirty

Definition at line 138 of file globals.c.

Referenced by MarkBufferDirty(), and MarkBufferDirtyHint().

◆ VacuumCostPageHit

int VacuumCostPageHit

Definition at line 136 of file globals.c.

Referenced by ReadBuffer_common().

◆ VacuumCostPageMiss

int VacuumCostPageMiss

Definition at line 137 of file globals.c.

Referenced by ReadBuffer_common().

◆ VacuumPageDirty

int VacuumPageDirty

Definition at line 144 of file globals.c.

Referenced by lazy_vacuum_rel(), MarkBufferDirty(), MarkBufferDirtyHint(), and vacuum().

◆ VacuumPageHit

int VacuumPageHit

Definition at line 142 of file globals.c.

Referenced by lazy_vacuum_rel(), ReadBuffer_common(), and vacuum().

◆ VacuumPageMiss

int VacuumPageMiss

Definition at line 143 of file globals.c.

Referenced by lazy_vacuum_rel(), ReadBuffer_common(), and vacuum().

◆ work_mem

PGDLLIMPORT int work_mem

Definition at line 120 of file globals.c.

Referenced by _bt_parallel_scan_and_sort(), _bt_spools_heapscan(), add_paths_to_grouping_rel(), begin_partition(), brin_page_items(), bt_check_every_level(), BuildTupleHashTable(), choose_hashed_setop(), collectMatchBitmap(), compute_bitmap_pages(), connectby(), consider_groupingsets_paths(), cost_material(), cost_rescan(), create_distinct_paths(), create_gather_merge_path(), create_groupingsets_path(), create_merge_append_path(), create_partial_grouping_paths(), create_sort_path(), create_unique_path(), crosstab(), dblink_get_notify(), deflist_to_tuplestore(), each_worker(), each_worker_jsonb(), elements_worker(), elements_worker_jsonb(), exec_init_tuple_store(), ExecChooseHashTableSize(), ExecInitCteScan(), ExecInitRecursiveUnion(), ExecMakeTableFunctionResult(), ExecMaterial(), ExecParallelHashIncreaseNumBatches(), ExecRecursiveUnion(), ExecSort(), final_cost_hashjoin(), final_cost_mergejoin(), fmgr_sql(), get_crosstab_tuplestore(), GetCurrentFDWTuplestore(), ginInsertCleanup(), initial_cost_mergejoin(), initialize_aggregate(), initialize_phase(), label_sort_with_costsize(), libpqrcv_processTuples(), MakeTransitionCaptureState(), materializeQueryResult(), materializeResult(), MultiExecBitmapIndexScan(), MultiExecBitmapOr(), ordered_set_startup(), pg_available_extension_versions(), pg_available_extensions(), pg_config(), pg_cursor(), pg_event_trigger_ddl_commands(), pg_event_trigger_dropped_objects(), pg_extension_update_paths(), pg_get_replication_slots(), pg_hba_file_rules(), pg_logical_slot_get_changes_guts(), pg_prepared_statement(), pg_show_replication_origin_status(), pg_stat_get_activity(), pg_stat_get_progress_info(), pg_stat_get_subscription(), pg_stat_get_wal_senders(), pg_stat_statements_internal(), pg_stop_backup_v2(), plperl_return_next_internal(), pltcl_init_tuple_store(), populate_recordset_worker(), PortalCreateHoldStore(), show_all_file_settings(), storeRow(), subplan_is_hashable(), tfuncFetchRows(), and xpath_table().