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_NOFORCE_RLS   0x0004
 
#define IsBootstrapProcessingMode()   (Mode == BootstrapProcessing)
 
#define IsInitProcessingMode()   (Mode == InitProcessing)
 
#define IsNormalProcessingMode()   (Mode == NormalProcessing)
 
#define GetProcessingMode()   Mode
 
#define SetProcessingMode(mode)
 
#define AmBootstrapProcess()   (MyAuxProcType == BootstrapProcess)
 
#define AmStartupProcess()   (MyAuxProcType == StartupProcess)
 
#define AmBackgroundWriterProcess()   (MyAuxProcType == BgWriterProcess)
 
#define AmCheckpointerProcess()   (MyAuxProcType == CheckpointerProcess)
 
#define AmWalWriterProcess()   (MyAuxProcType == WalWriterProcess)
 
#define AmWalReceiverProcess()   (MyAuxProcType == WalReceiverProcess)
 
#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)
 
bool stack_is_too_deep (void)
 
void PreventCommandIfReadOnly (const char *cmdname)
 
void PreventCommandIfParallelMode (const char *cmdname)
 
void PreventCommandDuringRecovery (const char *cmdname)
 
int trace_recovery (int trace_level)
 
void InitPostmasterChild (void)
 
void InitStandaloneProcess (const char *argv0)
 
void SetDatabasePath (const char *path)
 
char * GetUserNameFromId (Oid roleid, bool noerr)
 
Oid GetUserId (void)
 
Oid GetOuterUserId (void)
 
Oid GetSessionUserId (void)
 
Oid GetAuthenticatedUserId (void)
 
void GetUserIdAndSecContext (Oid *userid, int *sec_context)
 
void SetUserIdAndSecContext (Oid userid, int sec_context)
 
bool InLocalUserIdChange (void)
 
bool InSecurityRestrictedOperation (void)
 
bool InNoForceRLSOperation (void)
 
void GetUserIdAndContext (Oid *userid, bool *sec_def_context)
 
void SetUserIdAndContext (Oid userid, bool sec_def_context)
 
void InitializeSessionUserId (const char *rolename, Oid useroid)
 
void InitializeSessionUserIdStandalone (void)
 
void SetSessionAuthorization (Oid userid, bool is_superuser)
 
Oid GetCurrentRoleId (void)
 
void SetCurrentRoleId (Oid roleid, bool is_superuser)
 
void 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)
 
bool RecheckDataDirLockFile (void)
 
void ValidatePgVersion (const char *path)
 
void process_shared_preload_libraries (void)
 
void process_session_preload_libraries (void)
 
void pg_bindtextdomain (const char *domain)
 
bool has_rolreplication (Oid roleid)
 
bool BackupInProgress (void)
 
void CancelBackup (void)
 

Variables

PGDLLIMPORT volatile bool InterruptPending
 
PGDLLIMPORT volatile bool QueryCancelPending
 
PGDLLIMPORT volatile bool ProcDiePending
 
PGDLLIMPORT volatile bool IdleInTransactionSessionTimeoutPending
 
volatile bool ClientConnectionLost
 
PGDLLIMPORT volatile uint32 InterruptHoldoffCount
 
PGDLLIMPORT volatile uint32 QueryCancelHoldoffCount
 
PGDLLIMPORT volatile uint32 CritSectionCount
 
PGDLLIMPORT 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
 
PGDLLIMPORT int replacement_sort_tuples
 
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 403 of file miscadmin.h.

Referenced by ForwardFsyncRequest().

#define AmBootstrapProcess ( )    (MyAuxProcType == BootstrapProcess)

Definition at line 401 of file miscadmin.h.

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

Definition at line 402 of file miscadmin.h.

Referenced by HotStandbyActiveInReplay(), and mdinit().

#define AmWalReceiverProcess ( )    (MyAuxProcType == WalReceiverProcess)

Definition at line 406 of file miscadmin.h.

Referenced by get_sync_bit().

#define AmWalWriterProcess ( )    (MyAuxProcType == WalWriterProcess)

Definition at line 405 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:2833

Definition at line 97 of file miscadmin.h.

Referenced by _bt_buildadd(), _bt_steppage(), _bt_walk_left(), _crypt_blowfish_rn(), _hash_metapinit(), _hash_readnext(), _hash_readprev(), add_partial_path(), add_path(), analyze_rel(), ATRewriteTable(), backend_read_statsfile(), BipartiteMatch(), blbulkdelete(), blgetbitmap(), bloomBuildCallback(), 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(), collect_corrupt_items(), collect_visibility_data(), copy_file(), copy_heap_data(), copy_messages(), copy_relation_data(), copydir(), CopyFrom(), CopyTo(), count_nondeletable_pages(), CountOtherDBBackends(), db_dir_size(), DecodingContextFindStartpoint(), do_autovacuum(), do_des(), 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(), gather_readnext(), get_query_def(), get_rule_expr(), get_setop_query(), GetMultiXactIdMembers(), GetNewOidWithIndex(), GetNewRelFileNode(), getNextNearest(), ginbuild(), ginBuildCallback(), gingetbitmap(), 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(), lseg_inside_poly(), make_bounded_heap(), mode_final(), mq_putmessage(), MultiExecBitmapIndexScan(), MultiExecProcNode(), numeric_fac(), pg_logical_slot_get_changes_guts(), pg_prewarm(), pg_sleep(), pg_visibility_map_summary(), pgfdw_get_result(), 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(), read_local_xlog_page(), refresh_matview_datafill(), regexp_fixed_prefix(), replace_text(), replace_text_regexp(), replorigin_create(), RequestCheckpoint(), revmap_extend_and_get_blkno(), sendAuthRequest(), sendDir(), set_rtable_names(), 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 217 of file miscadmin.h.

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

#define DATEORDER_YMD   0

Definition at line 215 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:667
PGDLLIMPORT volatile uint32 CritSectionCount
Definition: globals.c:36

Definition at line 132 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(), GenericXLogFinish(), ginbuild(), ginbuildempty(), ginbulkdelete(), ginDeletePage(), ginHeapTupleFastInsert(), ginPlaceToPage(), ginUpdateStats(), ginVacuumPostingTreeLeaf(), gistbuild(), gistbuildempty(), gistbulkdelete(), gistplacetopage(), gistvacuumpage(), 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(), TruncateMultiXact(), UpdateFullPageWrites(), vacuumLeafPage(), vacuumLeafRoot(), vacuumRedirectAndPlaceholder(), visibilitymap_set(), write_relmap_file(), writeListPage(), XLogBackgroundFlush(), XLogFlush(), and XLogInsertRecord().

#define GetProcessingMode ( )    Mode

Definition at line 368 of file miscadmin.h.

#define HOLD_CANCEL_INTERRUPTS ( )    (QueryCancelHoldoffCount++)

Definition at line 122 of file miscadmin.h.

Referenced by CopyGetData(), and SocketBackend().

#define INTSTYLE_ISO_8601   3

Definition at line 232 of file miscadmin.h.

Referenced by EncodeInterval().

#define INTSTYLE_POSTGRES   0

Definition at line 229 of file miscadmin.h.

Referenced by EncodeInterval(), and set_transmission_modes().

#define INTSTYLE_POSTGRES_VERBOSE   1

Definition at line 230 of file miscadmin.h.

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

#define INTSTYLE_SQL_STANDARD   2

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

#define LOCK_FILE_LINE_LISTEN_ADDR   6

Definition at line 450 of file miscadmin.h.

Referenced by PostmasterMain(), and test_postmaster_connection().

#define LOCK_FILE_LINE_PID   1

Definition at line 445 of file miscadmin.h.

Referenced by test_postmaster_connection().

#define LOCK_FILE_LINE_PORT   4

Definition at line 448 of file miscadmin.h.

Referenced by get_sock_dir(), and test_postmaster_connection().

#define LOCK_FILE_LINE_SHMEM_KEY   7

Definition at line 451 of file miscadmin.h.

Referenced by CreateLockFile(), and InternalIpcMemoryCreate().

#define LOCK_FILE_LINE_SOCKET_DIR   5

Definition at line 449 of file miscadmin.h.

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

