PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
miscadmin.h File Reference
#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 PG_BACKEND_VERSIONSTR   "postgres (PostgreSQL) " PG_VERSION "\n"
 
#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_ROW_LEVEL_DISABLED   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)
 
#define LOCK_FILE_LINE_PID   1
 
#define LOCK_FILE_LINE_DATA_DIR   2
 
#define LOCK_FILE_LINE_START_TIME   3
 
#define LOCK_FILE_LINE_PORT   4
 
#define LOCK_FILE_LINE_SOCKET_DIR   5
 
#define LOCK_FILE_LINE_LISTEN_ADDR   6
 
#define LOCK_FILE_LINE_SHMEM_KEY   7
 

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)
 
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 InRowLevelSecurityDisabled (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 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)
 
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)
 
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
 
volatile bool ClientConnectionLost
 
PGDLLIMPORT volatile uint32 InterruptHoldoffCount
 
PGDLLIMPORT volatile uint32 QueryCancelHoldoffCount
 
PGDLLIMPORT volatile uint32 CritSectionCount
 
pid_t PostmasterPid
 
bool IsPostmasterEnvironment
 
PGDLLIMPORT bool IsUnderPostmaster
 
bool IsBackgroundWorker
 
PGDLLIMPORT bool IsBinaryUpgrade
 
bool ExitOnAnyError
 
PGDLLIMPORT char * DataDir
 
PGDLLIMPORT int NBuffers
 
int MaxBackends
 
int MaxConnections
 
int max_worker_processes
 
PGDLLIMPORT int MyProcPid
 
PGDLLIMPORT pg_time_t MyStartTime
 
PGDLLIMPORT struct PortMyProcPort
 
PGDLLIMPORT struct LatchMyLatch
 
long 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
 
bool allowSystemTableMods
 
PGDLLIMPORT int work_mem
 
PGDLLIMPORT int maintenance_work_mem
 
int VacuumCostPageHit
 
int VacuumCostPageMiss
 
int VacuumCostPageDirty
 
int VacuumCostLimit
 
int VacuumCostDelay
 
int VacuumPageHit
 
int VacuumPageMiss
 
int VacuumPageDirty
 
int VacuumCostBalance
 
bool VacuumCostActive
 
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

#define AmBackgroundWriterProcess ( )    (MyAuxProcType == BgWriterProcess)

Definition at line 400 of file miscadmin.h.

Referenced by ForwardFsyncRequest().

#define AmBootstrapProcess ( )    (MyAuxProcType == BootstrapProcess)

Definition at line 398 of file miscadmin.h.

#define AmCheckpointerProcess ( )    (MyAuxProcType == CheckpointerProcess)
#define AmStartupProcess ( )    (MyAuxProcType == StartupProcess)

Definition at line 399 of file miscadmin.h.

Referenced by HotStandbyActiveInReplay(), mdinit(), and TruncateMultiXact().

#define AmWalReceiverProcess ( )    (MyAuxProcType == WalReceiverProcess)

Definition at line 403 of file miscadmin.h.

Referenced by get_sync_bit().

#define AmWalWriterProcess ( )    (MyAuxProcType == WalWriterProcess)

Definition at line 402 of file miscadmin.h.

#define CHECK_FOR_INTERRUPTS ( )
Value:
do { \
} while(0)
PGDLLIMPORT volatile bool InterruptPending
Definition: globals.c:29
void ProcessInterrupts(void)
Definition: postgres.c:2844

Definition at line 96 of file miscadmin.h.

Referenced by _bt_buildadd(), _bt_steppage(), _bt_walk_left(), _hash_metapinit(), _hash_readnext(), _hash_readprev(), add_path(), analyze_rel(), ATRewriteTable(), backend_read_statsfile(), BipartiteMatch(), brin_evacuate_page(), brin_getinsertbuffer(), brin_vacuum_scan(), bringetbitmap(), brinGetTupleForHeapBlock(), brininsert(), brinsummarize(), btree_xlog_delete_get_latestRemovedXid(), calculate_database_size(), calculate_relation_size(), calculate_tablespace_size(), ClientAuthentication(), cluster_rel(), copy_file(), copy_heap_data(), copy_messages(), copy_relation_data(), copydir(), CopyFrom(), CopyTo(), count_nondeletable_pages(), CountOtherDBBackends(), db_dir_size(), DecodingContextFindStartpoint(), do_autovacuum(), do_pg_stop_backup(), errfinish(), exec_execute_message(), exec_parse_message(), exec_replication_command(), exec_simple_query(), exec_stmt(), exec_stmts(), ExecHashJoin(), ExecMakeTableFunctionResult(), ExecProcNode(), ExecScan(), fsm_vacuum_page(), get_query_def(), get_rule_expr(), get_setop_query(), GetMultiXactIdMembers(), GetNewOidWithIndex(), GetNewRelFileNode(), getNextNearest(), ginbuild(), ginBuildCallback(), gingetbitmap(), ginInsertCleanup(), gistgetbitmap(), gistgettuple(), gistProcessItup(), HandleFunctionRequest(), HandleParallelMessages(), heap_lock_updated_tuple_rec(), heap_multi_insert(), heapgetpage(), hypothetical_dense_rank_final(), hypothetical_rank_common(), ident_inet(), IndexBuildHeapRangeScan(), IndexCheckExclusion(), interactive_getc(), lazy_truncate_heap(), logical_read_local_xlog_page(), make_bounded_heap(), md5_crypt_verify(), mode_final(), mq_putmessage(), MultiExecBitmapIndexScan(), MultiExecProcNode(), numeric_fac(), pg_logical_slot_get_changes_guts(), pg_prewarm(), pg_sleep(), PGSemaphoreLock(), pgstat_collect_oids(), pgstat_get_backend_current_activity(), pgstat_heap(), pgstat_index(), pgstat_read_current_status(), pgstat_vacuum_stat(), pgstatindex_impl(), plperl_spi_prepare(), PortalRunMulti(), postgresAcquireSampleRowsFunc(), PostgresMain(), predicate_implied_by_simple_clause(), predicate_refuted_by_simple_clause(), ProcessClientReadInterrupt(), ProcessClientWriteInterrupt(), ProcessWalRcvInterrupts(), ProcSleep(), ProcWaitForSignal(), puttuple_common(), random_relative_prime(), RE_compile_and_cache(), RE_wchar_execute(), refresh_matview_datafill(), regexp_fixed_prefix(), replace_text(), replace_text_regexp(), replorigin_create(), RequestCheckpoint(), revmap_extend_and_get_blkno(), sendAuthRequest(), sendDir(), 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(), throttle(), toast_save_datum(), tuplesort_heap_insert(), tuplesort_heap_siftup(), tuplesort_skiptuples(), tuplestore_skiptuples(), vacuum_delay_point(), vacuum_rel(), validate_index_heapscan(), wait_for_workers_to_become_ready(), wait_pid(), WaitForBackgroundWorkerShutdown(), WaitForBackgroundWorkerStartup(), WaitForParallelWorkersToFinish(), walkdir(), WalSndLoop(), WalSndWaitForWal(), and WalSndWriteData().

#define DATEORDER_DMY   1
#define DATEORDER_MDY   2

Definition at line 216 of file miscadmin.h.

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

#define DATEORDER_YMD   0

Definition at line 214 of file miscadmin.h.

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

#define END_CRIT_SECTION ( )
Value:
do { \
} while(0)
#define Assert(condition)
Definition: c.h:661
PGDLLIMPORT volatile uint32 CritSectionCount
Definition: globals.c:35

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(), _hash_expandtable(), AbsorbFsyncRequests(), addLeafTuple(), AlterSequence(), brin_doinsert(), brin_doupdate(), brin_initialize_empty_new_buffer(), brinbuildempty(), CreateCheckPoint(), CreateEndOfRecoveryRecord(), createPostingTree(), CreateSlotOnDisk(), do_setval(), doPickSplit(), EndPrepare(), fill_seq_with_data(), ginbuild(), ginbuildempty(), ginbulkdelete(), ginDeletePage(), ginHeapTupleFastInsert(), ginPlaceToPage(), ginUpdateStats(), ginVacuumPostingTreeLeaf(), gistbuild(), gistbuildempty(), gistbulkdelete(), gistplacetopage(), 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(), ReplicationSlotDropAcquired(), RestoreSlotFromDisk(), revmap_physical_extend(), SaveSlotToPath(), shiftList(), SlruPhysicalWritePage(), spgAddNodeAction(), spgbuild(), spgSplitNodeAction(), UpdateFullPageWrites(), vacuumLeafPage(), vacuumLeafRoot(), vacuumRedirectAndPlaceholder(), visibilitymap_set(), write_relmap_file(), writeListPage(), XLogBackgroundFlush(), XLogFlush(), and XLogInsertRecord().

#define GetProcessingMode ( )    Mode

Definition at line 365 of file miscadmin.h.

#define HOLD_CANCEL_INTERRUPTS ( )    (QueryCancelHoldoffCount++)

Definition at line 121 of file miscadmin.h.

Referenced by CopyGetData(), and SocketBackend().

#define INTSTYLE_ISO_8601   3

Definition at line 231 of file miscadmin.h.

Referenced by EncodeInterval().

#define INTSTYLE_POSTGRES   0

Definition at line 228 of file miscadmin.h.

Referenced by EncodeInterval(), and set_transmission_modes().

#define INTSTYLE_POSTGRES_VERBOSE   1

Definition at line 229 of file miscadmin.h.

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

#define INTSTYLE_SQL_STANDARD   2

Definition at line 230 of file miscadmin.h.

Referenced by DecodeInterval(), and EncodeInterval().

#define IsInitProcessingMode ( )    (Mode == InitProcessing)
#define IsNormalProcessingMode ( )    (Mode == NormalProcessing)
#define LOCK_FILE_LINE_DATA_DIR   2

Definition at line 443 of file miscadmin.h.

#define LOCK_FILE_LINE_LISTEN_ADDR   6

Definition at line 447 of file miscadmin.h.

Referenced by PostmasterMain(), and test_postmaster_connection().

#define LOCK_FILE_LINE_PID   1