#define LOCK_FILE_LINE_START_TIME   3

Definition at line 447 of file miscadmin.h.

Referenced by test_postmaster_connection().

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

Definition at line 236 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:35
#define Assert(condition)
Definition: c.h:667

Definition at line 124 of file miscadmin.h.

Referenced by CopyGetData(), and SocketBackend().

#define SECURITY_NOFORCE_RLS   0x0004

Definition at line 292 of file miscadmin.h.

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

#define SECURITY_RESTRICTED_OPERATION   0x0002
#define SetProcessingMode (   mode)
#define START_CRIT_SECTION ( )    (CritSectionCount++)

Definition at line 130 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(), GenericXLogFinish(), GetNewMultiXactId(), ginbuild(), ginbuildempty(), ginbulkdelete(), ginDeletePage(), ginHeapTupleFastInsert(), ginPlaceToPage(), ginUpdateStats(), ginVacuumPostingTreeLeaf(), gistbuild(), gistbuildempty(), gistbulkdelete(), gistplacetopage(), gistvacuumpage(), 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(), TruncateMultiXact(), UpdateFullPageWrites(), vacuumLeafPage(), vacuumLeafRoot(), vacuumRedirectAndPlaceholder(), visibilitymap_set(), write_relmap_file(), writeListPage(), XLogBackgroundFlush(), XLogFlush(), and XLogInsertRecord().

#define USE_GERMAN_DATES   3

Definition at line 211 of file miscadmin.h.

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

#define USE_ISO_DATES   1
#define USE_POSTGRES_DATES   0

Definition at line 208 of file miscadmin.h.

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

#define USE_SQL_DATES   2

Definition at line 210 of file miscadmin.h.

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

#define USE_XSD_DATES   4

Typedef Documentation

Definition at line 267 of file miscadmin.h.

Enumeration Type Documentation

Enumerator
NotAnAuxProcess 
CheckerProcess 
BootstrapProcess 
StartupProcess 
BgWriterProcess 
CheckpointerProcess 
WalWriterProcess 
WalReceiverProcess 
NUM_AUXPROCTYPES 

Definition at line 385 of file miscadmin.h.

Enumerator
BootstrapProcessing 
InitProcessing 
NormalProcessing 

Definition at line 355 of file miscadmin.h.

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

Function Documentation

void AddToDataDirLockFile ( int  target_line,
const char *  str 
)

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