Definition at line 442 of file miscadmin.h.

Referenced by test_postmaster_connection().

#define LOCK_FILE_LINE_PORT   4

Definition at line 445 of file miscadmin.h.

Referenced by get_sock_dir(), and test_postmaster_connection().

#define LOCK_FILE_LINE_SHMEM_KEY   7

Definition at line 448 of file miscadmin.h.

Referenced by CreateLockFile(), and InternalIpcMemoryCreate().

#define LOCK_FILE_LINE_SOCKET_DIR   5

Definition at line 446 of file miscadmin.h.

Referenced by get_sock_dir(), PostmasterMain(), and test_postmaster_connection().

#define LOCK_FILE_LINE_START_TIME   3

Definition at line 444 of file miscadmin.h.

Referenced by test_postmaster_connection().

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

Definition at line 235 of file miscadmin.h.

Referenced by abstime2tm(), and EncodeDateTime().

#define PG_BACKEND_VERSIONSTR   "postgres (PostgreSQL) " PG_VERSION "\n"

Definition at line 29 of file miscadmin.h.

Referenced by adjust_data_dir(), do_start(), getInstallationPaths(), and setup_bin_paths().

#define RESUME_CANCEL_INTERRUPTS ( )
Value:
do { \
} while(0)
PGDLLIMPORT volatile uint32 QueryCancelHoldoffCount
Definition: globals.c:34
#define Assert(condition)
Definition: c.h:661

Definition at line 123 of file miscadmin.h.

Referenced by CopyGetData(), and SocketBackend().

#define SECURITY_RESTRICTED_OPERATION   0x0002
#define SECURITY_ROW_LEVEL_DISABLED   0x0004

Definition at line 289 of file miscadmin.h.

Referenced by InRowLevelSecurityDisabled(), and ri_PlanCheck().

#define SetProcessingMode (   mode)
#define START_CRIT_SECTION ( )    (CritSectionCount++)

Definition at line 129 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(), _hash_expandtable(), AbsorbFsyncRequests(), addLeafTuple(), AlterSequence(), brin_doinsert(), brin_doupdate(), brin_initialize_empty_new_buffer(), brinbuildempty(), CreateCheckPoint(), CreateEndOfRecoveryRecord(), createPostingTree(), CreateSlotOnDisk(), dataPlaceToPageInternal(), dataPlaceToPageLeaf(), do_setval(), doPickSplit(), EndPrepare(), entryPlaceToPage(), fill_seq_with_data(), GetNewMultiXactId(), ginbuild(), ginbuildempty(), ginbulkdelete(), ginDeletePage(), ginHeapTupleFastInsert(), ginPlaceToPage(), ginUpdateStats(), ginVacuumPostingTreeLeaf(), gistbuild(), gistbuildempty(), gistbulkdelete(), gistplacetopage(), 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(), ReplicationSlotDropAcquired(), RestoreSlotFromDisk(), revmap_physical_extend(), SaveSlotToPath(), shiftList(), SlruPhysicalWritePage(), spgAddNodeAction(), spgbuild(), spgSplitNodeAction(), UpdateFullPageWrites(), vacuumLeafPage(), vacuumLeafRoot(), vacuumRedirectAndPlaceholder(), visibilitymap_set(), write_relmap_file(), writeListPage(), XLogBackgroundFlush(), XLogFlush(), and XLogInsertRecord().

#define USE_GERMAN_DATES   3

Definition at line 210 of file miscadmin.h.

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

#define USE_ISO_DATES   1
#define USE_POSTGRES_DATES   0

Definition at line 207 of file miscadmin.h.

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

#define USE_SQL_DATES   2

Definition at line 209 of file miscadmin.h.

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

#define USE_XSD_DATES   4

Typedef Documentation

Definition at line 265 of file miscadmin.h.

Enumeration Type Documentation

Enumerator
NotAnAuxProcess 
CheckerProcess 
BootstrapProcess 
StartupProcess 
BgWriterProcess 
CheckpointerProcess 
WalWriterProcess 
WalReceiverProcess 
NUM_AUXPROCTYPES 

Definition at line 382 of file miscadmin.h.

Enumerator
BootstrapProcessing 
InitProcessing 
NormalProcessing 

Definition at line 352 of file miscadmin.h.