1149 {
1150  int fd;
1151  int len;
1152  int lineno;
1153  char *srcptr;
1154  char *destptr;
1155  char srcbuffer[BLCKSZ];
1156  char destbuffer[BLCKSZ];
1157 
1158  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1159  if (fd < 0)
1160  {
1161  ereport(LOG,
1163  errmsg("could not open file \"%s\": %m",
1165  return;
1166  }
1167  len = read(fd, srcbuffer, sizeof(srcbuffer) - 1);
1168  if (len < 0)
1169  {
1170  ereport(LOG,
1172  errmsg("could not read from file \"%s\": %m",
1174  close(fd);
1175  return;
1176  }
1177  srcbuffer[len] = '\0';
1178 
1179  /*
1180  * Advance over lines we are not supposed to rewrite, then copy them to
1181  * destbuffer.
1182  */
1183  srcptr = srcbuffer;
1184  for (lineno = 1; lineno < target_line; lineno++)
1185  {
1186  if ((srcptr = strchr(srcptr, '\n')) == NULL)
1187  {
1188  elog(LOG, "incomplete data in \"%s\": found only %d newlines while trying to add line %d",
1189  DIRECTORY_LOCK_FILE, lineno - 1, target_line);
1190  close(fd);
1191  return;
1192  }
1193  srcptr++;
1194  }
1195  memcpy(destbuffer, srcbuffer, srcptr - srcbuffer);
1196  destptr = destbuffer + (srcptr - srcbuffer);
1197 
1198  /*
1199  * Write or rewrite the target line.
1200  */
1201  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s\n", str);
1202  destptr += strlen(destptr);
1203 
1204  /*
1205  * If there are more lines in the old file, append them to destbuffer.
1206  */
1207  if ((srcptr = strchr(srcptr, '\n')) != NULL)
1208  {
1209  srcptr++;
1210  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s",
1211  srcptr);
1212  }
1213 
1214  /*
1215  * And rewrite the data. Since we write in a single kernel call, this
1216  * update should appear atomic to onlookers.
1217  */
1218  len = strlen(destbuffer);
1219  errno = 0;
1220  if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
1221  (int) write(fd, destbuffer, len) != len)
1222  {
1223  /* if write didn't set errno, assume problem is no disk space */
1224  if (errno == 0)
1225  errno = ENOSPC;
1226  ereport(LOG,
1228  errmsg("could not write to file \"%s\": %m",
1230  close(fd);
1231  return;
1232  }
1233  if (pg_fsync(fd) != 0)
1234  {
1235  ereport(LOG,
1237  errmsg("could not write to file \"%s\": %m",
1239  }
1240  if (close(fd) != 0)
1241  {
1242  ereport(LOG,
1244  errmsg("could not write to file \"%s\": %m",
1246  }
1247 }
#define write(a, b, c)
Definition: win32.h:19
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:53
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:1018
int errcode_for_file_access(void)
Definition: elog.c:598
#define ereport(elevel, rest)
Definition: elog.h:122
#define NULL
Definition: c.h:226
int errmsg(const char *fmt,...)
Definition: elog.c:797
int pg_fsync(int fd)
Definition: fd.c:326
#define elog
Definition: elog.h:218
#define close(a)
Definition: win32.h:17
#define read(a, b, c)
Definition: win32.h:18
bool BackupInProgress ( void  )

Definition at line 10870 of file xlog.c.

References BACKUP_LABEL_FILE.

Referenced by pg_is_in_backup(), and PostmasterStateMachine().

10871 {
10872  struct stat stat_buf;
10873 
10874  return (stat(BACKUP_LABEL_FILE, &stat_buf) == 0);
10875 }
struct stat stat_buf
Definition: pg_standby.c:101
#define BACKUP_LABEL_FILE
Definition: xlog.h:288
void BaseInit ( void  )

Definition at line 519 of file postinit.c.

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

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

520 {
521  /*
522  * Attach to shared memory and semaphores, and initialize our
523  * input/output/debugging file descriptors.
524  */
526  DebugFileOpen();
527 
528  /* Do local initialization of file, storage and buffer managers */
529  InitFileAccess();
530  smgrinit();
532 }
static void InitCommunication(void)
Definition: postinit.c:411
void InitBufferPoolAccess(void)
Definition: bufmgr.c:2420
void DebugFileOpen(void)
Definition: elog.c:1854
void smgrinit(void)
Definition: smgr.c:102
void InitFileAccess(void)
Definition: fd.c:720
void CancelBackup ( void  )

Definition at line 10890 of file xlog.c.

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

Referenced by PostmasterStateMachine().

10891 {
10892  struct stat stat_buf;
10893 
10894  /* if the backup_label file is not there, return */
10895  if (stat(BACKUP_LABEL_FILE, &stat_buf) < 0)
10896  return;
10897 
10898  /* remove leftover file from previously canceled backup if it exists */
10900 
10902  {
10903  ereport(WARNING,
10905  errmsg("online backup mode was not canceled"),
10906  errdetail("File \"%s\" could not be renamed to \"%s\": %m.",
10908  return;
10909  }
10910 
10911  /* if the tablespace_map file is not there, return */
10912  if (stat(TABLESPACE_MAP, &stat_buf) < 0)
10913  {
10914  ereport(LOG,
10915  (errmsg("online backup mode canceled"),
10916  errdetail("File \"%s\" was renamed to \"%s\".",
10918  return;
10919  }
10920 
10921  /* remove leftover file from previously canceled backup if it exists */
10923 
10925  {
10926  ereport(LOG,
10927  (errmsg("online backup mode canceled"),
10928  errdetail("Files \"%s\" and \"%s\" were renamed to "
10929  "\"%s\" and \"%s\", respectively.",
10932  }
10933  else
10934  {
10935  ereport(WARNING,
10937  errmsg("online backup mode canceled"),
10938  errdetail("File \"%s\" was renamed to \"%s\", but "
10939  "file \"%s\" could not be renamed to \"%s\": %m.",
10942  }
10943 }
#define DEBUG1
Definition: elog.h:25
#define LOG
Definition: elog.h:26
#define BACKUP_LABEL_OLD
Definition: xlog.h:289
#define TABLESPACE_MAP
Definition: xlog.h:291
struct stat stat_buf
Definition: pg_standby.c:101
int errdetail(const char *fmt,...)
Definition: elog.c:873
int errcode_for_file_access(void)
Definition: elog.c:598
int unlink(const char *filename)
#define ereport(elevel, rest)
Definition: elog.h:122
int durable_rename(const char *oldfile, const char *newfile, int elevel)
Definition: fd.c:586
#define WARNING
Definition: elog.h:40
#define TABLESPACE_MAP_OLD
Definition: xlog.h:292
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define BACKUP_LABEL_FILE
Definition: xlog.h:288
void ChangeToDataDir ( void  )

Definition at line 114 of file miscinit.c.

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

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

115 {
117 
118  if (chdir(DataDir) < 0)
119  ereport(FATAL,
121  errmsg("could not change directory to \"%s\": %m",
122  DataDir)));
123 }
#define AssertState(condition)
Definition: c.h:670
#define FATAL
Definition: elog.h:52
int errcode_for_file_access(void)
Definition: elog.c:598
#define ereport(elevel, rest)
Definition: elog.h:122
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * DataDir
Definition: globals.c:59
void check_stack_depth ( void  )

Definition at line 3110 of file postgres.c.

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

Referenced by addone(), clean_fakeval_intree(), clean_NOT_intree(), cntsize(), contains_required_value(), convertJsonbValue(), copyNODE(), copyObject(), Cover(), datum_to_json(), datum_to_jsonb(), 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(), hash_range(), hk_depth_search(), infix(), inline_set_returning_function(), int_query_opr_selec(), JsonbDeepContains(), JumbleExpr(), ltree_execute(), makepol(), maketree(), MatchText(), normalize_phrase_tree(), parse_array(), parse_object(), plainnode(), plperl_hash_from_tuple(), plperl_sv_to_datum(), QT2QTN(), QTNBinary(), QTNClearFlags(), QTNCopy(), QTNFree(), QTNodeCompare(), QTNSort(), QTNTernary(), range_cmp(), range_in(), range_out(), range_recv(), range_send(), raw_expression_tree_walker(), record_cmp(), record_eq(), record_in(), record_out(), record_recv(), record_send(), setPath(), split_array(), tqueueWalk(), transformExprRecurse(), transformSetOperationTree(), TS_execute(), TS_execute_ternary(), TS_phrase_execute(), tsquery_opr_selec(), tsquery_requires_match(), and TupleQueueRemap().

3111 {
3112  if (stack_is_too_deep())
3113  {
3114  ereport(ERROR,
3115  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3116  errmsg("stack depth limit exceeded"),
3117  errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3118  "after ensuring the platform's stack depth limit is adequate.",
3119  max_stack_depth)));
3120  }
3121 }
int errhint(const char *fmt,...)
Definition: elog.c:987
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
int max_stack_depth
Definition: postgres.c:94
int errmsg(const char *fmt,...)
Definition: elog.c:797
bool stack_is_too_deep(void)
Definition: postgres.c:3124
void CreateDataDirLockFile ( bool  amPostmaster)

Definition at line 1072 of file miscinit.c.

References CreateLockFile(), DataDir, and DIRECTORY_LOCK_FILE.

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

1073 {
1074  CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, "", true, DataDir);
1075 }
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:53
static void CreateLockFile(const char *filename, bool amPostmaster, const char *socketDir, bool isDDLock, const char *refName)
Definition: miscinit.c:767
char * DataDir
Definition: globals.c:59
void CreateSocketLockFile ( const char *  socketfile,
bool  amPostmaster,
const char *  socketDir 
)

Definition at line 1081 of file miscinit.c.

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

1083 {
1084  char lockfile[MAXPGPATH];
1085 
1086  snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
1087  CreateLockFile(lockfile, amPostmaster, socketDir, false, socketfile);
1088 }
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:767
#define MAXPGPATH
Oid GetAuthenticatedUserId ( void  )

Definition at line 341 of file miscinit.c.

References AssertState, AuthenticatedUserId, and OidIsValid.

Referenced by InitializeParallelDSM().

342 {
344  return AuthenticatedUserId;
345 }
#define AssertState(condition)
Definition: c.h:670
#define OidIsValid(objectId)
Definition: c.h:530
static Oid AuthenticatedUserId
Definition: miscinit.c:154
Oid GetCurrentRoleId ( void  )

Definition at line 634 of file miscinit.c.

References InvalidOid, OuterUserId, and SetRoleIsActive.

Referenced by show_role().

635 {
636  if (SetRoleIsActive)
637  return OuterUserId;
638  else
639  return InvalidOid;
640 }
static Oid OuterUserId
Definition: miscinit.c:156
#define InvalidOid
Definition: postgres_ext.h:36
static bool SetRoleIsActive
Definition: miscinit.c:166
Oid GetOuterUserId ( void  )

Definition at line 293 of file miscinit.c.

References AssertState, OidIsValid, and OuterUserId.

Referenced by DropRole(), and RenameRole().

294 {
296  return OuterUserId;
297 }
#define AssertState(condition)
Definition: c.h:670
static Oid OuterUserId
Definition: miscinit.c:156
#define OidIsValid(objectId)
Definition: c.h:530
Oid GetSessionUserId ( void  )

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

317 {
319  return SessionUserId;
320 }
#define AssertState(condition)
Definition: c.h:670
static Oid SessionUserId
Definition: miscinit.c:155
#define OidIsValid(objectId)
Definition: c.h:530
Oid GetUserId ( void  )

Definition at line 282 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(), brin_summarize_new_values(), build_join_rel(), BuildCachedPlan(), BuildDescForRelation(), BuildIndexValueDescription(), calculate_database_size(), calculate_tablespace_size(), check_enable_rls(), check_permissions(), check_temp_tablespaces(), CheckCachedPlan(), checkDomainOwner(), checkEnumOwner(), checkFkeyPermissions(), CheckFunctionValidatorAccess(), CheckMyDatabase(), cluster_rel(), CommentObject(), compile_plperl_function(), compile_pltcl_function(), CompleteCachedPlan(), compute_return_type(), CreateCast(), CreateConversionCommand(), createdb(), CreateEventTrigger(), CreateExtensionInternal(), 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(), gin_clean_pending_list(), GrantRole(), HandleFunctionRequest(), has_any_column_privilege_id(), has_any_column_privilege_name(), has_column_privilege_id_attnum(), has_column_privilege_id_name(), has_column_privilege_name_attnum(), has_column_privilege_name_name(), has_database_privilege_id(), has_database_privilege_name(), has_foreign_data_wrapper_privilege_id(), has_foreign_data_wrapper_privilege_name(), has_function_privilege_id(), has_function_privilege_name(), has_language_privilege_id(), has_language_privilege_name(), has_schema_privilege_id(), has_schema_privilege_name(), has_sequence_privilege_id(), has_sequence_privilege_name(), has_server_privilege_id(), has_server_privilege_name(), has_table_privilege_id(), has_table_privilege_name(), has_tablespace_privilege_id(), has_tablespace_privilege_name(), has_type_privilege_id(), has_type_privilege_name(), have_createdb_privilege(), have_createrole_privilege(), ImportForeignSchema(), init_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_stat_get_activity(), pg_stat_get_backend_activity(), pg_stat_get_backend_activity_start(), pg_stat_get_backend_client_addr(), pg_stat_get_backend_client_port(), pg_stat_get_backend_start(), pg_stat_get_backend_wait_event(), pg_stat_get_backend_wait_event_type(), pg_stat_get_backend_xact_start(), pg_stat_get_progress_info(), pg_stat_statements_internal(), pgrowlocks(), pgss_store(), pgstat_get_backend_current_activity(), pltcl_fetch_interp(), postgresBeginDirectModify(), postgresBeginForeignModify(), postgresBeginForeignScan(), postgresGetForeignRelSize(), postgresImportForeignSchema(), PrepareTempTablespaces(), PrepareTransaction(), RangeVarCallbackForAlterRelation(), RangeVarCallbackForDropRelation(), RangeVarCallbackForPolicy(), RangeVarCallbackForReindexIndex(), RangeVarCallbackForRenameRule(), RangeVarCallbackForRenameTrigger(), RangeVarCallbackOwnsRelation(), RangeVarCallbackOwnsTable(), RangeVarGetAndCheckCreationNamespace(), ReassignOwnedObjects(), recomputeNamespacePath(), ReindexMultipleTables(), RemoveObjects(), RemoveRoleFromObjectPolicy(), renameatt_check(), RenameDatabase(), RenameSchema(), RenameTableSpace(), RenameType(), RevalidateCachedQuery(), RI_Initial_Check(), ri_ReportViolation(), select_perl_context(), superuser(), timetravel(), transformTableLikeClause(), truncate_check_rel(), user_mapping_ddl_aclcheck(), vacuum_rel(), ValidateJoinEstimator(), and ValidateRestrictionEstimator().

283 {
285  return CurrentUserId;
286 }
#define AssertState(condition)
Definition: c.h:670
#define OidIsValid(objectId)
Definition: c.h:530
static Oid CurrentUserId
Definition: miscinit.c:157
void GetUserIdAndContext ( Oid userid,
bool sec_def_context 
)

Definition at line 436 of file miscinit.c.

References CurrentUserId, and InLocalUserIdChange().

437 {
438  *userid = CurrentUserId;
439  *sec_def_context = InLocalUserIdChange();
440 }
bool InLocalUserIdChange(void)
Definition: miscinit.c:405
static Oid CurrentUserId
Definition: miscinit.c:157
void GetUserIdAndSecContext ( Oid userid,
int *  sec_context 
)
char* GetUserNameFromId ( Oid  roleid,
bool  noerr 
)

Definition at line 690 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(), RemoveRoleFromObjectPolicy(), session_user(), and timetravel().

691 {
692  HeapTuple tuple;
693  char *result;
694 
695  tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
696  if (!HeapTupleIsValid(tuple))
697  {
698  if (!noerr)
699  ereport(ERROR,
700  (errcode(ERRCODE_UNDEFINED_OBJECT),
701  errmsg("invalid role OID: %u", roleid)));
702  result = NULL;
703  }
704  else
705  {
706  result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
707  ReleaseSysCache(tuple);
708  }
709  return result;
710 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
char * pstrdup(const char *in)
Definition: mcxt.c:1168
int errcode(int sqlerrcode)
Definition: elog.c:575
#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:43
#define ereport(elevel, rest)
Definition: elog.h:122
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:990
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:226
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define NameStr(name)
Definition: c.h:494
bool has_rolreplication ( Oid  roleid)

Definition at line 463 of file miscinit.c.

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

Referenced by check_permissions(), and InitPostgres().

464 {
465  bool result = false;
466  HeapTuple utup;
467 
468  utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
469  if (HeapTupleIsValid(utup))
470  {
471  result = ((Form_pg_authid) GETSTRUCT(utup))->rolreplication;
472  ReleaseSysCache(utup);
473  }
474  return result;
475 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#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:990
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void InitializeMaxBackends ( void  )

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

498 {
499  Assert(MaxBackends == 0);
500 
501  /* the extra unit accounts for the autovacuum launcher */
504 
505  /* internal error because the values were all checked previously */
507  elog(ERROR, "too many backends configured");
508 }
#define ERROR
Definition: elog.h:43
#define MAX_BACKENDS
Definition: postmaster.h:75
int MaxBackends
Definition: globals.c:125
int MaxConnections
Definition: globals.c:123
int autovacuum_max_workers
Definition: autovacuum.c:111
#define Assert(condition)
Definition: c.h:667
int max_worker_processes
Definition: globals.c:124
#define elog
Definition: elog.h:218
void InitializeSessionUserId ( const char *  rolename,
Oid  useroid 
)

Definition at line 481 of file miscinit.c.

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

Referenced by InitPostgres().

482 {
483  HeapTuple roleTup;
484  Form_pg_authid rform;
485  char *rname;
486 
487  /*
488  * Don't do scans if we're bootstrapping, none of the system catalogs
489  * exist yet, and they should be owned by postgres anyway.
490  */
492 
493  /* call only once */
495 
496  if (rolename != NULL)
497  {
498  roleTup = SearchSysCache1(AUTHNAME, PointerGetDatum(rolename));
499  if (!HeapTupleIsValid(roleTup))
500  ereport(FATAL,
501  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
502  errmsg("role \"%s\" does not exist", rolename)));
503  }
504  else
505  {
506  roleTup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
507  if (!HeapTupleIsValid(roleTup))
508  ereport(FATAL,
509  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
510  errmsg("role with OID %u does not exist", roleid)));
511  }
512 
513  rform = (Form_pg_authid) GETSTRUCT(roleTup);
514  roleid = HeapTupleGetOid(roleTup);
515  rname = NameStr(rform->rolname);
516 
517  AuthenticatedUserId = roleid;
518  AuthenticatedUserIsSuperuser = rform->rolsuper;
519 
520  /* This sets OuterUserId/CurrentUserId too */
522 
523  /* Also mark our PGPROC entry with the authenticated user id */
524  /* (We assume this is an atomic store so no lock is needed) */
525  MyProc->roleId = roleid;
526 
527  /*
528  * These next checks are not enforced when in standalone mode, so that
529  * there is a way to recover from sillinesses like "UPDATE pg_authid SET
530  * rolcanlogin = false;".
531  */
532  if (IsUnderPostmaster)
533  {
534  /*
535  * Is role allowed to login at all?
536  */
537  if (!rform->rolcanlogin)
538  ereport(FATAL,
539  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
540  errmsg("role \"%s\" is not permitted to log in",
541  rname)));
542 
543  /*
544  * Check connection limit for this role.
545  *
546  * There is a race condition here --- we create our PGPROC before
547  * checking for other PGPROCs. If two backends did this at about the
548  * same time, they might both think they were over the limit, while
549  * ideally one should succeed and one fail. Getting that to work
550  * exactly seems more trouble than it is worth, however; instead we
551  * just document that the connection limit is approximate.
552  */
553  if (rform->rolconnlimit >= 0 &&
555  CountUserBackends(roleid) > rform->rolconnlimit)
556  ereport(FATAL,
557  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
558  errmsg("too many connections for role \"%s\"",
559  rname)));
560  }
561 
562  /* Record username and superuser status as GUC settings too */
563  SetConfigOption("session_authorization", rname,
565  SetConfigOption("is_superuser",
566  AuthenticatedUserIsSuperuser ? "on" : "off",
568 
569  ReleaseSysCache(roleTup);
570 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define AssertState(condition)
Definition: c.h:670
PGPROC * MyProc
Definition: proc.c:65
#define PointerGetDatum(X)
Definition: postgres.h:564
Oid roleId
Definition: proc.h:103
int errcode(int sqlerrcode)
Definition: elog.c:575
#define OidIsValid(objectId)
Definition: c.h:530
#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:52
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6571
bool IsUnderPostmaster
Definition: globals.c:100
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:160
#define ereport(elevel, rest)
Definition: elog.h:122
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:990
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:226
int CountUserBackends(Oid roleid)
Definition: procarray.c:2797
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:364
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define NameStr(name)
Definition: c.h:494
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:324
static Oid AuthenticatedUserId
Definition: miscinit.c:154
void InitializeSessionUserIdStandalone ( void  )

Definition at line 577 of file miscinit.c.

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

Referenced by InitPostgres().

578 {
579  /*
580  * This function should only be called in single-user mode, in autovacuum
581  * workers, and in background workers.
582  */
584 
585  /* call only once */
587 
590 
592 }
#define AssertState(condition)
Definition: c.h:670
#define OidIsValid(objectId)
Definition: c.h:530
bool IsBackgroundWorker
Definition: globals.c:102
bool IsUnderPostmaster
Definition: globals.c:100
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:160
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:2905
#define BOOTSTRAP_SUPERUSERID
Definition: pg_authid.h:104
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:324
static Oid AuthenticatedUserId
Definition: miscinit.c:154
void InitPostgres ( const char *  in_dbname,
Oid  dboid,
const char *  username,
Oid  useroid,
char *  out_dbname 
)

Definition at line 560 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, IDLE_IN_TRANSACTION_SESSION_TIMEOUT, IdleInTransactionSessionTimeoutHandler(), 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().

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

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

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

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

219 {
221 
222  MyProcPid = getpid(); /* reset MyProcPid */
223 
224  MyStartTime = time(NULL); /* set our start time in case we call elog */
225 
226  /* Initialize process-local latch support */
230 
231  /* Compute paths, no postmaster to inherit from */
232  if (my_exec_path[0] == '\0')
233  {
234  if (find_my_exec(argv0, my_exec_path) < 0)
235  elog(FATAL, "%s: could not locate my own executable path",
236  argv0);
237  }
238 
239  if (pkglib_path[0] == '\0')
241 }
bool IsPostmasterEnvironment
Definition: globals.c:99
static char * argv0
Definition: pg_ctl.c:91
int MyProcPid
Definition: globals.c:38
pg_time_t MyStartTime
Definition: globals.c:39
void get_pkglib_path(const char *my_exec_path, char *ret_path)
Definition: path.c:758
static Latch LocalLatchData
Definition: miscinit.c:60
#define FATAL
Definition: elog.h:52
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:119
char my_exec_path[MAXPGPATH]
Definition: globals.c:63
void InitializeLatchSupport(void)
Definition: latch.c:156
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:667
void InitLatch(volatile Latch *latch)
Definition: latch.c:188
struct Latch * MyLatch
Definition: globals.c:51
#define elog
Definition: elog.h:218
char pkglib_path[MAXPGPATH]
Definition: globals.c:64
bool InLocalUserIdChange ( void  )

Definition at line 405 of file miscinit.c.

References SECURITY_LOCAL_USERID_CHANGE, and SecurityRestrictionContext.

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

406 {
408 }
static int SecurityRestrictionContext
Definition: miscinit.c:163
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:290
bool InNoForceRLSOperation ( void  )

Definition at line 423 of file miscinit.c.

References SECURITY_NOFORCE_RLS, and SecurityRestrictionContext.

Referenced by check_enable_rls().

424 {
426 }
static int SecurityRestrictionContext
Definition: miscinit.c:163
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:292
bool InSecurityRestrictedOperation ( void  )

Definition at line 414 of file miscinit.c.

References SECURITY_RESTRICTED_OPERATION, and SecurityRestrictionContext.

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

415 {
417 }
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:291
static int SecurityRestrictionContext
Definition: miscinit.c:163
void pg_bindtextdomain ( const char *  domain)

Definition at line 1488 of file miscinit.c.

References get_locale_path(), MAXPGPATH, and my_exec_path.

Referenced by _PG_init().

1489 {
1490 #ifdef ENABLE_NLS
1491  if (my_exec_path[0] != '\0')
1492  {
1493  char locale_path[MAXPGPATH];
1494 
1495  get_locale_path(my_exec_path, locale_path);
1496  bindtextdomain(domain, locale_path);
1497  pg_bind_textdomain_codeset(domain);
1498  }
1499 #endif
1500 }
#define MAXPGPATH
char my_exec_path[MAXPGPATH]
Definition: globals.c:63
void get_locale_path(const char *my_exec_path, char *ret_path)
Definition: path.c:767
void pg_split_opts ( char **  argv,
int *  argcp,
const char *  optstr 
)

Definition at line 438 of file postinit.c.

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

Referenced by BackendRun(), and process_startup_options().

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

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

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

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

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

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

Definition at line 229 of file utility.c.

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

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

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

Definition at line 1477 of file miscinit.c.

References load_libraries(), local_preload_libraries_string, and session_preload_libraries_string.

Referenced by PostgresMain().

1478 {
1480  "session_preload_libraries",
1481  false);
1483  "local_preload_libraries",
1484  true);
1485 }
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1409
char * local_preload_libraries_string
Definition: miscinit.c:1397
char * session_preload_libraries_string
Definition: miscinit.c:1395
void process_shared_preload_libraries ( void  )

Definition at line 1464 of file miscinit.c.

References load_libraries(), process_shared_preload_libraries_in_progress, and shared_preload_libraries_string.

Referenced by PostmasterMain().

1465 {
1468  "shared_preload_libraries",
1469  false);
1471 }
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1400
char * shared_preload_libraries_string
Definition: miscinit.c:1396
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1409
void ProcessInterrupts ( void  )

Definition at line 2833 of file postgres.c.

References Assert, ClientAuthInProgress, ClientConnectionLost, CritSectionCount, DestNone, DestRemote, DoingCommandRead, ereport, errcode(), errdetail_recovery_conflict(), errhint(), errmsg(), ERROR, FATAL, get_timeout_finish_time(), get_timeout_indicator(), HandleParallelMessages(), IdleInTransactionSessionTimeout, IdleInTransactionSessionTimeoutPending, InterruptHoldoffCount, InterruptPending, IsAutoVacuumWorkerProcess(), 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().

2834 {
2835  /* OK to accept any interrupts now? */
2836  if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
2837  return;
2838  InterruptPending = false;
2839 
2840  if (ProcDiePending)
2841  {
2842  ProcDiePending = false;
2843  QueryCancelPending = false; /* ProcDie trumps QueryCancel */
2844  LockErrorCleanup();
2845  /* As in quickdie, don't risk sending to client during auth */
2849  ereport(FATAL,
2850  (errcode(ERRCODE_QUERY_CANCELED),
2851  errmsg("canceling authentication due to timeout")));
2852  else if (IsAutoVacuumWorkerProcess())
2853  ereport(FATAL,
2854  (errcode(ERRCODE_ADMIN_SHUTDOWN),
2855  errmsg("terminating autovacuum process due to administrator command")));
2857  {
2859  ereport(FATAL,
2860  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2861  errmsg("terminating connection due to conflict with recovery"),
2863  }
2864  else if (RecoveryConflictPending)
2865  {
2866  /* Currently there is only one non-retryable recovery conflict */
2869  ereport(FATAL,
2870  (errcode(ERRCODE_DATABASE_DROPPED),
2871  errmsg("terminating connection due to conflict with recovery"),
2873  }
2874  else
2875  ereport(FATAL,
2876  (errcode(ERRCODE_ADMIN_SHUTDOWN),
2877  errmsg("terminating connection due to administrator command")));
2878  }
2880  {
2881  QueryCancelPending = false; /* lost connection trumps QueryCancel */
2882  LockErrorCleanup();
2883  /* don't send to client, we already know the connection to be dead. */
2885  ereport(FATAL,
2886  (errcode(ERRCODE_CONNECTION_FAILURE),
2887  errmsg("connection to client lost")));
2888  }
2889 
2890  /*
2891  * If a recovery conflict happens while we are waiting for input from the
2892  * client, the client is presumably just sitting idle in a transaction,
2893  * preventing recovery from making progress. Terminate the connection to
2894  * dislodge it.
2895  */
2897  {
2898  QueryCancelPending = false; /* this trumps QueryCancel */
2899  RecoveryConflictPending = false;
2900  LockErrorCleanup();
2902  ereport(FATAL,
2903  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2904  errmsg("terminating connection due to conflict with recovery"),
2906  errhint("In a moment you should be able to reconnect to the"
2907  " database and repeat your command.")));
2908  }
2909 
2910  if (QueryCancelPending)
2911  {
2912  bool lock_timeout_occurred;
2913  bool stmt_timeout_occurred;
2914 
2915  /*
2916  * Don't allow query cancel interrupts while reading input from the
2917  * client, because we might lose sync in the FE/BE protocol. (Die
2918  * interrupts are OK, because we won't read any further messages from
2919  * the client in that case.)
2920  */
2921  if (QueryCancelHoldoffCount != 0)
2922  {
2923  /*
2924  * Re-arm InterruptPending so that we process the cancel request
2925  * as soon as we're done reading the message.
2926  */
2927  InterruptPending = true;
2928  return;
2929  }
2930 
2931  QueryCancelPending = false;
2932 
2933  /*
2934  * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
2935  * need to clear both, so always fetch both.
2936  */
2937  lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
2938  stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
2939 
2940  /*
2941  * If both were set, we want to report whichever timeout completed
2942  * earlier; this ensures consistent behavior if the machine is slow
2943  * enough that the second timeout triggers before we get here. A tie
2944  * is arbitrarily broken in favor of reporting a lock timeout.
2945  */
2946  if (lock_timeout_occurred && stmt_timeout_occurred &&
2948  lock_timeout_occurred = false; /* report stmt timeout */
2949 
2950  if (lock_timeout_occurred)
2951  {
2952  LockErrorCleanup();
2953  ereport(ERROR,
2954  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
2955  errmsg("canceling statement due to lock timeout")));
2956  }
2957  if (stmt_timeout_occurred)
2958  {
2959  LockErrorCleanup();
2960  ereport(ERROR,
2961  (errcode(ERRCODE_QUERY_CANCELED),
2962  errmsg("canceling statement due to statement timeout")));
2963  }
2965  {
2966  LockErrorCleanup();
2967  ereport(ERROR,
2968  (errcode(ERRCODE_QUERY_CANCELED),
2969  errmsg("canceling autovacuum task")));
2970  }
2972  {
2973  RecoveryConflictPending = false;
2974  LockErrorCleanup();
2976  ereport(ERROR,
2977  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2978  errmsg("canceling statement due to conflict with recovery"),
2980  }
2981 
2982  /*
2983  * If we are reading a command from the client, just ignore the cancel
2984  * request --- sending an extra error message won't accomplish
2985  * anything. Otherwise, go ahead and throw the error.
2986  */
2987  if (!DoingCommandRead)
2988  {
2989  LockErrorCleanup();
2990  ereport(ERROR,
2991  (errcode(ERRCODE_QUERY_CANCELED),
2992  errmsg("canceling statement due to user request")));
2993  }
2994  }
2995 
2997  {
2998  /* Has the timeout setting changed since last we looked? */
3000  ereport(FATAL,
3001  (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
3002  errmsg("terminating connection due to idle-in-transaction timeout")));
3003  else
3005 
3006  }
3007 
3010 }
volatile uint32 InterruptHoldoffCount
Definition: globals.c:34
TimestampTz get_timeout_finish_time(TimeoutId id)
Definition: timeout.c:667
int errhint(const char *fmt,...)
Definition: elog.c:987
void pgstat_report_recovery_conflict(int reason)
Definition: pgstat.c:1402
volatile bool IdleInTransactionSessionTimeoutPending
Definition: globals.c:33
volatile uint32 QueryCancelHoldoffCount
Definition: globals.c:35
int errcode(int sqlerrcode)
Definition: elog.c:575
volatile bool QueryCancelPending
Definition: globals.c:30
volatile bool ClientConnectionLost
Definition: globals.c:32
bool ClientAuthInProgress
Definition: postmaster.c:346
#define ERROR
Definition: elog.h:43
int IdleInTransactionSessionTimeout
Definition: proc.c:61
#define FATAL
Definition: elog.h:52
void HandleParallelMessages(void)
Definition: parallel.c:701
Definition: dest.h:88
volatile uint32 CritSectionCount
Definition: globals.c:36
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:2905
#define ereport(elevel, rest)
Definition: elog.h:122
void LockErrorCleanup(void)
Definition: proc.c:677
static ProcSignalReason RecoveryConflictReason
Definition: postgres.c:166
static bool RecoveryConflictPending
Definition: postgres.c:164
static bool RecoveryConflictRetryable
Definition: postgres.c:165
bool get_timeout_indicator(TimeoutId id, bool reset_indicator)
Definition: timeout.c:633
static int errdetail_recovery_conflict(void)
Definition: postgres.c:2248
volatile bool InterruptPending
Definition: globals.c:29
#define Assert(condition)
Definition: c.h:667
static bool DoingCommandRead
Definition: postgres.c:142
bool ParallelMessagePending
Definition: parallel.c:97
volatile bool ProcDiePending
Definition: globals.c:31
int errmsg(const char *fmt,...)
Definition: elog.c:797
CommandDest whereToSendOutput
Definition: postgres.c:86
bool RecheckDataDirLockFile ( void  )

Definition at line 1262 of file miscinit.c.

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

Referenced by ServerLoop().

1263 {
1264  int fd;
1265  int len;
1266  long file_pid;
1267  char buffer[BLCKSZ];
1268 
1269  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1270  if (fd < 0)
1271  {
1272  /*
1273  * There are many foreseeable false-positive error conditions. For
1274  * safety, fail only on enumerated clearly-something-is-wrong
1275  * conditions.
1276  */
1277  switch (errno)
1278  {
1279  case ENOENT:
1280  case ENOTDIR:
1281  /* disaster */
1282  ereport(LOG,
1284  errmsg("could not open file \"%s\": %m",
1286  return false;
1287  default:
1288  /* non-fatal, at least for now */
1289  ereport(LOG,
1291  errmsg("could not open file \"%s\": %m; continuing anyway",
1293  return true;
1294  }
1295  }
1296  len = read(fd, buffer, sizeof(buffer) - 1);
1297  if (len < 0)
1298  {
1299  ereport(LOG,
1301  errmsg("could not read from file \"%s\": %m",
1303  close(fd);
1304  return true; /* treat read failure as nonfatal */
1305  }
1306  buffer[len] = '\0';
1307  close(fd);
1308  file_pid = atol(buffer);
1309  if (file_pid == getpid())
1310  return true; /* all is well */
1311 
1312  /* Trouble: someone's overwritten the lock file */
1313  ereport(LOG,
1314  (errmsg("lock file \"%s\" contains wrong PID: %ld instead of %ld",
1315  DIRECTORY_LOCK_FILE, file_pid, (long) getpid())));
1316  return false;
1317 }
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:53
#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:1018
int errcode_for_file_access(void)
Definition: elog.c:598
#define ereport(elevel, rest)
Definition: elog.h:122
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define close(a)
Definition: win32.h:17
#define read(a, b, c)
Definition: win32.h:18
void restore_stack_base ( pg_stack_base_t  base)

Definition at line 3088 of file postgres.c.

References stack_base_ptr.

3089 {
3090 #if defined(__ia64__) || defined(__ia64)
3091  stack_base_ptr = base.stack_base_ptr;
3092  register_stack_base_ptr = base.register_stack_base_ptr;
3093 #else
3094  stack_base_ptr = base;
3095 #endif
3096 }
char * stack_base_ptr
Definition: postgres.c:115
pg_stack_base_t set_stack_base ( void  )

Definition at line 3057 of file postgres.c.

References stack_base_ptr.

Referenced by PostmasterMain().

3058 {
3059  char stack_base;
3060  pg_stack_base_t old;
3061 
3062 #if defined(__ia64__) || defined(__ia64)
3063  old.stack_base_ptr = stack_base_ptr;
3064  old.register_stack_base_ptr = register_stack_base_ptr;
3065 #else
3066  old = stack_base_ptr;
3067 #endif
3068 
3069  /* Set up reference point for stack depth checking */
3070  stack_base_ptr = &stack_base;
3071 #if defined(__ia64__) || defined(__ia64)
3072  register_stack_base_ptr = ia64_get_bsp();
3073 #endif
3074 
3075  return old;
3076 }
char * stack_base_ptr
Definition: postgres.c:115
char * pg_stack_base_t
Definition: miscadmin.h:267
void SetCurrentRoleId ( Oid  roleid,
bool  is_superuser 
)

Definition at line 655 of file miscinit.c.

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

Referenced by assign_role().

656 {
657  /*
658  * Get correct info if it's SET ROLE NONE
659  *
660  * If SessionUserId hasn't been set yet, just do nothing --- the eventual
661  * SetSessionUserId call will fix everything. This is needed since we
662  * will get called during GUC initialization.
663  */
664  if (!OidIsValid(roleid))
665  {
667  return;
668 
669  roleid = SessionUserId;
671 
672  SetRoleIsActive = false;
673  }
674  else
675  SetRoleIsActive = true;
676 
677  SetOuterUserId(roleid);
678 
679  SetConfigOption("is_superuser",
680  is_superuser ? "on" : "off",
682 }
static Oid SessionUserId
Definition: miscinit.c:155
static void SetOuterUserId(Oid userid)
Definition: miscinit.c:301
#define OidIsValid(objectId)
Definition: c.h:530
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6571
static bool SetRoleIsActive
Definition: miscinit.c:166
static bool SessionUserIsSuperuser
Definition: miscinit.c:161
bool is_superuser(void)
Definition: common.c:1930
void SetDatabasePath ( const char *  path)

Definition at line 81 of file miscinit.c.

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

Referenced by InitPostgres().

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

Definition at line 93 of file miscinit.c.

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

Referenced by SelectConfigFiles().

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

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

610 {
611  /* Must have authenticated already, else can't make permission check */
613 
614  if (userid != AuthenticatedUserId &&
616  ereport(ERROR,
617  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
618  errmsg("permission denied to set session authorization")));
619 
621 
622  SetConfigOption("is_superuser",
623  is_superuser ? "on" : "off",
625 }
#define AssertState(condition)
Definition: c.h:670
int errcode(int sqlerrcode)
Definition: elog.c:575
#define OidIsValid(objectId)
Definition: c.h:530
#define ERROR
Definition: elog.h:43
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6571
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:160
#define ereport(elevel, rest)
Definition: elog.h:122
bool is_superuser(void)
Definition: common.c:1930
int errmsg(const char *fmt,...)
Definition: elog.c:797
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:324
static Oid AuthenticatedUserId
Definition: miscinit.c:154
void SetUserIdAndContext ( Oid  userid,
bool  sec_def_context 
)

Definition at line 443 of file miscinit.c.

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

444 {
445  /* We throw the same error SET ROLE would. */
447  ereport(ERROR,
448  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
449  errmsg("cannot set parameter \"%s\" within security-restricted operation",
450  "role")));
451  CurrentUserId = userid;
452  if (sec_def_context)
454  else
456 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
static int SecurityRestrictionContext
Definition: miscinit.c:163
#define ereport(elevel, rest)
Definition: elog.h:122
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:290
static Oid CurrentUserId
Definition: miscinit.c:157
bool InSecurityRestrictedOperation(void)
Definition: miscinit.c:414
int errmsg(const char *fmt,...)
Definition: elog.c:797
void SetUserIdAndSecContext ( Oid  userid,
int  sec_context 
)
bool stack_is_too_deep ( void  )

Definition at line 3124 of file postgres.c.

References max_stack_depth_bytes, NULL, and stack_base_ptr.

Referenced by check_stack_depth(), and rstacktoodeep().

3125 {
3126  char stack_top_loc;
3127  long stack_depth;
3128 
3129  /*
3130  * Compute distance from reference point to my local variables
3131  */
3132  stack_depth = (long) (stack_base_ptr - &stack_top_loc);
3133 
3134  /*
3135  * Take abs value, since stacks grow up on some machines, down on others
3136  */
3137  if (stack_depth < 0)
3138  stack_depth = -stack_depth;
3139 
3140  /*
3141  * Trouble?
3142  *
3143  * The test on stack_base_ptr prevents us from erroring out if called
3144  * during process setup or in a non-backend process. Logically it should
3145  * be done first, but putting it here avoids wasting cycles during normal
3146  * cases.
3147  */
3148  if (stack_depth > max_stack_depth_bytes &&
3149  stack_base_ptr != NULL)
3150  return true;
3151 
3152  /*
3153  * On IA64 there is a separate "register" stack that requires its own
3154  * independent check. For this, we have to measure the change in the
3155  * "BSP" pointer from PostgresMain to here. Logic is just as above,
3156  * except that we know IA64's register stack grows up.
3157  *
3158  * Note we assume that the same max_stack_depth applies to both stacks.
3159  */
3160 #if defined(__ia64__) || defined(__ia64)
3161  stack_depth = (long) (ia64_get_bsp() - register_stack_base_ptr);
3162 
3163  if (stack_depth > max_stack_depth_bytes &&
3164  register_stack_base_ptr != NULL)
3165  return true;
3166 #endif /* IA64 */
3167 
3168  return false;
3169 }
static long max_stack_depth_bytes
Definition: postgres.c:107
#define NULL
Definition: c.h:226
char * stack_base_ptr
Definition: postgres.c:115
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_metapage_info(), brin_page_items(), brin_page_type(), brin_revmap_data(), bt_metap(), bt_page_items(), bt_page_stats(), check_conn_params(), check_encoding_locale_matches(), check_permissions(), connect_pg_server(), CreateAccessMethod(), 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_logdir_ls(), pg_ls_dir(), pg_read_binary_file(), pg_read_file(), pg_relpages(), pg_relpagesbyid(), pg_signal_backend(), pg_stat_file(), pg_stat_get_wal_receiver(), pg_stat_get_wal_senders(), pg_stat_statements_internal(), pgstat_get_backend_current_activity(), pgstatginindex(), pgstatindex(), pgstatindexbyid(), pgstattuple(), pgstattuple_approx(), pgstattuplebyid(), ProcedureCreate(), regress_putenv(), RemoveAccessMethodById(), RenameRole(), replorigin_check_prerequisites(), requireSuperuser(), sepgsql_restorecon(), set_config_by_name(), SetPGVariable(), ShowAllGUCConfig(), standard_ProcessUtility(), tuple_data_split(), validate_option_array_item(), and wait_pid().

48 {
49  return superuser_arg(GetUserId());
50 }
Oid GetUserId(void)
Definition: miscinit.c:282
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:656
#define OidIsValid(objectId)
Definition: c.h:530
#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:100
void CacheRegisterSyscacheCallback(int cacheid, SyscacheCallbackFunction func, Datum arg)
Definition: inval.c:1354
uintptr_t Datum
Definition: postgres.h:374
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:990
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define BOOTSTRAP_SUPERUSERID
Definition: pg_authid.h:104
static bool roleid_callback_registered
Definition: superuser.c:38
void SwitchBackToLocalLatch ( void  )

Definition at line 263 of file miscinit.c.

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

Referenced by AuxiliaryProcKill(), and ProcKill().

264 {
267 
269 
270  if (FeBeWaitSet)
272 
273  SetLatch(MyLatch);
274 }
PGPROC * MyProc
Definition: proc.c:65
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:680
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:168
Latch procLatch
Definition: proc.h:92
static Latch LocalLatchData
Definition: miscinit.c:60
void SetLatch(volatile Latch *latch)
Definition: latch.c:377
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:667
struct Latch * MyLatch
Definition: globals.c:51
#define WL_LATCH_SET
Definition: latch.h:108
void SwitchToSharedLatch ( void  )

Definition at line 244 of file miscinit.c.

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

Referenced by InitAuxiliaryProcess(), and InitProcess().

245 {
247  Assert(MyProc != NULL);
248 
250 
251  if (FeBeWaitSet)
253 
254  /*
255  * Set the shared latch as the local one might have been set. This
256  * shouldn't normally be necessary as code is supposed to check the
257  * condition before waiting for the latch, but a bit care can't hurt.
258  */
259  SetLatch(MyLatch);
260 }
PGPROC * MyProc
Definition: proc.c:65
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:680
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:168
Latch procLatch
Definition: proc.h:92
static Latch LocalLatchData
Definition: miscinit.c:60
void SetLatch(volatile Latch *latch)
Definition: latch.c:377
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:667
struct Latch * MyLatch
Definition: globals.c:51
#define WL_LATCH_SET
Definition: latch.h:108
void TouchSocketLockFiles ( void  )

Definition at line 1099 of file miscinit.c.

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

Referenced by ServerLoop().

1100 {
1101  ListCell *l;
1102 
1103  foreach(l, lock_files)
1104  {
1105  char *socketLockFile = (char *) lfirst(l);
1106 
1107  /* No need to touch the data directory lock file, we trust */
1108  if (strcmp(socketLockFile, DIRECTORY_LOCK_FILE) == 0)
1109  continue;
1110 
1111  /*
1112  * utime() is POSIX standard, utimes() is a common alternative; if we
1113  * have neither, fall back to actually reading the file (which only
1114  * sets the access time not mod time, but that should be enough in
1115  * most cases). In all paths, we ignore errors.
1116  */
1117 #ifdef HAVE_UTIME
1118  utime(socketLockFile, NULL);
1119 #else /* !HAVE_UTIME */
1120 #ifdef HAVE_UTIMES
1121  utimes(socketLockFile, NULL);
1122 #else /* !HAVE_UTIMES */
1123  int fd;
1124  char buffer[1];
1125 
1126  fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
1127  if (fd >= 0)
1128  {
1129  read(fd, buffer, sizeof(buffer));
1130  close(fd);
1131  }
1132 #endif /* HAVE_UTIMES */
1133 #endif /* HAVE_UTIME */
1134  }
1135 }
static List * lock_files
Definition: miscinit.c:58
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:53
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PG_BINARY
Definition: c.h:1018
#define NULL
Definition: c.h:226
#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 1332 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().

1333 {
1334  char full_path[MAXPGPATH];
1335  FILE *file;
1336  int ret;
1337  long file_major,
1338  file_minor;
1339  long my_major = 0,
1340  my_minor = 0;
1341  char *endptr;
1342  const char *version_string = PG_VERSION;
1343 
1344  my_major = strtol(version_string, &endptr, 10);
1345  if (*endptr == '.')
1346  my_minor = strtol(endptr + 1, NULL, 10);
1347 
1348  snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
1349 
1350  file = AllocateFile(full_path, "r");
1351  if (!file)
1352  {
1353  if (errno == ENOENT)
1354  ereport(FATAL,
1355  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1356  errmsg("\"%s\" is not a valid data directory",
1357  path),
1358  errdetail("File \"%s\" is missing.", full_path)));
1359  else
1360  ereport(FATAL,
1362  errmsg("could not open file \"%s\": %m", full_path)));
1363  }
1364 
1365  ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
1366  if (ret != 2)
1367  ereport(FATAL,
1368  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1369  errmsg("\"%s\" is not a valid data directory",
1370  path),
1371  errdetail("File \"%s\" does not contain valid data.",
1372  full_path),
1373  errhint("You might need to initdb.")));
1374 
1375  FreeFile(file);
1376 
1377  if (my_major != file_major || my_minor != file_minor)
1378  ereport(FATAL,
1379  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1380  errmsg("database files are incompatible with server"),
1381  errdetail("The data directory was initialized by PostgreSQL version %ld.%ld, "
1382  "which is not compatible with this version %s.",
1383  file_major, file_minor, version_string)));
1384 }
int errhint(const char *fmt,...)
Definition: elog.c:987
int errcode(int sqlerrcode)
Definition: elog.c:575
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define FATAL
Definition: elog.h:52
#define MAXPGPATH
int errdetail(const char *fmt,...)
Definition: elog.c:873
int errcode_for_file_access(void)
Definition: elog.c:598
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:1966
#define ereport(elevel, rest)
Definition: elog.h:122
#define NULL
Definition: c.h:226
int FreeFile(FILE *file)
Definition: fd.c:2149
int errmsg(const char *fmt,...)
Definition: elog.c:797

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

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

PGDLLIMPORT volatile bool IdleInTransactionSessionTimeoutPending

Definition at line 33 of file globals.c.

Referenced by IdleInTransactionSessionTimeoutHandler(), and ProcessInterrupts().

bool IgnoreSystemIndexes
PGDLLIMPORT volatile uint32 InterruptHoldoffCount

Definition at line 34 of file globals.c.

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

PGDLLIMPORT int IntervalStyle
bool IsBackgroundWorker
PGDLLIMPORT bool IsUnderPostmaster

Definition at line 100 of file globals.c.

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

char* local_preload_libraries_string

Definition at line 1397 of file miscinit.c.

Referenced by process_session_preload_libraries().

Definition at line 55 of file miscinit.c.

AuxProcType MyAuxProcType

Definition at line 65 of file bootstrap.c.

Referenced by AuxiliaryProcessMain().

long MyCancelKey
PGDLLIMPORT Oid MyDatabaseId

Definition at line 76 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_ListenPreCommit(), 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(), LogLogicalMessage(), LogStandbyInvalidations(), map_sql_catalog_to_xmlschema_types(), map_sql_schema_to_xmlschema_types(), map_sql_table_to_xmlschema(), map_sql_type_to_xml_name(), movedb(), perform_relmap_update(), 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 122 of file globals.c.

char OutputFileName[]

Definition at line 61 of file globals.c.

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

char pkglib_path[]

Definition at line 64 of file globals.c.

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

PGDLLIMPORT bool process_shared_preload_libraries_in_progress
PGDLLIMPORT volatile uint32 QueryCancelHoldoffCount

Definition at line 35 of file globals.c.

Referenced by errfinish(), and ProcessInterrupts().

PGDLLIMPORT int replacement_sort_tuples

Definition at line 114 of file globals.c.

Referenced by useselection().

char* session_preload_libraries_string

Definition at line 1395 of file miscinit.c.

Referenced by process_session_preload_libraries().

char* shared_preload_libraries_string

Definition at line 1396 of file miscinit.c.

Referenced by process_shared_preload_libraries().

int trace_recovery_messages

Definition at line 433 of file guc.c.

Referenced by StartupXLOG(), and trace_recovery().

bool VacuumCostActive
int VacuumCostBalance
int VacuumCostLimit
int VacuumCostPageDirty

Definition at line 129 of file globals.c.

Referenced by MarkBufferDirty(), and MarkBufferDirtyHint().

int VacuumCostPageHit

Definition at line 127 of file globals.c.

Referenced by ReadBuffer_common().

int VacuumCostPageMiss

Definition at line 128 of file globals.c.

Referenced by ReadBuffer_common().

int VacuumPageDirty

Definition at line 135 of file globals.c.

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

int VacuumPageHit

Definition at line 133 of file globals.c.

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

int VacuumPageMiss

Definition at line 134 of file globals.c.

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

PGDLLIMPORT int work_mem

Definition at line 112 of file globals.c.

Referenced by _bt_spoolinit(), begin_partition(), brin_page_items(), BuildTupleHashTable(), choose_hashed_setop(), collectMatchBitmap(), connectby(), cost_material(), cost_rescan(), create_distinct_paths(), create_grouping_paths(), create_groupingsets_path(), create_merge_append_path(), create_sort_path(), create_unique_path(), crosstab(), dblink_get_notify(), deflist_to_tuplestore(), each_worker(), each_worker_jsonb(), elements_worker(), elements_worker_jsonb(), exec_init_tuple_store(), ExecChooseHashTableSize(), ExecHashTableCreate(), ExecInitCteScan(), ExecInitRecursiveUnion(), ExecMakeTableFunctionResult(), ExecMaterial(), ExecRecursiveUnion(), ExecSort(), final_cost_mergejoin(), fmgr_sql(), get_crosstab_tuplestore(), GetCurrentFDWTuplestore(), ginInsertCleanup(), initial_cost_mergejoin(), initialize_aggregate(), initialize_phase(), label_sort_with_costsize(), materializeQueryResult(), materializeResult(), MultiExecBitmapIndexScan(), MultiExecBitmapOr(), ordered_set_startup(), pg_available_extension_versions(), pg_available_extensions(), pg_config(), pg_cursor(), pg_event_trigger_ddl_commands(), pg_event_trigger_dropped_objects(), pg_extension_update_paths(), pg_get_replication_slots(), pg_logical_slot_get_changes_guts(), pg_prepared_statement(), pg_show_replication_origin_status(), pg_stat_get_activity(), pg_stat_get_progress_info(), pg_stat_get_wal_senders(), pg_stat_statements_internal(), pg_stop_backup_v2(), plperl_return_next(), populate_recordset_worker(), PortalCreateHoldStore(), show_all_file_settings(), storeRow(), subplan_is_hashable(), and xpath_table().