353 {
354  BootstrapProcessing, /* bootstrap creation of template database */
355  InitProcessing, /* initializing system */
356  NormalProcessing /* normal processing */
ProcessingMode
Definition: miscadmin.h:352

Function Documentation

void AddToDataDirLockFile ( int  target_line,
const char *  str 
)

Definition at line 1115 of file miscinit.c.

References close, DIRECTORY_LOCK_FILE, elog, ereport, errcode_for_file_access(), errmsg(), fd(), LOG, NULL, PG_BINARY, pg_fsync(), read, snprintf(), and write.

Referenced by InternalIpcMemoryCreate(), and PostmasterMain().

1116 {
1117  int fd;
1118  int len;
1119  int lineno;
1120  char *srcptr;
1121  char *destptr;
1122  char srcbuffer[BLCKSZ];
1123  char destbuffer[BLCKSZ];
1124 
1125  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1126  if (fd < 0)
1127  {
1128  ereport(LOG,
1130  errmsg("could not open file \"%s\": %m",
1132  return;
1133  }
1134  len = read(fd, srcbuffer, sizeof(srcbuffer) - 1);
1135  if (len < 0)
1136  {
1137  ereport(LOG,
1139  errmsg("could not read from file \"%s\": %m",
1141  close(fd);
1142  return;
1143  }
1144  srcbuffer[len] = '\0';
1145 
1146  /*
1147  * Advance over lines we are not supposed to rewrite, then copy them to
1148  * destbuffer.
1149  */
1150  srcptr = srcbuffer;
1151  for (lineno = 1; lineno < target_line; lineno++)
1152  {
1153  if ((srcptr = strchr(srcptr, '\n')) == NULL)
1154  {
1155  elog(LOG, "incomplete data in \"%s\": found only %d newlines while trying to add line %d",
1156  DIRECTORY_LOCK_FILE, lineno - 1, target_line);
1157  close(fd);
1158  return;
1159  }
1160  srcptr++;
1161  }
1162  memcpy(destbuffer, srcbuffer, srcptr - srcbuffer);
1163  destptr = destbuffer + (srcptr - srcbuffer);
1164 
1165  /*
1166  * Write or rewrite the target line.
1167  */
1168  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s\n", str);
1169  destptr += strlen(destptr);
1170 
1171  /*
1172  * If there are more lines in the old file, append them to destbuffer.
1173  */
1174  if ((srcptr = strchr(srcptr, '\n')) != NULL)
1175  {
1176  srcptr++;
1177  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s",
1178  srcptr);
1179  }
1180 
1181  /*
1182  * And rewrite the data. Since we write in a single kernel call, this
1183  * update should appear atomic to onlookers.
1184  */
1185  len = strlen(destbuffer);
1186  errno = 0;
1187  if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
1188  (int) write(fd, destbuffer, len) != len)
1189  {
1190  /* if write didn't set errno, assume problem is no disk space */
1191  if (errno == 0)
1192  errno = ENOSPC;
1193  ereport(LOG,
1195  errmsg("could not write to file \"%s\": %m",
1197  close(fd);
1198  return;
1199  }
1200  if (pg_fsync(fd) != 0)
1201  {
1202  ereport(LOG,
1204  errmsg("could not write to file \"%s\": %m",
1206  }
1207  if (close(fd) != 0)
1208  {
1209  ereport(LOG,
1211  errmsg("could not write to file \"%s\": %m",
1213  }
1214 }
#define write(a, b, c)
Definition: win32.h:19
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:52
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:1012
int errcode_for_file_access(void)
Definition: elog.c:592
#define ereport(elevel, rest)
Definition: elog.h:132
#define NULL
Definition: c.h:215
int errmsg(const char *fmt,...)
Definition: elog.c:791
int pg_fsync(int fd)
Definition: fd.c:316
#define elog
Definition: elog.h:228
#define close(a)
Definition: win32.h:17
#define read(a, b, c)
Definition: win32.h:18
bool BackupInProgress ( void  )

Definition at line 10886 of file xlog.c.

References BACKUP_LABEL_FILE.

Referenced by pg_is_in_backup(), and PostmasterStateMachine().

10887 {
10888  struct stat stat_buf;
10889 
10890  return (stat(BACKUP_LABEL_FILE, &stat_buf) == 0);
10891 }
struct stat stat_buf
Definition: pg_standby.c:101
#define BACKUP_LABEL_FILE
Definition: xlog.h:284
void BaseInit ( void  )

Definition at line 517 of file postinit.c.

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

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

518 {
519  /*
520  * Attach to shared memory and semaphores, and initialize our
521  * input/output/debugging file descriptors.
522  */
524  DebugFileOpen();
525 
526  /* Do local initialization of file, storage and buffer managers */
527  InitFileAccess();
528  smgrinit();
530 }
static void InitCommunication(void)
Definition: postinit.c:409
void InitBufferPoolAccess(void)
Definition: bufmgr.c:2098
void DebugFileOpen(void)
Definition: elog.c:1838
void smgrinit(void)
Definition: smgr.c:100
void InitFileAccess(void)
Definition: fd.c:472
void CancelBackup ( void  )

Definition at line 10906 of file xlog.c.

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

Referenced by PostmasterStateMachine().

10907 {
10908  struct stat stat_buf;
10909 
10910  /* if the file is not there, return */
10911  if (stat(BACKUP_LABEL_FILE, &stat_buf) < 0)
10912  return;
10913 
10914  /* remove leftover file from previously canceled backup if it exists */
10916 
10917  if (rename(BACKUP_LABEL_FILE, BACKUP_LABEL_OLD) == 0)
10918  {
10919  ereport(LOG,
10920  (errmsg("online backup mode canceled"),
10921  errdetail("\"%s\" was renamed to \"%s\".",
10923  }
10924  else
10925  {
10926  ereport(WARNING,
10928  errmsg("online backup mode was not canceled"),
10929  errdetail("Could not rename \"%s\" to \"%s\": %m.",
10931  }
10932 
10933  /* if the tablespace_map file is not there, return */
10934  if (stat(TABLESPACE_MAP, &stat_buf) < 0)
10935  return;
10936 
10937  /* remove leftover file from previously canceled backup if it exists */
10939 
10940  if (rename(TABLESPACE_MAP, TABLESPACE_MAP_OLD) == 0)
10941  {
10942  ereport(LOG,
10943  (errmsg("online backup mode canceled"),
10944  errdetail("\"%s\" was renamed to \"%s\".",
10946  }
10947  else
10948  {
10949  ereport(WARNING,
10951  errmsg("online backup mode was not canceled"),
10952  errdetail("Could not rename \"%s\" to \"%s\": %m.",
10954  }
10955 }
#define LOG
Definition: elog.h:26
#define BACKUP_LABEL_OLD
Definition: xlog.h:285
#define TABLESPACE_MAP
Definition: xlog.h:287
struct stat stat_buf
Definition: pg_standby.c:101
int errdetail(const char *fmt,...)
Definition: elog.c:864
int errcode_for_file_access(void)
Definition: elog.c:592
int unlink(const char *filename)
#define ereport(elevel, rest)
Definition: elog.h:132
#define WARNING
Definition: elog.h:38
#define TABLESPACE_MAP_OLD
Definition: xlog.h:288
int errmsg(const char *fmt,...)
Definition: elog.c:791
#define BACKUP_LABEL_FILE
Definition: xlog.h:284
void ChangeToDataDir ( void  )

Definition at line 113 of file miscinit.c.

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

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

114 {
116 
117  if (chdir(DataDir) < 0)
118  ereport(FATAL,
120  errmsg("could not change directory to \"%s\": %m",
121  DataDir)));
122 }
#define AssertState(condition)
Definition: c.h:664
#define FATAL
Definition: elog.h:50
int errcode_for_file_access(void)
Definition: elog.c:592
#define ereport(elevel, rest)
Definition: elog.h:132
int errmsg(const char *fmt,...)
Definition: elog.c:791
char * DataDir
Definition: globals.c:58
void check_stack_depth ( void  )

Definition at line 3089 of file postgres.c.

References ereport, errcode(), errhint(), errmsg(), ERROR, max_stack_depth, max_stack_depth_bytes, NULL, and stack_base_ptr.

Referenced by addone(), clean_fakeval_intree(), clean_NOT_intree(), cntsize(), contains_required_value(), convertJsonbValue(), copyObject(), Cover(), dofindsubquery(), EventTriggerInvoke(), ExecInitExpr(), ExecMakeFunctionResult(), ExecMakeFunctionResultNoSets(), execute(), expression_tree_mutator(), expression_tree_walker(), fillQT(), findoprnd(), findoprnd_recurse(), flatten_grouping_sets(), freetree(), get_query_def(), get_rule_expr(), get_setop_query(), gistSplit(), hk_depth_search(), infix(), inline_set_returning_function(), int_query_opr_selec(), JsonbDeepContains(), JumbleExpr(), makepol(), plainnode(), plperl_hash_from_tuple(), plperl_sv_to_datum(), QT2QTN(), QTNBinary(), QTNClearFlags(), QTNCopy(), QTNFree(), QTNodeCompare(), QTNSort(), QTNTernary(), raw_expression_tree_walker(), split_array(), transformExprRecurse(), transformSetOperationTree(), TS_execute(), TS_execute_ternary(), tsquery_opr_selec(), and tsquery_requires_match().

3090 {
3091  char stack_top_loc;
3092  long stack_depth;
3093 
3094  /*
3095  * Compute distance from reference point to my local variables
3096  */
3097  stack_depth = (long) (stack_base_ptr - &stack_top_loc);
3098 
3099  /*
3100  * Take abs value, since stacks grow up on some machines, down on others
3101  */
3102  if (stack_depth < 0)
3103  stack_depth = -stack_depth;
3104 
3105  /*
3106  * Trouble?
3107  *
3108  * The test on stack_base_ptr prevents us from erroring out if called
3109  * during process setup or in a non-backend process. Logically it should
3110  * be done first, but putting it here avoids wasting cycles during normal
3111  * cases.
3112  */
3113  if (stack_depth > max_stack_depth_bytes &&
3114  stack_base_ptr != NULL)
3115  {
3116  ereport(ERROR,
3117  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3118  errmsg("stack depth limit exceeded"),
3119  errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3120  "after ensuring the platform's stack depth limit is adequate.",
3121  max_stack_depth)));
3122  }
3123 
3124  /*
3125  * On IA64 there is a separate "register" stack that requires its own
3126  * independent check. For this, we have to measure the change in the
3127  * "BSP" pointer from PostgresMain to here. Logic is just as above,
3128  * except that we know IA64's register stack grows up.
3129  *
3130  * Note we assume that the same max_stack_depth applies to both stacks.
3131  */
3132 #if defined(__ia64__) || defined(__ia64)
3133  stack_depth = (long) (ia64_get_bsp() - register_stack_base_ptr);
3134 
3135  if (stack_depth > max_stack_depth_bytes &&
3136  register_stack_base_ptr != NULL)
3137  {
3138  ereport(ERROR,
3139  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3140  errmsg("stack depth limit exceeded"),
3141  errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3142  "after ensuring the platform's stack depth limit is adequate.",
3143  max_stack_depth)));
3144  }
3145 #endif /* IA64 */
3146 }
int errhint(const char *fmt,...)
Definition: elog.c:978
int errcode(int sqlerrcode)
Definition: elog.c:569
#define ERROR
Definition: elog.h:41
#define ereport(elevel, rest)
Definition: elog.h:132
int max_stack_depth
Definition: postgres.c:94
static long max_stack_depth_bytes
Definition: postgres.c:107
#define NULL
Definition: c.h:215
char * stack_base_ptr
Definition: postgres.c:115
int errmsg(const char *fmt,...)
Definition: elog.c:791
void CreateDataDirLockFile ( bool  amPostmaster)

Definition at line 1039 of file miscinit.c.

References CreateLockFile(), DataDir, and DIRECTORY_LOCK_FILE.

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

1040 {
1041  CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, "", true, DataDir);
1042 }
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:52
static void CreateLockFile(const char *filename, bool amPostmaster, const char *socketDir, bool isDDLock, const char *refName)
Definition: miscinit.c:734
char * DataDir
Definition: globals.c:58
void CreateSocketLockFile ( const char *  socketfile,
bool  amPostmaster,
const char *  socketDir 
)

Definition at line 1048 of file miscinit.c.

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

1050 {
1051  char lockfile[MAXPGPATH];
1052 
1053  snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
1054  CreateLockFile(lockfile, amPostmaster, socketDir, false, socketfile);
1055 }
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:734
#define MAXPGPATH
Oid GetAuthenticatedUserId ( void  )

Definition at line 333 of file miscinit.c.

References AssertState, AuthenticatedUserId, and OidIsValid.

Referenced by InitializeParallelDSM().

334 {
336  return AuthenticatedUserId;
337 }
#define AssertState(condition)
Definition: c.h:664
#define OidIsValid(objectId)
Definition: c.h:524
static Oid AuthenticatedUserId
Definition: miscinit.c:153
Oid GetCurrentRoleId ( void  )

Definition at line 612 of file miscinit.c.

References InvalidOid, OuterUserId, and SetRoleIsActive.

Referenced by show_role().

613 {
614  if (SetRoleIsActive)
615  return OuterUserId;
616  else
617  return InvalidOid;
618 }
static Oid OuterUserId
Definition: miscinit.c:155
#define InvalidOid
Definition: postgres_ext.h:36
static bool SetRoleIsActive
Definition: miscinit.c:165
Oid GetOuterUserId ( void  )

Definition at line 285 of file miscinit.c.

References AssertState, OidIsValid, and OuterUserId.

Referenced by DropRole(), and RenameRole().

286 {
288  return OuterUserId;
289 }
#define AssertState(condition)
Definition: c.h:664
static Oid OuterUserId
Definition: miscinit.c:155
#define OidIsValid(objectId)
Definition: c.h:524
Oid GetSessionUserId ( void  )

Definition at line 308 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().

309 {
311  return SessionUserId;
312 }
#define AssertState(condition)
Definition: c.h:664
static Oid SessionUserId
Definition: miscinit.c:154
#define OidIsValid(objectId)
Definition: c.h:524
Oid GetUserId ( void  )

Definition at line 274 of file miscinit.c.

References AssertState, CurrentUserId, and OidIsValid.

Referenced by AddRoleMems(), AggregateCreate(), AlterDatabase(), AlterDatabaseOwner(), AlterDatabaseSet(), AlterEventTrigger(), AlterEventTriggerOwner_internal(), AlterExtensionNamespace(), AlterForeignServer(), AlterForeignServerOwner_internal(), AlterFunction(), AlterObjectNamespace_internal(), AlterObjectOwner_internal(), AlterObjectRename_internal(), AlterOperator(), AlterOpFamilyAdd(), AlterRole(), AlterRoleSet(), AlterSchemaOwner_internal(), AlterSequence(), AlterTableMoveAll(), AlterTableSpaceOptions(), AlterTSConfiguration(), AlterTSDictionary(), AlterTypeNamespace_oid(), AlterTypeOwner(), analyze_rel(), ATExecAddColumn(), ATExecChangeOwner(), ATPrepAlterColumnType(), ATPrepSetStatistics(), ATPrepSetTableSpace(), ATSimplePermissions(), binary_upgrade_create_empty_extension(), BuildDescForRelation(), BuildIndexValueDescription(), calculate_database_size(), calculate_tablespace_size(), check_enable_rls(), check_permissions(), check_temp_tablespaces(), checkDomainOwner(), checkEnumOwner(), checkFkeyPermissions(), CheckFunctionValidatorAccess(), CheckMyDatabase(), cluster_rel(), CommentObject(), compile_plperl_function(), compile_pltcl_function(), compute_return_type(), CreateCast(), CreateConversionCommand(), createdb(), CreateEventTrigger(), CreateExtension(), CreateForeignDataWrapper(), CreateForeignServer(), CreateForeignTable(), CreateFunction(), CreateOpFamily(), CreateProceduralLanguage(), CreateRole(), 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(), dropdb(), DropOwnedObjects(), DropRole(), DropTableSpace(), EnableDisableRule(), ExecAlterDefaultPrivilegesStmt(), ExecAlterExtensionContentsStmt(), ExecAlterExtensionStmt(), ExecBuildSlotValueDescription(), ExecCheckRTEPerms(), ExecEvalArrayCoerceExpr(), ExecGrant_Attribute(), ExecGrant_Database(), ExecGrant_Fdw(), ExecGrant_ForeignServer(), ExecGrant_Function(), ExecGrant_Language(), ExecGrant_Largeobject(), ExecGrant_Namespace(), ExecGrant_Relation(), ExecGrant_Tablespace(), ExecGrant_Type(), ExecInitAgg(), ExecInitWindowAgg(), ExecSecLabelStmt(), ExecuteDoStmt(), ExecuteTruncate(), 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(), 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_fcache(), InitializeSearchPath(), InitPostgres(), InitTempTableNamespace(), inline_function(), inline_set_returning_function(), insert_username(), interpret_function_parameter_list(), inv_create(), LargeObjectCreate(), lastval(), lo_get_fragment_internal(), lo_read(), lo_truncate_internal(), lo_unlink(), lo_write(), LockTableAclCheck(), lookup_agg_function(), LookupCreationNamespace(), LookupExplicitNamespace(), MergeAttributes(), movedb(), nextval_internal(), OperatorCreate(), OperatorShellMake(), pg_has_role_id(), pg_has_role_name(), pg_prewarm(), pg_sequence_parameters(), pg_signal_backend(), pg_start_backup(), 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_waiting(), pg_stat_get_backend_xact_start(), pg_stat_statements_internal(), pg_stop_backup(), pgrowlocks(), pgss_store(), pgstat_get_backend_current_activity(), pltcl_fetch_interp(), postgresBeginForeignModify(), postgresBeginForeignScan(), postgresGetForeignRelSize(), postgresImportForeignSchema(), PrepareTempTablespaces(), PrepareTransaction(), RangeVarCallbackForAlterRelation(), RangeVarCallbackForDropRelation(), RangeVarCallbackForPolicy(), RangeVarCallbackForReindexIndex(), RangeVarCallbackForRenameRule(), RangeVarCallbackForRenameTrigger(), RangeVarCallbackOwnsRelation(), RangeVarCallbackOwnsTable(), RangeVarGetAndCheckCreationNamespace(), ReassignOwnedObjects(), recomputeNamespacePath(), ReindexMultipleTables(), RemoveObjects(), renameatt_check(), RenameDatabase(), RenameSchema(), RenameTableSpace(), RenameType(), RevalidateCachedQuery(), RI_Initial_Check(), ri_ReportViolation(), select_perl_context(), superuser(), timetravel(), transformTableLikeClause(), truncate_check_rel(), user_mapping_ddl_aclcheck(), vacuum_rel(), ValidateJoinEstimator(), and ValidateRestrictionEstimator().

275 {
277  return CurrentUserId;
278 }
#define AssertState(condition)
Definition: c.h:664
#define OidIsValid(objectId)
Definition: c.h:524
static Oid CurrentUserId
Definition: miscinit.c:156
void GetUserIdAndContext ( Oid userid,
bool sec_def_context 
)

Definition at line 424 of file miscinit.c.

References CurrentUserId, and InLocalUserIdChange().

425 {
426  *userid = CurrentUserId;
427  *sec_def_context = InLocalUserIdChange();
428 }
bool InLocalUserIdChange(void)
Definition: miscinit.c:393
static Oid CurrentUserId
Definition: miscinit.c:156
void GetUserIdAndSecContext ( Oid userid,
int *  sec_context 
)
char* GetUserNameFromId ( Oid  roleid,
bool  noerr 
)

Definition at line 668 of file miscinit.c.

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

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

669 {
670  HeapTuple tuple;
671  char *result;
672 
673  tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
674  if (!HeapTupleIsValid(tuple))
675  {
676  if (!noerr)
677  ereport(ERROR,
678  (errcode(ERRCODE_UNDEFINED_OBJECT),
679  errmsg("invalid role OID: %u", roleid)));
680  result = NULL;
681  }
682  else
683  {
684  result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
685  ReleaseSysCache(tuple);
686  }
687  return result;
688 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:631
char * pstrdup(const char *in)
Definition: mcxt.c:1160
int errcode(int sqlerrcode)
Definition: elog.c:569
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:141
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:72
#define ObjectIdGetDatum(X)
Definition: postgres.h:515
#define ERROR
Definition: elog.h:41
#define ereport(elevel, rest)
Definition: elog.h:132
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:989
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:215
int errmsg(const char *fmt,...)
Definition: elog.c:791
#define NameStr(name)
Definition: c.h:488
bool has_rolreplication ( Oid  roleid)

Definition at line 451 of file miscinit.c.

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

Referenced by check_permissions(), InitPostgres(), pg_start_backup(), and pg_stop_backup().

452 {
453  bool result = false;
454  HeapTuple utup;
455 
456  utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
457  if (HeapTupleIsValid(utup))
458  {
459  result = ((Form_pg_authid) GETSTRUCT(utup))->rolreplication;
460  ReleaseSysCache(utup);
461  }
462  return result;
463 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:631
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:141
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:72
#define ObjectIdGetDatum(X)
Definition: postgres.h:515
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:989
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void InitializeMaxBackends ( void  )

Definition at line 495 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().

496 {
497  Assert(MaxBackends == 0);
498 
499  /* the extra unit accounts for the autovacuum launcher */
502 
503  /* internal error because the values were all checked previously */
505  elog(ERROR, "too many backends configured");
506 }
#define ERROR
Definition: elog.h:41
#define MAX_BACKENDS
Definition: postmaster.h:72
int MaxBackends
Definition: globals.c:121
int MaxConnections
Definition: globals.c:119
int autovacuum_max_workers
Definition: autovacuum.c:111
#define Assert(condition)
Definition: c.h:661
int max_worker_processes
Definition: globals.c:120
#define elog
Definition: elog.h:228
void InitializeSessionUserId ( const char *  rolename,
Oid  useroid 
)

Definition at line 469 of file miscinit.c.

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

Referenced by InitPostgres().

470 {
471  HeapTuple roleTup;
472  Form_pg_authid rform;
473 
474  /*
475  * Don't do scans if we're bootstrapping, none of the system catalogs
476  * exist yet, and they should be owned by postgres anyway.
477  */
479 
480  /* call only once */
482 
483  if (rolename != NULL)
484  roleTup = SearchSysCache1(AUTHNAME, PointerGetDatum(rolename));
485  else
486  roleTup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
487  if (!HeapTupleIsValid(roleTup))
488  ereport(FATAL,
489  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
490  errmsg("role \"%s\" does not exist", rolename)));
491 
492  rform = (Form_pg_authid) GETSTRUCT(roleTup);
493  roleid = HeapTupleGetOid(roleTup);
494 
495  AuthenticatedUserId = roleid;
496  AuthenticatedUserIsSuperuser = rform->rolsuper;
497 
498  /* This sets OuterUserId/CurrentUserId too */
500 
501  /* Also mark our PGPROC entry with the authenticated user id */
502  /* (We assume this is an atomic store so no lock is needed) */
503  MyProc->roleId = roleid;
504 
505  /*
506  * These next checks are not enforced when in standalone mode, so that
507  * there is a way to recover from sillinesses like "UPDATE pg_authid SET
508  * rolcanlogin = false;".
509  */
510  if (IsUnderPostmaster)
511  {
512  /*
513  * Is role allowed to login at all?
514  */
515  if (!rform->rolcanlogin)
516  ereport(FATAL,
517  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
518  errmsg("role \"%s\" is not permitted to log in",
519  rolename)));
520 
521  /*
522  * Check connection limit for this role.
523  *
524  * There is a race condition here --- we create our PGPROC before
525  * checking for other PGPROCs. If two backends did this at about the
526  * same time, they might both think they were over the limit, while
527  * ideally one should succeed and one fail. Getting that to work
528  * exactly seems more trouble than it is worth, however; instead we
529  * just document that the connection limit is approximate.
530  */
531  if (rform->rolconnlimit >= 0 &&
533  CountUserBackends(roleid) > rform->rolconnlimit)
534  ereport(FATAL,
535  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
536  errmsg("too many connections for role \"%s\"",
537  rolename)));
538  }
539 
540  /* Record username and superuser status as GUC settings too */
541  SetConfigOption("session_authorization", rolename,
543  SetConfigOption("is_superuser",
544  AuthenticatedUserIsSuperuser ? "on" : "off",
546 
547  ReleaseSysCache(roleTup);
548 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:631
#define AssertState(condition)
Definition: c.h:664
PGPROC * MyProc
Definition: proc.c:63
#define PointerGetDatum(X)
Definition: postgres.h:564
Oid roleId
Definition: proc.h:103
int errcode(int sqlerrcode)
Definition: elog.c:569
#define OidIsValid(objectId)
Definition: c.h:524
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:141
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:72
#define ObjectIdGetDatum(X)
Definition: postgres.h:515
#define FATAL
Definition: elog.h:50
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6394
bool IsUnderPostmaster
Definition: globals.c:97
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:159
#define ereport(elevel, rest)
Definition: elog.h:132
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:989
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:215
int CountUserBackends(Oid roleid)
Definition: procarray.c:2727
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:361
int errmsg(const char *fmt,...)
Definition: elog.c:791
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:670
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:316
static Oid AuthenticatedUserId
Definition: miscinit.c:153
void InitializeSessionUserIdStandalone ( void  )

Definition at line 555 of file miscinit.c.

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

Referenced by InitPostgres().

556 {
557  /*
558  * This function should only be called in single-user mode, in autovacuum
559  * workers, and in background workers.
560  */
562 
563  /* call only once */
565 
568 
570 }
#define AssertState(condition)
Definition: c.h:664
#define OidIsValid(objectId)
Definition: c.h:524
bool IsBackgroundWorker
Definition: globals.c:99
bool IsUnderPostmaster
Definition: globals.c:97
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:159
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:2893
#define BOOTSTRAP_SUPERUSERID
Definition: pg_authid.h:100
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:316
static Oid AuthenticatedUserId
Definition: miscinit.c:153
void InitPostgres ( const char *  in_dbname,
Oid  dboid,
const char *  username,
Oid  useroid,
char *  out_dbname 
)

Definition at line 558 of file postinit.c.

References am_db_walsender, am_walsender, Assert, before_shmem_exit(), CAC_WAITBACKUP, Port::canAcceptConnections, CheckDeadLockAlert(), CheckMyDatabase(), CommitTransactionCommand(), PGPROC::databaseId, DatabaseRelationId, dbname, DEADLOCK_TIMEOUT, DEBUG3, DEFAULTTABLESPACE_OID, elog, EnablePortalManager(), ereport, errcode(), errcode_for_file_access(), errdetail(), errhint(), errmsg(), FATAL, GetDatabasePath(), GetDatabaseTuple(), GetDatabaseTupleByOid(), GetSessionUserId(), GETSTRUCT, GetTransactionSnapshot(), GetUserId(), has_rolreplication(), HaveNFreeProcs(), HeapTupleGetOid, HeapTupleIsValid, InitBufferPoolBackend(), InitCatalogCache(), initialize_acl(), InitializeClientEncoding(), InitializeSearchPath(), InitializeSessionUserId(), InitializeSessionUserIdStandalone(), InitPlanCache(), InitProcessPhase2(), InvalidateCatalogSnapshot(), InvalidBackendId, IsAutoVacuumLauncherProcess(), IsAutoVacuumWorkerProcess(), IsBackgroundWorker, IsBinaryUpgrade, IsBootstrapProcessingMode, IsUnderPostmaster, LOCK_TIMEOUT, LockSharedObject(), LockTimeoutHandler(), MaxBackends, MyBackendId, MyDatabaseId, MyDatabaseTableSpace, MyProc, MyProcPort, NAMEDATALEN, NameStr, NULL, OidIsValid, on_shmem_exit(), PerformAuthentication(), pg_usleep(), pgstat_bestart(), pgstat_initialize(), PostAuthDelay, process_settings(), process_startup_options(), ProcSignalInit(), RecoveryInProgress(), RegisterTimeout(), RelationCacheInitialize(), RelationCacheInitializePhase2(), RelationCacheInitializePhase3(), ReservedBackends, RowExclusiveLock, SetCurrentStatementStartTimestamp(), SetDatabasePath(), SharedInvalBackendInit(), ShutdownPostgres(), ShutdownXLOG(), StartTransactionCommand(), StartupXLOG(), STATEMENT_TIMEOUT, StatementTimeoutHandler(), strlcpy(), superuser(), TemplateDbOid, ThereIsAtLeastOneRole(), ValidatePgVersion(), WARNING, XACT_READ_COMMITTED, and XactIsoLevel.

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

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

Definition at line 173 of file miscinit.c.

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

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

174 {
175  IsUnderPostmaster = true; /* we are a postmaster subprocess now */
176 
177  MyProcPid = getpid(); /* reset MyProcPid */
178 
179  MyStartTime = time(NULL); /* set our start time in case we call elog */
180 
181  /*
182  * make sure stderr is in binary mode before anything can possibly be
183  * written to it, in case it's actually the syslogger pipe, so the pipe
184  * chunking protocol isn't disturbed. Non-logpipe data gets translated on
185  * redirection (e.g. via pg_ctl -l) anyway.
186  */
187 #ifdef WIN32
188  _setmode(fileno(stderr), _O_BINARY);
189 #endif
190 
191  /* We don't want the postmaster's proc_exit() handlers */
192  on_exit_reset();
193 
194  /* Initialize process-local latch support */
198 
199  /*
200  * If possible, make this process a group leader, so that the postmaster
201  * can signal any child processes too. Not all processes will have
202  * children, but for consistency we make all postmaster child processes do
203  * this.
204  */
205 #ifdef HAVE_SETSID
206  if (setsid() < 0)
207  elog(FATAL, "setsid() failed: %m");
208 #endif
209 }
void InitLatch(volatile Latch *latch)
Definition: unix_latch.c:106
int MyProcPid
Definition: globals.c:37
pg_time_t MyStartTime
Definition: globals.c:38
void on_exit_reset(void)
Definition: ipc.c:396
static Latch LocalLatchData
Definition: miscinit.c:59
#define FATAL
Definition: elog.h:50
bool IsUnderPostmaster
Definition: globals.c:97
void InitializeLatchSupport(void)
Definition: unix_latch.c:78
#define NULL
Definition: c.h:215
struct Latch * MyLatch
Definition: globals.c:50
#define elog
Definition: elog.h:228
void InitStandaloneProcess ( const char *  argv0)

Definition at line 217 of file miscinit.c.

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

Referenced by AuxiliaryProcessMain(), and PostgresMain().

218 {
220 
221  MyProcPid = getpid(); /* reset MyProcPid */
222 
223  MyStartTime = time(NULL); /* set our start time in case we call elog */
224 
225  /* Initialize process-local latch support */
229 
230  /* Compute paths, no postmaster to inherit from */
231  if (my_exec_path[0] == '\0')
232  {
233  if (find_my_exec(argv0, my_exec_path) < 0)
234  elog(FATAL, "%s: could not locate my own executable path",
235  argv0);
236  }
237 
238  if (pkglib_path[0] == '\0')
240 }
void InitLatch(volatile Latch *latch)
Definition: unix_latch.c:106
bool IsPostmasterEnvironment
Definition: globals.c:96
static char * argv0
Definition: pg_ctl.c:96
int MyProcPid
Definition: globals.c:37
pg_time_t MyStartTime
Definition: globals.c:38
void get_pkglib_path(const char *my_exec_path, char *ret_path)
Definition: path.c:724
static Latch LocalLatchData
Definition: miscinit.c:59
#define FATAL
Definition: elog.h:50
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:119
void InitializeLatchSupport(void)
Definition: unix_latch.c:78
char my_exec_path[MAXPGPATH]
Definition: globals.c:62
#define NULL
Definition: c.h:215
#define Assert(condition)
Definition: c.h:661
struct Latch * MyLatch
Definition: globals.c:50
#define elog
Definition: elog.h:228
char pkglib_path[MAXPGPATH]
Definition: globals.c:63
bool InLocalUserIdChange ( void  )

Definition at line 393 of file miscinit.c.

References SECURITY_LOCAL_USERID_CHANGE, and SecurityRestrictionContext.

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

394 {
396 }
static int SecurityRestrictionContext
Definition: miscinit.c:162
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:287
bool InRowLevelSecurityDisabled ( void  )

Definition at line 411 of file miscinit.c.

References SECURITY_ROW_LEVEL_DISABLED, and SecurityRestrictionContext.

Referenced by check_enable_rls(), and CreateCachedPlan().

412 {
414 }
static int SecurityRestrictionContext
Definition: miscinit.c:162
#define SECURITY_ROW_LEVEL_DISABLED
Definition: miscadmin.h:289
bool InSecurityRestrictedOperation ( void  )

Definition at line 402 of file miscinit.c.

References SECURITY_RESTRICTED_OPERATION, and SecurityRestrictionContext.

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

403 {
405 }
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:288
static int SecurityRestrictionContext
Definition: miscinit.c:162
void pg_bindtextdomain ( const char *  domain)

Definition at line 1385 of file miscinit.c.

References get_locale_path(), MAXPGPATH, and my_exec_path.

Referenced by _PG_init().

1386 {
1387 #ifdef ENABLE_NLS
1388  if (my_exec_path[0] != '\0')
1389  {
1390  char locale_path[MAXPGPATH];
1391 
1392  get_locale_path(my_exec_path, locale_path);
1393  bindtextdomain(domain, locale_path);
1394  pg_bind_textdomain_codeset(domain);
1395  }
1396 #endif
1397 }
#define MAXPGPATH
char my_exec_path[MAXPGPATH]
Definition: globals.c:62
void get_locale_path(const char *my_exec_path, char *ret_path)
Definition: path.c:733
void pg_split_opts ( char **  argv,
int *  argcp,
const char *  optstr 
)

Definition at line 436 of file postinit.c.

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

Referenced by BackendRun(), and process_startup_options().

437 {
438  StringInfoData s;
439 
440  initStringInfo(&s);
441 
442  while (*optstr)
443  {
444  bool last_was_escape = false;
445 
446  resetStringInfo(&s);
447 
448  /* skip over leading space */
449  while (isspace((unsigned char) *optstr))
450  optstr++;
451 
452  if (*optstr == '\0')
453  break;
454 
455  /*
456  * Parse a single option, stopping at the first space, unless it's
457  * escaped.
458  */
459  while (*optstr)
460  {
461  if (isspace((unsigned char) *optstr) && !last_was_escape)
462  break;
463 
464  if (!last_was_escape && *optstr == '\\')
465  last_was_escape = true;
466  else
467  {
468  last_was_escape = false;
469  appendStringInfoChar(&s, *optstr);
470  }
471 
472  optstr++;
473  }
474 
475  /* now store the option in the next argv[] position */
476  argv[(*argcp)++] = pstrdup(s.data);
477  }
478 
479  pfree(s.data);
480 }
char * pstrdup(const char *in)
Definition: mcxt.c:1160
void pfree(void *pointer)
Definition: mcxt.c:993
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
void PreventCommandDuringRecovery ( const char *  cmdname)

Definition at line 265 of file utility.c.

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

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

266 {
267  if (RecoveryInProgress())
268  ereport(ERROR,
269  (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
270  /* translator: %s is name of a SQL command, eg CREATE */
271  errmsg("cannot execute %s during recovery",
272  cmdname)));
273 }
int errcode(int sqlerrcode)
Definition: elog.c:569
bool RecoveryInProgress(void)
Definition: xlog.c:7526
#define ERROR
Definition: elog.h:41
#define ereport(elevel, rest)
Definition: elog.h:132
int errmsg(const char *fmt,...)
Definition: elog.c:791
void PreventCommandIfParallelMode ( const char *  cmdname)

Definition at line 246 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().

247 {
248  if (IsInParallelMode())
249  ereport(ERROR,
250  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
251  /* translator: %s is name of a SQL command, eg CREATE */
252  errmsg("cannot execute %s during a parallel operation",
253  cmdname)));
254 }
int errcode(int sqlerrcode)
Definition: elog.c:569
bool IsInParallelMode(void)
Definition: xact.c:910
#define ERROR
Definition: elog.h:41
#define ereport(elevel, rest)
Definition: elog.h:132
int errmsg(const char *fmt,...)
Definition: elog.c:791
void PreventCommandIfReadOnly ( const char *  cmdname)

Definition at line 228 of file utility.c.

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

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

229 {
230  if (XactReadOnly)
231  ereport(ERROR,
232  (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
233  /* translator: %s is name of a SQL command, eg CREATE */
234  errmsg("cannot execute %s in a read-only transaction",
235  cmdname)));
236 }
int errcode(int sqlerrcode)
Definition: elog.c:569
#define ERROR
Definition: elog.h:41
#define ereport(elevel, rest)
Definition: elog.h:132
bool XactReadOnly
Definition: xact.c:75
int errmsg(const char *fmt,...)
Definition: elog.c:791
void process_session_preload_libraries ( void  )

Definition at line 1374 of file miscinit.c.

References load_libraries(), local_preload_libraries_string, and session_preload_libraries_string.

Referenced by PostgresMain().

1375 {
1377  "session_preload_libraries",
1378  false);
1380  "local_preload_libraries",
1381  true);
1382 }
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1306
char * local_preload_libraries_string
Definition: miscinit.c:1294
char * session_preload_libraries_string
Definition: miscinit.c:1292
void process_shared_preload_libraries ( void  )

Definition at line 1361 of file miscinit.c.

References load_libraries(), process_shared_preload_libraries_in_progress, and shared_preload_libraries_string.

Referenced by PostmasterMain().

1362 {
1365  "shared_preload_libraries",
1366  false);
1368 }
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1297
char * shared_preload_libraries_string
Definition: miscinit.c:1293
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1306
void ProcessInterrupts ( void  )

Definition at line 2844 of file postgres.c.

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

Referenced by die().

2845 {
2846  /* OK to accept any interrupts now? */
2847  if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
2848  return;
2849  InterruptPending = false;
2850 
2851  if (ProcDiePending)
2852  {
2853  ProcDiePending = false;
2854  QueryCancelPending = false; /* ProcDie trumps QueryCancel */
2855  LockErrorCleanup();
2856  /* As in quickdie, don't risk sending to client during auth */
2860  ereport(FATAL,
2861  (errcode(ERRCODE_QUERY_CANCELED),
2862  errmsg("canceling authentication due to timeout")));
2863  else if (IsAutoVacuumWorkerProcess())
2864  ereport(FATAL,
2865  (errcode(ERRCODE_ADMIN_SHUTDOWN),
2866  errmsg("terminating autovacuum process due to administrator command")));
2868  {
2870  ereport(FATAL,
2871  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2872  errmsg("terminating connection due to conflict with recovery"),
2874  }
2875  else if (RecoveryConflictPending)
2876  {
2877  /* Currently there is only one non-retryable recovery conflict */
2880  ereport(FATAL,
2881  (errcode(ERRCODE_DATABASE_DROPPED),
2882  errmsg("terminating connection due to conflict with recovery"),
2884  }
2885  else
2886  ereport(FATAL,
2887  (errcode(ERRCODE_ADMIN_SHUTDOWN),
2888  errmsg("terminating connection due to administrator command")));
2889  }
2891  {
2892  QueryCancelPending = false; /* lost connection trumps QueryCancel */
2893  LockErrorCleanup();
2894  /* don't send to client, we already know the connection to be dead. */
2896  ereport(FATAL,
2897  (errcode(ERRCODE_CONNECTION_FAILURE),
2898  errmsg("connection to client lost")));
2899  }
2900 
2901  /*
2902  * If a recovery conflict happens while we are waiting for input from the
2903  * client, the client is presumably just sitting idle in a transaction,
2904  * preventing recovery from making progress. Terminate the connection to
2905  * dislodge it.
2906  */
2908  {
2909  QueryCancelPending = false; /* this trumps QueryCancel */
2910  RecoveryConflictPending = false;
2911  LockErrorCleanup();
2913  ereport(FATAL,
2914  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2915  errmsg("terminating connection due to conflict with recovery"),
2917  errhint("In a moment you should be able to reconnect to the"
2918  " database and repeat your command.")));
2919  }
2920 
2921  if (QueryCancelPending)
2922  {
2923  /*
2924  * Don't allow query cancel interrupts while reading input from the
2925  * client, because we might lose sync in the FE/BE protocol. (Die
2926  * interrupts are OK, because we won't read any further messages from
2927  * the client in that case.)
2928  */
2929  if (QueryCancelHoldoffCount != 0)
2930  {
2931  /*
2932  * Re-arm InterruptPending so that we process the cancel request
2933  * as soon as we're done reading the message.
2934  */
2935  InterruptPending = true;
2936  return;
2937  }
2938 
2939  QueryCancelPending = false;
2940 
2941  /*
2942  * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
2943  * prefer to report the former; but be sure to clear both.
2944  */
2946  {
2948  LockErrorCleanup();
2949  ereport(ERROR,
2950  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
2951  errmsg("canceling statement due to lock timeout")));
2952  }
2954  {
2955  LockErrorCleanup();
2956  ereport(ERROR,
2957  (errcode(ERRCODE_QUERY_CANCELED),
2958  errmsg("canceling statement due to statement timeout")));
2959  }
2961  {
2962  LockErrorCleanup();
2963  ereport(ERROR,
2964  (errcode(ERRCODE_QUERY_CANCELED),
2965  errmsg("canceling autovacuum task")));
2966  }
2968  {
2969  RecoveryConflictPending = false;
2970  LockErrorCleanup();
2972  ereport(ERROR,
2973  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2974  errmsg("canceling statement due to conflict with recovery"),
2976  }
2977 
2978  /*
2979  * If we are reading a command from the client, just ignore the cancel
2980  * request --- sending an extra error message won't accomplish
2981  * anything. Otherwise, go ahead and throw the error.
2982  */
2983  if (!DoingCommandRead)
2984  {
2985  LockErrorCleanup();
2986  ereport(ERROR,
2987  (errcode(ERRCODE_QUERY_CANCELED),
2988  errmsg("canceling statement due to user request")));
2989  }
2990  }
2991 
2994 }
volatile uint32 InterruptHoldoffCount
Definition: globals.c:33
int errhint(const char *fmt,...)
Definition: elog.c:978
void pgstat_report_recovery_conflict(int reason)
Definition: pgstat.c:1407
volatile uint32 QueryCancelHoldoffCount
Definition: globals.c:34
int errcode(int sqlerrcode)
Definition: elog.c:569
volatile bool QueryCancelPending
Definition: globals.c:30
volatile bool ClientConnectionLost
Definition: globals.c:32
bool ClientAuthInProgress
Definition: postmaster.c:343
#define ERROR
Definition: elog.h:41
#define FATAL
Definition: elog.h:50
void HandleParallelMessages(void)
Definition: parallel.c:620
Definition: dest.h:88
volatile uint32 CritSectionCount
Definition: globals.c:35
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:2893
#define ereport(elevel, rest)
Definition: elog.h:132
void LockErrorCleanup(void)
Definition: proc.c:668
static ProcSignalReason RecoveryConflictReason
Definition: postgres.c:176
static bool RecoveryConflictPending
Definition: postgres.c:174
static bool RecoveryConflictRetryable
Definition: postgres.c:175
bool get_timeout_indicator(TimeoutId id, bool reset_indicator)
Definition: timeout.c:633
static int errdetail_recovery_conflict(void)
Definition: postgres.c:2257
volatile bool InterruptPending
Definition: globals.c:29
#define Assert(condition)
Definition: c.h:661
static bool DoingCommandRead
Definition: postgres.c:142
bool ParallelMessagePending
Definition: parallel.c:96
volatile bool ProcDiePending
Definition: globals.c:31
int errmsg(const char *fmt,...)
Definition: elog.c:791
CommandDest whereToSendOutput
Definition: postgres.c:86
void restore_stack_base ( pg_stack_base_t  base)

Definition at line 3070 of file postgres.c.

References stack_base_ptr.

3071 {
3072 #if defined(__ia64__) || defined(__ia64)
3073  stack_base_ptr = base.stack_base_ptr;
3074  register_stack_base_ptr = base.register_stack_base_ptr;
3075 #else
3076  stack_base_ptr = base;
3077 #endif
3078 }
char * stack_base_ptr
Definition: postgres.c:115
pg_stack_base_t set_stack_base ( void  )

Definition at line 3039 of file postgres.c.

References stack_base_ptr.

Referenced by PostmasterMain().

3040 {
3041  char stack_base;
3042  pg_stack_base_t old;
3043 
3044 #if defined(__ia64__) || defined(__ia64)
3045  old.stack_base_ptr = stack_base_ptr;
3046  old.register_stack_base_ptr = register_stack_base_ptr;
3047 #else
3048  old = stack_base_ptr;
3049 #endif
3050 
3051  /* Set up reference point for stack depth checking */
3052  stack_base_ptr = &stack_base;
3053 #if defined(__ia64__) || defined(__ia64)
3054  register_stack_base_ptr = ia64_get_bsp();
3055 #endif
3056 
3057  return old;
3058 }
char * stack_base_ptr
Definition: postgres.c:115
char * pg_stack_base_t
Definition: miscadmin.h:265
void SetCurrentRoleId ( Oid  roleid,
bool  is_superuser 
)

Definition at line 633 of file miscinit.c.

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

Referenced by assign_role().

634 {
635  /*
636  * Get correct info if it's SET ROLE NONE
637  *
638  * If SessionUserId hasn't been set yet, just do nothing --- the eventual
639  * SetSessionUserId call will fix everything. This is needed since we
640  * will get called during GUC initialization.
641  */
642  if (!OidIsValid(roleid))
643  {
645  return;
646 
647  roleid = SessionUserId;
649 
650  SetRoleIsActive = false;
651  }
652  else
653  SetRoleIsActive = true;
654 
655  SetOuterUserId(roleid);
656 
657  SetConfigOption("is_superuser",
658  is_superuser ? "on" : "off",
660 }
static Oid SessionUserId
Definition: miscinit.c:154
static void SetOuterUserId(Oid userid)
Definition: miscinit.c:293
#define OidIsValid(objectId)
Definition: c.h:524
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6394
static bool SetRoleIsActive
Definition: miscinit.c:165
static bool SessionUserIsSuperuser
Definition: miscinit.c:160
bool is_superuser(void)
Definition: common.c:1730
void SetDatabasePath ( const char *  path)

Definition at line 80 of file miscinit.c.

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

Referenced by InitPostgres().

81 {
82  /* This should happen only once per process */
85 }
MemoryContext TopMemoryContext
Definition: mcxt.c:43
char * DatabasePath
Definition: globals.c:81
#define Assert(condition)
Definition: c.h:661
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1147
void SetDataDir ( const char *  dir)

Definition at line 92 of file miscinit.c.

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

Referenced by SelectConfigFiles().

93 {
94  char *new;
95 
96  AssertArg(dir);
97 
98  /* If presented path is relative, convert to absolute */
99  new = make_absolute_path(dir);
100 
101  if (DataDir)
102  free(DataDir);
103  DataDir = new;
104 }
char * make_absolute_path(const char *path)
Definition: path.c:574
#define AssertArg(condition)
Definition: c.h:663
#define free(a)
Definition: header.h:60
char * DataDir
Definition: globals.c:58
void SetSessionAuthorization ( Oid  userid,
bool  is_superuser 
)

Definition at line 587 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().

588 {
589  /* Must have authenticated already, else can't make permission check */
591 
592  if (userid != AuthenticatedUserId &&
594  ereport(ERROR,
595  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
596  errmsg("permission denied to set session authorization")));
597 
599 
600  SetConfigOption("is_superuser",
601  is_superuser ? "on" : "off",
603 }
#define AssertState(condition)
Definition: c.h:664
int errcode(int sqlerrcode)
Definition: elog.c:569
#define OidIsValid(objectId)
Definition: c.h:524
#define ERROR
Definition: elog.h:41
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6394
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:159
#define ereport(elevel, rest)
Definition: elog.h:132
bool is_superuser(void)
Definition: common.c:1730
int errmsg(const char *fmt,...)
Definition: elog.c:791
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:316
static Oid AuthenticatedUserId
Definition: miscinit.c:153
void SetUserIdAndContext ( Oid  userid,
bool  sec_def_context 
)

Definition at line 431 of file miscinit.c.

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

432 {
433  /* We throw the same error SET ROLE would. */
435  ereport(ERROR,
436  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
437  errmsg("cannot set parameter \"%s\" within security-restricted operation",
438  "role")));
439  CurrentUserId = userid;
440  if (sec_def_context)
442  else
444 }
int errcode(int sqlerrcode)
Definition: elog.c:569
#define ERROR
Definition: elog.h:41
static int SecurityRestrictionContext
Definition: miscinit.c:162
#define ereport(elevel, rest)
Definition: elog.h:132
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:287
static Oid CurrentUserId
Definition: miscinit.c:156
bool InSecurityRestrictedOperation(void)
Definition: miscinit.c:402
int errmsg(const char *fmt,...)
Definition: elog.c:791
void SetUserIdAndSecContext ( Oid  userid,
int  sec_context 
)
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(), AlterRole(), AlterRoleSet(), AlterSystemSetConfigFile(), AlterTypeOwner(), ATExecChangeOwner(), brin_page_items(), brin_revmap_data(), bt_metap(), bt_page_items(), bt_page_stats(), check_conn_params(), check_encoding_locale_matches(), check_permissions(), connect_pg_server(), CreateCast(), CreateEventTrigger(), CreateForeignDataWrapper(), CreateFunction(), CreateProceduralLanguage(), CreateRole(), CreateTableSpace(), dblink_connstr_check(), dblink_security_check(), DefineAggregate(), DefineOpClass(), DefineOpFamily(), DefineTSParser(), DefineTSTemplate(), DefineType(), DelRoleMems(), DoCopy(), DropRole(), dummy_object_relabel(), EnableDisableTrigger(), ExecSetVariableStmt(), execute_extension_script(), ExecuteDoStmt(), file_fdw_validator(), fmgr_security_definer(), fsm_page_contents(), get_raw_page_internal(), GetConfigOption(), GetConfigOptionByName(), GetConfigOptionByNum(), GetConfigOptionResetString(), gin_leafpage_items(), gin_metapage_info(), gin_page_opaque_info(), GUCArrayReset(), have_createdb_privilege(), heap_page_items(), InitPostgres(), lo_export(), lo_import_internal(), main(), page_header(), pg_create_restore_point(), pg_logdir_ls(), pg_ls_dir(), pg_read_binary_file(), pg_read_file(), pg_reload_conf(), pg_relpages(), pg_relpagesbyid(), pg_rotate_logfile(), pg_signal_backend(), pg_start_backup(), pg_stat_file(), pg_stat_get_wal_senders(), pg_stat_statements_internal(), pg_stop_backup(), pg_switch_xlog(), pg_xlog_replay_pause(), pg_xlog_replay_resume(), pgstat_get_backend_current_activity(), pgstat_reset_counters(), pgstat_reset_shared_counters(), pgstat_reset_single_counter(), pgstatginindex(), pgstatindex(), pgstatindexbyid(), pgstattuple(), pgstattuple_approx(), pgstattuplebyid(), ProcedureCreate(), regress_putenv(), RenameRole(), replorigin_check_prerequisites(), requireSuperuser(), sepgsql_restorecon(), set_config_by_name(), SetPGVariable(), ShowAllGUCConfig(), standard_ProcessUtility(), validate_option_array_item(), and wait_pid().

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

Definition at line 57 of file superuser.c.

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

Referenced by AddRoleMems(), AlterEventTriggerOwner_internal(), AlterForeignDataWrapperOwner_internal(), check_object_ownership(), 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_signal_backend(), pg_tablespace_aclmask(), pg_tablespace_ownercheck(), pg_ts_config_ownercheck(), pg_ts_dict_ownercheck(), pg_type_aclmask(), pg_type_ownercheck(), pltcl_init_load_unknown(), 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:631
#define OidIsValid(objectId)
Definition: c.h:524
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:141
static void RoleidCallback(Datum arg, int cacheid, uint32 hashvalue)
Definition: superuser.c:104
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:72
static bool last_roleid_is_super
Definition: superuser.c:37
#define ObjectIdGetDatum(X)
Definition: postgres.h:515
bool IsUnderPostmaster
Definition: globals.c:97
void CacheRegisterSyscacheCallback(int cacheid, SyscacheCallbackFunction func, Datum arg)
Definition: inval.c:1353
uintptr_t Datum
Definition: postgres.h:374
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:989
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define BOOTSTRAP_SUPERUSERID
Definition: pg_authid.h:100
static bool roleid_callback_registered
Definition: superuser.c:38
void SwitchBackToLocalLatch ( void  )

Definition at line 259 of file miscinit.c.

References Assert, LocalLatchData, MyLatch, MyProc, NULL, PGPROC::procLatch, and SetLatch().

Referenced by AuxiliaryProcKill(), and ProcKill().

260 {
263 
265  SetLatch(MyLatch);
266 }
PGPROC * MyProc
Definition: proc.c:63
Latch procLatch
Definition: proc.h:92
static Latch LocalLatchData
Definition: miscinit.c:59
void SetLatch(volatile Latch *latch)
Definition: unix_latch.c:520
#define NULL
Definition: c.h:215
#define Assert(condition)
Definition: c.h:661
struct Latch * MyLatch
Definition: globals.c:50
void SwitchToSharedLatch ( void  )

Definition at line 243 of file miscinit.c.

References Assert, MyLatch, MyProc, NULL, PGPROC::procLatch, and SetLatch().

Referenced by InitAuxiliaryProcess(), and InitProcess().

244 {
246  Assert(MyProc != NULL);
247 
249 
250  /*
251  * Set the shared latch as the local one might have been set. This
252  * shouldn't normally be necessary as code is supposed to check the
253  * condition before waiting for the latch, but a bit care can't hurt.
254  */
255  SetLatch(MyLatch);
256 }
PGPROC * MyProc
Definition: proc.c:63
Latch procLatch
Definition: proc.h:92
static Latch LocalLatchData
Definition: miscinit.c:59
void SetLatch(volatile Latch *latch)
Definition: unix_latch.c:520
#define NULL
Definition: c.h:215
#define Assert(condition)
Definition: c.h:661
struct Latch * MyLatch
Definition: globals.c:50
void TouchSocketLockFiles ( void  )

Definition at line 1066 of file miscinit.c.

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

Referenced by ServerLoop().

1067 {
1068  ListCell *l;
1069 
1070  foreach(l, lock_files)
1071  {
1072  char *socketLockFile = (char *) lfirst(l);
1073 
1074  /* No need to touch the data directory lock file, we trust */
1075  if (strcmp(socketLockFile, DIRECTORY_LOCK_FILE) == 0)
1076  continue;
1077 
1078  /*
1079  * utime() is POSIX standard, utimes() is a common alternative; if we
1080  * have neither, fall back to actually reading the file (which only
1081  * sets the access time not mod time, but that should be enough in
1082  * most cases). In all paths, we ignore errors.
1083  */
1084 #ifdef HAVE_UTIME
1085  utime(socketLockFile, NULL);
1086 #else /* !HAVE_UTIME */
1087 #ifdef HAVE_UTIMES
1088  utimes(socketLockFile, NULL);
1089 #else /* !HAVE_UTIMES */
1090  int fd;
1091  char buffer[1];
1092 
1093  fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
1094  if (fd >= 0)
1095  {
1096  read(fd, buffer, sizeof(buffer));
1097  close(fd);
1098  }
1099 #endif /* HAVE_UTIMES */
1100 #endif /* HAVE_UTIME */
1101  }
1102 }
static List * lock_files
Definition: miscinit.c:57
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:52
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PG_BINARY
Definition: c.h:1012
#define NULL
Definition: c.h:215
#define lfirst(lc)
Definition: pg_list.h:106
#define close(a)
Definition: win32.h:17
#define read(a, b, c)
Definition: win32.h:18
int trace_recovery ( int  trace_level)
void ValidatePgVersion ( const char *  path)

Definition at line 1229 of file miscinit.c.

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

Referenced by AuxiliaryProcessMain(), checkDataDir(), InitPostgres(), and PostgresMain().

1230 {
1231  char full_path[MAXPGPATH];
1232  FILE *file;
1233  int ret;
1234  long file_major,
1235  file_minor;
1236  long my_major = 0,
1237  my_minor = 0;
1238  char *endptr;
1239  const char *version_string = PG_VERSION;
1240 
1241  my_major = strtol(version_string, &endptr, 10);
1242  if (*endptr == '.')
1243  my_minor = strtol(endptr + 1, NULL, 10);
1244 
1245  snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
1246 
1247  file = AllocateFile(full_path, "r");
1248  if (!file)
1249  {
1250  if (errno == ENOENT)
1251  ereport(FATAL,
1252  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1253  errmsg("\"%s\" is not a valid data directory",
1254  path),
1255  errdetail("File \"%s\" is missing.", full_path)));
1256  else
1257  ereport(FATAL,
1259  errmsg("could not open file \"%s\": %m", full_path)));
1260  }
1261 
1262  ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
1263  if (ret != 2)
1264  ereport(FATAL,
1265  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1266  errmsg("\"%s\" is not a valid data directory",
1267  path),
1268  errdetail("File \"%s\" does not contain valid data.",
1269  full_path),
1270  errhint("You might need to initdb.")));
1271 
1272  FreeFile(file);
1273 
1274  if (my_major != file_major || my_minor != file_minor)
1275  ereport(FATAL,
1276  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1277  errmsg("database files are incompatible with server"),
1278  errdetail("The data directory was initialized by PostgreSQL version %ld.%ld, "
1279  "which is not compatible with this version %s.",
1280  file_major, file_minor, version_string)));
1281 }
int errhint(const char *fmt,...)
Definition: elog.c:978
int errcode(int sqlerrcode)
Definition: elog.c:569
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define FATAL
Definition: elog.h:50
#define MAXPGPATH
int errdetail(const char *fmt,...)
Definition: elog.c:864
int errcode_for_file_access(void)
Definition: elog.c:592
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:1659
#define ereport(elevel, rest)
Definition: elog.h:132
#define NULL
Definition: c.h:215
int FreeFile(FILE *file)
Definition: fd.c:1842
int errmsg(const char *fmt,...)
Definition: elog.c:791

Variable Documentation

volatile bool ClientConnectionLost

Definition at line 32 of file globals.c.

Referenced by internal_flush(), and ProcessInterrupts().

PGDLLIMPORT int DateOrder
bool ExitOnAnyError

Definition at line 101 of file globals.c.

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

bool IgnoreSystemIndexes
PGDLLIMPORT volatile uint32 InterruptHoldoffCount

Definition at line 33 of file globals.c.

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

PGDLLIMPORT int IntervalStyle
bool IsBackgroundWorker
PGDLLIMPORT bool IsUnderPostmaster

Definition at line 97 of file globals.c.

Referenced by _PG_init(), AutoVacuumShmemInit(), AuxiliaryProcessMain(), BackgroundWorkerShmemInit(), bootstrap_signals(), BootstrapModeMain(), BTreeShmemInit(), CheckMyDatabase(), CheckRecoveryConsistency(), CommitTsShmemInit(), CreateLWLocks(), CreateSharedMemoryAndSemaphores(), DebugFileOpen(), DetermineSafeOldestOffset(), 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(), InitializeSessionUserId(), InitializeSessionUserIdStandalone(), InitPostgres(), InitPostmasterChild(), InitProcess(), LWLockAcquire(), mdinit(), MultiXactShmemInit(), PGSemaphoreCreate(), PGSharedMemoryReAttach(), pgss_shmem_startup(), PostgresMain(), process_postgres_switches(), process_settings(), ProcKill(), register_unlink(), RegisterBackgroundWorker(), RegisterDynamicBackgroundWorker(), RequestAddinLWLocks(), RequestAddinShmemSpace(), SendPostmasterSignal(), set_config_option(), set_config_sourcefile(), set_ps_display(), SetMultiXactIdLimit(), SetTransactionIdLimit(), ShmemInitStruct(), SimpleLruInit(), StartupXLOG(), superuser_arg(), SyncScanShmemInit(), TrimMultiXact(), TwoPhaseShmemInit(), verify_dictoptions(), XLogArchiveNotify(), and XLogWrite().

char* local_preload_libraries_string

Definition at line 1294 of file miscinit.c.

Referenced by process_session_preload_libraries().

Definition at line 54 of file miscinit.c.

AuxProcType MyAuxProcType

Definition at line 64 of file bootstrap.c.

Referenced by AuxiliaryProcessMain().

long MyCancelKey
PGDLLIMPORT Oid MyDatabaseId

Definition at line 73 of file globals.c.

Referenced by AfterTriggerSetState(), AlterDatabase(), AlterSchemaOwner_internal(), analyze_rel(), asyncQueueNotificationToEntry(), asyncQueueProcessPageEntries(), backend_read_statsfile(), CacheInvalidateCatalog(), CacheInvalidateHeapTuple(), CacheInvalidateRelcache(), CacheInvalidateRelcacheByTuple(), CheckLogicalDecodingRequirements(), CheckMyDatabase(), checkSharedDependencies(), classIdGetDbId(), CreateDecodingContext(), CreateInitDecodingContext(), CreateProceduralLanguage(), CreateSchemaCommand(), current_database(), database_to_xml_internal(), DeconstructQualifiedName(), do_analyze_rel(), do_autovacuum(), dropdb(), exec_object_restorecon(), ExpandColumnRefStar(), ExportSnapshot(), GetCurrentVirtualXIDs(), GetNewRelFileNode(), GetOldestXmin(), IdentifySystem(), ImportSnapshot(), InitializeParallelDSM(), InitPostgres(), InitTempTableNamespace(), lazy_vacuum_rel(), LocalExecuteInvalidationMessage(), LockDatabaseObject(), LockGXact(), logical_heap_rewrite_flush_mappings(), logical_rewrite_log_mapping(), 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(), pg_namespace_aclmask(), pg_relation_filepath(), pgss_store(), pgstat_beshutdown_hook(), pgstat_bestart(), 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_rel(), and XactLogCommitRecord().

PGDLLIMPORT int NBuffers

Definition at line 118 of file globals.c.

char OutputFileName[]

Definition at line 60 of file globals.c.

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

char pkglib_path[]

Definition at line 63 of file globals.c.

Referenced by getInstallationPaths(), InitStandaloneProcess(), and substitute_libpath_macro().

pid_t PostmasterPid
PGDLLIMPORT bool process_shared_preload_libraries_in_progress
PGDLLIMPORT volatile uint32 QueryCancelHoldoffCount

Definition at line 34 of file globals.c.

Referenced by errfinish(), and ProcessInterrupts().

char* session_preload_libraries_string

Definition at line 1292 of file miscinit.c.

Referenced by process_session_preload_libraries().

char* shared_preload_libraries_string

Definition at line 1293 of file miscinit.c.

Referenced by process_shared_preload_libraries().

int trace_recovery_messages

Definition at line 435 of file guc.c.

Referenced by StartupXLOG(), and trace_recovery().

bool VacuumCostActive
int VacuumCostBalance
int VacuumCostLimit
int VacuumCostPageDirty

Definition at line 125 of file globals.c.

Referenced by MarkBufferDirty(), and MarkBufferDirtyHint().

int VacuumCostPageHit

Definition at line 123 of file globals.c.

Referenced by ReadBuffer_common().

int VacuumCostPageMiss

Definition at line 124 of file globals.c.

Referenced by ReadBuffer_common().

int VacuumPageDirty

Definition at line 131 of file globals.c.

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

int VacuumPageHit

Definition at line 129 of file globals.c.

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

int VacuumPageMiss

Definition at line 130 of file globals.c.

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

PGDLLIMPORT int work_mem

Definition at line 109 of file globals.c.

Referenced by _bt_spoolinit(), begin_partition(), brin_page_items(), BuildTupleHashTable(), choose_hashed_distinct(), choose_hashed_grouping(), choose_hashed_setop(), collectMatchBitmap(), connectby(), cost_material(), cost_rescan(), create_merge_append_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(), ExecHashTableCreate(), ExecInitCteScan(), ExecInitRecursiveUnion(), ExecMakeTableFunctionResult(), ExecMaterial(), ExecRecursiveUnion(), ExecSort(), final_cost_mergejoin(), fmgr_sql(), get_crosstab_tuplestore(), GetCurrentFDWTuplestore(), grouping_planner(), initial_cost_mergejoin(), initialize_aggregate(), initialize_phase(), make_sort(), materializeQueryResult(), materializeResult(), MultiExecBitmapIndexScan(), MultiExecBitmapOr(), ordered_set_startup(), pg_available_extension_versions(), pg_available_extensions(), pg_cursor(), pg_event_trigger_ddl_commands(), pg_event_trigger_dropped_objects(), pg_extension_update_paths(), pg_get_replication_slots(), pg_logical_slot_get_changes_guts(), pg_prepared_statement(), pg_show_replication_origin_status(), pg_stat_get_activity(), pg_stat_get_wal_senders(), pg_stat_statements_internal(), plperl_return_next(), populate_recordset_worker(), PortalCreateHoldStore(), show_all_file_settings(), storeRow(), subplan_is_hashable(), and xpath_table().