PostgreSQL Source Code  git master
miscinit.c File Reference
#include "postgres.h"
#include <sys/param.h>
#include <signal.h>
#include <time.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <grp.h>
#include <pwd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <utime.h>
#include "access/htup_details.h"
#include "catalog/pg_authid.h"
#include "common/file_perm.h"
#include "libpq/libpq.h"
#include "libpq/pqsignal.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "postmaster/autovacuum.h"
#include "postmaster/interrupt.h"
#include "postmaster/pgarch.h"
#include "postmaster/postmaster.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/latch.h"
#include "storage/pg_shmem.h"
#include "storage/pmsignal.h"
#include "storage/proc.h"
#include "storage/procarray.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "utils/inval.h"
#include "utils/memutils.h"
#include "utils/pidfile.h"
#include "utils/syscache.h"
#include "utils/varlena.h"
Include dependency graph for miscinit.c:

Go to the source code of this file.

Macros

#define DIRECTORY_LOCK_FILE   "postmaster.pid"
 

Functions

void InitPostmasterChild (void)
 
void InitStandaloneProcess (const char *argv0)
 
void SwitchToSharedLatch (void)
 
void SwitchBackToLocalLatch (void)
 
const char * GetBackendTypeDesc (BackendType backendType)
 
void SetDatabasePath (const char *path)
 
void checkDataDir (void)
 
void SetDataDir (const char *dir)
 
void ChangeToDataDir (void)
 
Oid GetUserId (void)
 
Oid GetOuterUserId (void)
 
static void SetOuterUserId (Oid userid)
 
Oid GetSessionUserId (void)
 
static void SetSessionUserId (Oid userid, bool is_superuser)
 
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)
 
bool has_rolreplication (Oid roleid)
 
void InitializeSessionUserId (const char *rolename, Oid roleid)
 
void InitializeSessionUserIdStandalone (void)
 
void SetSessionAuthorization (Oid userid, bool is_superuser)
 
Oid GetCurrentRoleId (void)
 
void SetCurrentRoleId (Oid roleid, bool is_superuser)
 
char * GetUserNameFromId (Oid roleid, bool noerr)
 
static void UnlinkLockFiles (int status, Datum arg)
 
static void CreateLockFile (const char *filename, bool amPostmaster, const char *socketDir, bool isDDLock, const char *refName)
 
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)
 
static void load_libraries (const char *libraries, const char *gucname, bool restricted)
 
void process_shared_preload_libraries (void)
 
void process_session_preload_libraries (void)
 
void process_shmem_requests (void)
 
void pg_bindtextdomain (const char *domain)
 

Variables

ProcessingMode Mode = InitProcessing
 
BackendType MyBackendType
 
static Listlock_files = NIL
 
static Latch LocalLatchData
 
bool IgnoreSystemIndexes = false
 
static Oid AuthenticatedUserId = InvalidOid
 
static Oid SessionUserId = InvalidOid
 
static Oid OuterUserId = InvalidOid
 
static Oid CurrentUserId = InvalidOid
 
static bool AuthenticatedUserIsSuperuser = false
 
static bool SessionUserIsSuperuser = false
 
static int SecurityRestrictionContext = 0
 
static bool SetRoleIsActive = false
 
char * session_preload_libraries_string = NULL
 
char * shared_preload_libraries_string = NULL
 
char * local_preload_libraries_string = NULL
 
bool process_shared_preload_libraries_in_progress = false
 
bool process_shared_preload_libraries_done = false
 
shmem_request_hook_type shmem_request_hook = NULL
 
bool process_shmem_requests_in_progress = false
 

Macro Definition Documentation

◆ DIRECTORY_LOCK_FILE

#define DIRECTORY_LOCK_FILE   "postmaster.pid"

Definition at line 59 of file miscinit.c.

Function Documentation

◆ AddToDataDirLockFile()

void AddToDataDirLockFile ( int  target_line,
const char *  str 
)

Definition at line 1351 of file miscinit.c.

1352 {
1353  int fd;
1354  int len;
1355  int lineno;
1356  char *srcptr;
1357  char *destptr;
1358  char srcbuffer[BLCKSZ];
1359  char destbuffer[BLCKSZ];
1360 
1361  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1362  if (fd < 0)
1363  {
1364  ereport(LOG,
1366  errmsg("could not open file \"%s\": %m",
1368  return;
1369  }
1371  len = read(fd, srcbuffer, sizeof(srcbuffer) - 1);
1373  if (len < 0)
1374  {
1375  ereport(LOG,
1377  errmsg("could not read from file \"%s\": %m",
1379  close(fd);
1380  return;
1381  }
1382  srcbuffer[len] = '\0';
1383 
1384  /*
1385  * Advance over lines we are not supposed to rewrite, then copy them to
1386  * destbuffer.
1387  */
1388  srcptr = srcbuffer;
1389  for (lineno = 1; lineno < target_line; lineno++)
1390  {
1391  char *eol = strchr(srcptr, '\n');
1392 
1393  if (eol == NULL)
1394  break; /* not enough lines in file yet */
1395  srcptr = eol + 1;
1396  }
1397  memcpy(destbuffer, srcbuffer, srcptr - srcbuffer);
1398  destptr = destbuffer + (srcptr - srcbuffer);
1399 
1400  /*
1401  * Fill in any missing lines before the target line, in case lines are
1402  * added to the file out of order.
1403  */
1404  for (; lineno < target_line; lineno++)
1405  {
1406  if (destptr < destbuffer + sizeof(destbuffer))
1407  *destptr++ = '\n';
1408  }
1409 
1410  /*
1411  * Write or rewrite the target line.
1412  */
1413  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s\n", str);
1414  destptr += strlen(destptr);
1415 
1416  /*
1417  * If there are more lines in the old file, append them to destbuffer.
1418  */
1419  if ((srcptr = strchr(srcptr, '\n')) != NULL)
1420  {
1421  srcptr++;
1422  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s",
1423  srcptr);
1424  }
1425 
1426  /*
1427  * And rewrite the data. Since we write in a single kernel call, this
1428  * update should appear atomic to onlookers.
1429  */
1430  len = strlen(destbuffer);
1431  errno = 0;
1433  if (pg_pwrite(fd, destbuffer, len, 0) != len)
1434  {
1436  /* if write didn't set errno, assume problem is no disk space */
1437  if (errno == 0)
1438  errno = ENOSPC;
1439  ereport(LOG,
1441  errmsg("could not write to file \"%s\": %m",
1443  close(fd);
1444  return;
1445  }
1448  if (pg_fsync(fd) != 0)
1449  {
1450  ereport(LOG,
1452  errmsg("could not write to file \"%s\": %m",
1454  }
1456  if (close(fd) != 0)
1457  {
1458  ereport(LOG,
1460  errmsg("could not write to file \"%s\": %m",
1462  }
1463 }
#define PG_BINARY
Definition: c.h:1268
int errcode_for_file_access(void)
Definition: elog.c:716
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define LOG
Definition: elog.h:25
#define ereport(elevel,...)
Definition: elog.h:143
int pg_fsync(int fd)
Definition: fd.c:359
#define close(a)
Definition: win32.h:12
#define read(a, b, c)
Definition: win32.h:13
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:59
const void size_t len
ssize_t pg_pwrite(int fd, const void *buf, size_t nbyte, off_t offset)
Definition: pwrite.c:27
#define snprintf
Definition: port.h:225
static int fd(const char *x, int i)
Definition: preproc-init.c:105
@ WAIT_EVENT_LOCK_FILE_ADDTODATADIR_WRITE
Definition: wait_event.h:184
@ WAIT_EVENT_LOCK_FILE_ADDTODATADIR_READ
Definition: wait_event.h:182
@ WAIT_EVENT_LOCK_FILE_ADDTODATADIR_SYNC
Definition: wait_event.h:183
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:266
static void pgstat_report_wait_end(void)
Definition: wait_event.h:282

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

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

◆ ChangeToDataDir()

void ChangeToDataDir ( void  )

Definition at line 432 of file miscinit.c.

433 {
435 
436  if (chdir(DataDir) < 0)
437  ereport(FATAL,
439  errmsg("could not change directory to \"%s\": %m",
440  DataDir)));
441 }
#define AssertState(condition)
Definition: c.h:807
#define FATAL
Definition: elog.h:35
char * DataDir
Definition: globals.c:66

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

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

◆ checkDataDir()

void checkDataDir ( void  )

Definition at line 318 of file miscinit.c.

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

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

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

◆ CreateDataDirLockFile()

void CreateDataDirLockFile ( bool  amPostmaster)

Definition at line 1295 of file miscinit.c.

1296 {
1297  CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, "", true, DataDir);
1298 }
static void CreateLockFile(const char *filename, bool amPostmaster, const char *socketDir, bool isDDLock, const char *refName)
Definition: miscinit.c:990

References CreateLockFile(), DataDir, and DIRECTORY_LOCK_FILE.

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

◆ CreateLockFile()

static void CreateLockFile ( const char *  filename,
bool  amPostmaster,
const char *  socketDir,
bool  isDDLock,
const char *  refName 
)
static

Definition at line 990 of file miscinit.c.

993 {
994  int fd;
995  char buffer[MAXPGPATH * 2 + 256];
996  int ntries;
997  int len;
998  int encoded_pid;
999  pid_t other_pid;
1000  pid_t my_pid,
1001  my_p_pid,
1002  my_gp_pid;
1003  const char *envvar;
1004 
1005  /*
1006  * If the PID in the lockfile is our own PID or our parent's or
1007  * grandparent's PID, then the file must be stale (probably left over from
1008  * a previous system boot cycle). We need to check this because of the
1009  * likelihood that a reboot will assign exactly the same PID as we had in
1010  * the previous reboot, or one that's only one or two counts larger and
1011  * hence the lockfile's PID now refers to an ancestor shell process. We
1012  * allow pg_ctl to pass down its parent shell PID (our grandparent PID)
1013  * via the environment variable PG_GRANDPARENT_PID; this is so that
1014  * launching the postmaster via pg_ctl can be just as reliable as
1015  * launching it directly. There is no provision for detecting
1016  * further-removed ancestor processes, but if the init script is written
1017  * carefully then all but the immediate parent shell will be root-owned
1018  * processes and so the kill test will fail with EPERM. Note that we
1019  * cannot get a false negative this way, because an existing postmaster
1020  * would surely never launch a competing postmaster or pg_ctl process
1021  * directly.
1022  */
1023  my_pid = getpid();
1024 
1025 #ifndef WIN32
1026  my_p_pid = getppid();
1027 #else
1028 
1029  /*
1030  * Windows hasn't got getppid(), but doesn't need it since it's not using
1031  * real kill() either...
1032  */
1033  my_p_pid = 0;
1034 #endif
1035 
1036  envvar = getenv("PG_GRANDPARENT_PID");
1037  if (envvar)
1038  my_gp_pid = atoi(envvar);
1039  else
1040  my_gp_pid = 0;
1041 
1042  /*
1043  * We need a loop here because of race conditions. But don't loop forever
1044  * (for example, a non-writable $PGDATA directory might cause a failure
1045  * that won't go away). 100 tries seems like plenty.
1046  */
1047  for (ntries = 0;; ntries++)
1048  {
1049  /*
1050  * Try to create the lock file --- O_EXCL makes this atomic.
1051  *
1052  * Think not to make the file protection weaker than 0600/0640. See
1053  * comments below.
1054  */
1055  fd = open(filename, O_RDWR | O_CREAT | O_EXCL, pg_file_create_mode);
1056  if (fd >= 0)
1057  break; /* Success; exit the retry loop */
1058 
1059  /*
1060  * Couldn't create the pid file. Probably it already exists.
1061  */
1062  if ((errno != EEXIST && errno != EACCES) || ntries > 100)
1063  ereport(FATAL,
1065  errmsg("could not create lock file \"%s\": %m",
1066  filename)));
1067 
1068  /*
1069  * Read the file to get the old owner's PID. Note race condition
1070  * here: file might have been deleted since we tried to create it.
1071  */
1072  fd = open(filename, O_RDONLY, pg_file_create_mode);
1073  if (fd < 0)
1074  {
1075  if (errno == ENOENT)
1076  continue; /* race condition; try again */
1077  ereport(FATAL,
1079  errmsg("could not open lock file \"%s\": %m",
1080  filename)));
1081  }
1083  if ((len = read(fd, buffer, sizeof(buffer) - 1)) < 0)
1084  ereport(FATAL,
1086  errmsg("could not read lock file \"%s\": %m",
1087  filename)));
1089  close(fd);
1090 
1091  if (len == 0)
1092  {
1093  ereport(FATAL,
1094  (errcode(ERRCODE_LOCK_FILE_EXISTS),
1095  errmsg("lock file \"%s\" is empty", filename),
1096  errhint("Either another server is starting, or the lock file is the remnant of a previous server startup crash.")));
1097  }
1098 
1099  buffer[len] = '\0';
1100  encoded_pid = atoi(buffer);
1101 
1102  /* if pid < 0, the pid is for postgres, not postmaster */
1103  other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
1104 
1105  if (other_pid <= 0)
1106  elog(FATAL, "bogus data in lock file \"%s\": \"%s\"",
1107  filename, buffer);
1108 
1109  /*
1110  * Check to see if the other process still exists
1111  *
1112  * Per discussion above, my_pid, my_p_pid, and my_gp_pid can be
1113  * ignored as false matches.
1114  *
1115  * Normally kill() will fail with ESRCH if the given PID doesn't
1116  * exist.
1117  *
1118  * We can treat the EPERM-error case as okay because that error
1119  * implies that the existing process has a different userid than we
1120  * do, which means it cannot be a competing postmaster. A postmaster
1121  * cannot successfully attach to a data directory owned by a userid
1122  * other than its own, as enforced in checkDataDir(). Also, since we
1123  * create the lockfiles mode 0600/0640, we'd have failed above if the
1124  * lockfile belonged to another userid --- which means that whatever
1125  * process kill() is reporting about isn't the one that made the
1126  * lockfile. (NOTE: this last consideration is the only one that
1127  * keeps us from blowing away a Unix socket file belonging to an
1128  * instance of Postgres being run by someone else, at least on
1129  * machines where /tmp hasn't got a stickybit.)
1130  */
1131  if (other_pid != my_pid && other_pid != my_p_pid &&
1132  other_pid != my_gp_pid)
1133  {
1134  if (kill(other_pid, 0) == 0 ||
1135  (errno != ESRCH && errno != EPERM))
1136  {
1137  /* lockfile belongs to a live process */
1138  ereport(FATAL,
1139  (errcode(ERRCODE_LOCK_FILE_EXISTS),
1140  errmsg("lock file \"%s\" already exists",
1141  filename),
1142  isDDLock ?
1143  (encoded_pid < 0 ?
1144  errhint("Is another postgres (PID %d) running in data directory \"%s\"?",
1145  (int) other_pid, refName) :
1146  errhint("Is another postmaster (PID %d) running in data directory \"%s\"?",
1147  (int) other_pid, refName)) :
1148  (encoded_pid < 0 ?
1149  errhint("Is another postgres (PID %d) using socket file \"%s\"?",
1150  (int) other_pid, refName) :
1151  errhint("Is another postmaster (PID %d) using socket file \"%s\"?",
1152  (int) other_pid, refName))));
1153  }
1154  }
1155 
1156  /*
1157  * No, the creating process did not exist. However, it could be that
1158  * the postmaster crashed (or more likely was kill -9'd by a clueless
1159  * admin) but has left orphan backends behind. Check for this by
1160  * looking to see if there is an associated shmem segment that is
1161  * still in use.
1162  *
1163  * Note: because postmaster.pid is written in multiple steps, we might
1164  * not find the shmem ID values in it; we can't treat that as an
1165  * error.
1166  */
1167  if (isDDLock)
1168  {
1169  char *ptr = buffer;
1170  unsigned long id1,
1171  id2;
1172  int lineno;
1173 
1174  for (lineno = 1; lineno < LOCK_FILE_LINE_SHMEM_KEY; lineno++)
1175  {
1176  if ((ptr = strchr(ptr, '\n')) == NULL)
1177  break;
1178  ptr++;
1179  }
1180 
1181  if (ptr != NULL &&
1182  sscanf(ptr, "%lu %lu", &id1, &id2) == 2)
1183  {
1184  if (PGSharedMemoryIsInUse(id1, id2))
1185  ereport(FATAL,
1186  (errcode(ERRCODE_LOCK_FILE_EXISTS),
1187  errmsg("pre-existing shared memory block (key %lu, ID %lu) is still in use",
1188  id1, id2),
1189  errhint("Terminate any old server processes associated with data directory \"%s\".",
1190  refName)));
1191  }
1192  }
1193 
1194  /*
1195  * Looks like nobody's home. Unlink the file and try again to create
1196  * it. Need a loop because of possible race condition against other
1197  * would-be creators.
1198  */
1199  if (unlink(filename) < 0)
1200  ereport(FATAL,
1202  errmsg("could not remove old lock file \"%s\": %m",
1203  filename),
1204  errhint("The file seems accidentally left over, but "
1205  "it could not be removed. Please remove the file "
1206  "by hand and try again.")));
1207  }
1208 
1209  /*
1210  * Successfully created the file, now fill it. See comment in pidfile.h
1211  * about the contents. Note that we write the same first five lines into
1212  * both datadir and socket lockfiles; although more stuff may get added to
1213  * the datadir lockfile later.
1214  */
1215  snprintf(buffer, sizeof(buffer), "%d\n%s\n%ld\n%d\n%s\n",
1216  amPostmaster ? (int) my_pid : -((int) my_pid),
1217  DataDir,
1218  (long) MyStartTime,
1220  socketDir);
1221 
1222  /*
1223  * In a standalone backend, the next line (LOCK_FILE_LINE_LISTEN_ADDR)
1224  * will never receive data, so fill it in as empty now.
1225  */
1226  if (isDDLock && !amPostmaster)
1227  strlcat(buffer, "\n", sizeof(buffer));
1228 
1229  errno = 0;
1231  if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
1232  {
1233  int save_errno = errno;
1234 
1235  close(fd);
1236  unlink(filename);
1237  /* if write didn't set errno, assume problem is no disk space */
1238  errno = save_errno ? save_errno : ENOSPC;
1239  ereport(FATAL,
1241  errmsg("could not write lock file \"%s\": %m", filename)));
1242  }
1244 
1246  if (pg_fsync(fd) != 0)
1247  {
1248  int save_errno = errno;
1249 
1250  close(fd);
1251  unlink(filename);
1252  errno = save_errno;
1253  ereport(FATAL,
1255  errmsg("could not write lock file \"%s\": %m", filename)));
1256  }
1258  if (close(fd) != 0)
1259  {
1260  int save_errno = errno;
1261 
1262  unlink(filename);
1263  errno = save_errno;
1264  ereport(FATAL,
1266  errmsg("could not write lock file \"%s\": %m", filename)));
1267  }
1268 
1269  /*
1270  * Arrange to unlink the lock file(s) at proc_exit. If this is the first
1271  * one, set up the on_proc_exit function to do it; then add this lock file
1272  * to the list of files to unlink.
1273  */
1274  if (lock_files == NIL)
1276 
1277  /*
1278  * Use lcons so that the lock files are unlinked in reverse order of
1279  * creation; this is critical!
1280  */
1282 }
#define elog(elevel,...)
Definition: elog.h:218
int pg_file_create_mode
Definition: file_perm.c:19
pg_time_t MyStartTime
Definition: globals.c:45
#define write(a, b, c)
Definition: win32.h:14
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:305
List * lcons(void *datum, List *list)
Definition: list.c:474
char * pstrdup(const char *in)
Definition: mcxt.c:1305
static List * lock_files
Definition: miscinit.c:66
static void UnlinkLockFiles(int status, Datum arg)
Definition: miscinit.c:955
#define MAXPGPATH
static char * filename
Definition: pg_dumpall.c:94
#define NIL
Definition: pg_list.h:65
#define LOCK_FILE_LINE_SHMEM_KEY
Definition: pidfile.h:43
size_t strlcat(char *dst, const char *src, size_t siz)
Definition: strlcat.c:33
int PostPortNumber
Definition: postmaster.c:202
bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2)
Definition: sysv_shmem.c:320
@ WAIT_EVENT_LOCK_FILE_CREATE_SYNC
Definition: wait_event.h:186
@ WAIT_EVENT_LOCK_FILE_CREATE_READ
Definition: wait_event.h:185
@ WAIT_EVENT_LOCK_FILE_CREATE_WRITE
Definition: wait_event.h:187
#define kill(pid, sig)
Definition: win32_port.h:464

References close, DataDir, elog, ereport, errcode(), errcode_for_file_access(), errhint(), errmsg(), FATAL, fd(), filename, kill, lcons(), len, LOCK_FILE_LINE_SHMEM_KEY, lock_files, MAXPGPATH, MyStartTime, NIL, on_proc_exit(), pg_file_create_mode, pg_fsync(), PGSharedMemoryIsInUse(), pgstat_report_wait_end(), pgstat_report_wait_start(), PostPortNumber, pstrdup(), read, snprintf, strlcat(), UnlinkLockFiles(), WAIT_EVENT_LOCK_FILE_CREATE_READ, WAIT_EVENT_LOCK_FILE_CREATE_SYNC, WAIT_EVENT_LOCK_FILE_CREATE_WRITE, and write.

Referenced by CreateDataDirLockFile(), and CreateSocketLockFile().

◆ CreateSocketLockFile()

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

Definition at line 1304 of file miscinit.c.

1306 {
1307  char lockfile[MAXPGPATH];
1308 
1309  snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
1310  CreateLockFile(lockfile, amPostmaster, socketDir, false, socketfile);
1311 }

References CreateLockFile(), MAXPGPATH, and snprintf.

◆ GetAuthenticatedUserId()

Oid GetAuthenticatedUserId ( void  )

Definition at line 551 of file miscinit.c.

552 {
554  return AuthenticatedUserId;
555 }
#define OidIsValid(objectId)
Definition: c.h:710
static Oid AuthenticatedUserId
Definition: miscinit.c:472

References AssertState, AuthenticatedUserId, and OidIsValid.

Referenced by InitializeParallelDSM().

◆ GetBackendTypeDesc()

const char* GetBackendTypeDesc ( BackendType  backendType)

Definition at line 249 of file miscinit.c.

250 {
251  const char *backendDesc = "unknown process type";
252 
253  switch (backendType)
254  {
255  case B_INVALID:
256  backendDesc = "not initialized";
257  break;
258  case B_AUTOVAC_LAUNCHER:
259  backendDesc = "autovacuum launcher";
260  break;
261  case B_AUTOVAC_WORKER:
262  backendDesc = "autovacuum worker";
263  break;
264  case B_BACKEND:
265  backendDesc = "client backend";
266  break;
267  case B_BG_WORKER:
268  backendDesc = "background worker";
269  break;
270  case B_BG_WRITER:
271  backendDesc = "background writer";
272  break;
273  case B_CHECKPOINTER:
274  backendDesc = "checkpointer";
275  break;
276  case B_STARTUP:
277  backendDesc = "startup";
278  break;
279  case B_WAL_RECEIVER:
280  backendDesc = "walreceiver";
281  break;
282  case B_WAL_SENDER:
283  backendDesc = "walsender";
284  break;
285  case B_WAL_WRITER:
286  backendDesc = "walwriter";
287  break;
288  case B_ARCHIVER:
289  backendDesc = "archiver";
290  break;
291  case B_LOGGER:
292  backendDesc = "logger";
293  break;
294  }
295 
296  return backendDesc;
297 }
@ B_WAL_WRITER
Definition: miscadmin.h:336
@ B_WAL_RECEIVER
Definition: miscadmin.h:334
@ B_CHECKPOINTER
Definition: miscadmin.h:332
@ B_WAL_SENDER
Definition: miscadmin.h:335
@ B_LOGGER
Definition: miscadmin.h:338
@ B_STARTUP
Definition: miscadmin.h:333
@ B_BG_WORKER
Definition: miscadmin.h:330
@ B_INVALID
Definition: miscadmin.h:326
@ B_BG_WRITER
Definition: miscadmin.h:331
@ B_BACKEND
Definition: miscadmin.h:329
@ B_ARCHIVER
Definition: miscadmin.h:337
@ B_AUTOVAC_LAUNCHER
Definition: miscadmin.h:327
@ B_AUTOVAC_WORKER
Definition: miscadmin.h:328

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

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

◆ GetCurrentRoleId()

Oid GetCurrentRoleId ( void  )

Definition at line 857 of file miscinit.c.

858 {
859  if (SetRoleIsActive)
860  return OuterUserId;
861  else
862  return InvalidOid;
863 }
static Oid OuterUserId
Definition: miscinit.c:474
static bool SetRoleIsActive
Definition: miscinit.c:484
#define InvalidOid
Definition: postgres_ext.h:36

References InvalidOid, OuterUserId, and SetRoleIsActive.

Referenced by InitializeParallelDSM(), and show_role().

◆ GetOuterUserId()

Oid GetOuterUserId ( void  )

Definition at line 503 of file miscinit.c.

504 {
506  return OuterUserId;
507 }

References AssertState, OidIsValid, and OuterUserId.

Referenced by DropRole(), and RenameRole().

◆ GetSessionUserId()

Oid GetSessionUserId ( void  )

Definition at line 526 of file miscinit.c.

527 {
529  return SessionUserId;
530 }
static Oid SessionUserId
Definition: miscinit.c:473

References AssertState, OidIsValid, and SessionUserId.

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

◆ GetUserId()

Oid GetUserId ( void  )

Definition at line 492 of file miscinit.c.

493 {
495  return CurrentUserId;
496 }
static Oid CurrentUserId
Definition: miscinit.c:475

References AssertState, CurrentUserId, and OidIsValid.

Referenced by AddRoleMems(), AggregateCreate(), AlterCollation(), AlterDatabase(), AlterDatabaseOwner(), AlterDatabaseRefreshColl(), AlterDatabaseSet(), AlterEventTrigger(), AlterEventTriggerOwner_internal(), AlterExtensionNamespace(), AlterForeignServer(), AlterForeignServerOwner_internal(), AlterFunction(), AlterObjectNamespace_internal(), AlterObjectOwner_internal(), AlterObjectRename_internal(), AlterOperator(), AlterOpFamilyAdd(), AlterPublication(), AlterPublicationOwner_internal(), AlterRole(), AlterRoleSet(), AlterSchemaOwner_internal(), AlterStatistics(), AlterSubscription(), AlterSubscriptionOwner_internal(), AlterSystemSetConfigFile(), AlterTableMoveAll(), AlterTableSpaceOptions(), AlterTSConfiguration(), AlterTSDictionary(), AlterType(), AlterTypeNamespace_oid(), AlterTypeOwner(), ATExecAddColumn(), ATExecChangeOwner(), ATPrepAlterColumnType(), ATPrepSetTableSpace(), ATSimplePermissions(), bbsink_server_new(), be_lo_put(), be_lo_unlink(), binary_upgrade_create_empty_extension(), brin_desummarize_range(), BuildCachedPlan(), BuildDescForRelation(), BuildIndexValueDescription(), calculate_database_size(), calculate_tablespace_size(), call_pltcl_start_proc(), check_enable_rls(), check_temp_tablespaces(), CheckCachedPlan(), checkDomainOwner(), checkEnumOwner(), checkFkeyPermissions(), CheckFunctionValidatorAccess(), CheckMyDatabase(), CheckSlotPermissions(), CommentObject(), compile_plperl_function(), compile_pltcl_function(), CompleteCachedPlan(), compute_return_type(), convert_and_check_filename(), create_foreign_modify(), CreateCast(), CreateConversionCommand(), createdb(), CreateEventTrigger(), CreateExtensionInternal(), CreateForeignDataWrapper(), CreateForeignServer(), CreateForeignTable(), CreateFunction(), CreateOpFamily(), CreateProceduralLanguage(), CreatePublication(), CreateRole(), CreateStatistics(), CreateSubscription(), CreateTableSpace(), CreateTransform(), CreateTriggerFiringOn(), current_user(), currtid_internal(), currval_oid(), DefineAggregate(), DefineCollation(), DefineDomain(), DefineEnum(), DefineIndex(), DefineOpClass(), DefineOperator(), DefineOpFamily(), DefineQueryRewrite(), DefineRange(), DefineRelation(), DefineTSConfiguration(), DefineTSDictionary(), DefineType(), DelRoleMems(), do_setval(), DoCopy(), dropdb(), DropOwnedObjects(), DropRole(), DropSubscription(), DropTableSpace(), emit_audit_message(), EnableDisableRule(), examine_simple_variable(), examine_variable(), ExecAlterDefaultPrivilegesStmt(), ExecAlterExtensionContentsStmt(), ExecAlterExtensionStmt(), ExecAlterObjectDependsStmt(), ExecBuildGroupingEqual(), ExecBuildParamSetEqual(), ExecBuildSlotPartitionKeyDescription(), ExecBuildSlotValueDescription(), ExecCheckRTEPerms(), ExecGrant_Attribute(), ExecGrant_Database(), ExecGrant_Fdw(), ExecGrant_ForeignServer(), ExecGrant_Function(), ExecGrant_Language(), ExecGrant_Largeobject(), ExecGrant_Namespace(), ExecGrant_Parameter(), ExecGrant_Relation(), ExecGrant_Tablespace(), ExecGrant_Type(), ExecInitAgg(), ExecInitExprRec(), ExecInitFunc(), ExecInitWindowAgg(), ExecReindex(), ExecSecLabelStmt(), execute_extension_script(), ExecuteCallStmt(), ExecuteDoStmt(), ExecuteGrantStmt(), ExecuteTruncateGuts(), extension_is_trusted(), file_fdw_validator(), findRangeCanonicalFunction(), findRangeSubtypeDiffFunction(), FinishPreparedTransaction(), get_connect_string(), get_explain_guc_options(), get_other_operator(), get_rel_from_relname(), get_rolespec_oid(), get_rolespec_tuple(), get_row_security_policies(), get_tables_to_cluster(), get_tables_to_cluster_partitioned(), GetConfigOption(), GetConfigOptionByName(), GetConfigOptionByNum(), GetConfigOptionResetString(), gin_clean_pending_list(), GrantRole(), HandleFunctionRequest(), has_any_column_privilege_id(), has_any_column_privilege_name(), has_column_privilege_id_attnum(), has_column_privilege_id_name(), has_column_privilege_name_attnum(), has_column_privilege_name_name(), has_database_privilege_id(), has_database_privilege_name(), has_foreign_data_wrapper_privilege_id(), has_foreign_data_wrapper_privilege_name(), has_function_privilege_id(), has_function_privilege_name(), has_language_privilege_id(), has_language_privilege_name(), has_parameter_privilege_name(), has_schema_privilege_id(), has_schema_privilege_name(), has_sequence_privilege_id(), has_sequence_privilege_name(), has_server_privilege_id(), has_server_privilege_name(), has_table_privilege_id(), has_table_privilege_name(), has_tablespace_privilege_id(), has_tablespace_privilege_name(), has_type_privilege_id(), has_type_privilege_name(), have_createdb_privilege(), have_createrole_privilege(), heap_force_common(), ImportForeignSchema(), init_sexpr(), InitializeSearchPath(), InitPostgres(), InitTempTableNamespace(), inline_function(), inline_set_returning_function(), insert_username(), interpret_function_parameter_list(), inv_create(), inv_open(), LargeObjectCreate(), lastval(), LockViewRecurse(), LogicalRepSyncTableStart(), lookup_agg_function(), LookupCreationNamespace(), LookupExplicitNamespace(), MergeAttributes(), movedb(), nextval_internal(), OperatorCreate(), OperatorShellMake(), pg_has_role_id(), pg_has_role_name(), pg_import_system_collations(), pg_prewarm(), pg_sequence_last_value(), pg_sequence_parameters(), pg_signal_backend(), pg_stat_get_wal_receiver(), pg_stat_get_wal_senders(), pg_stat_statements_internal(), pgrowlocks(), pgss_store(), pgstat_get_backend_current_activity(), pltcl_fetch_interp(), postgresBeginDirectModify(), postgresBeginForeignScan(), postgresExecForeignTruncate(), postgresGetForeignRelSize(), postgresImportForeignSchema(), PrepareTempTablespaces(), PrepareTransaction(), PublicationAddTables(), RangeVarCallbackForAlterRelation(), RangeVarCallbackForDropRelation(), RangeVarCallbackForLockTable(), RangeVarCallbackForPolicy(), RangeVarCallbackForReindexIndex(), RangeVarCallbackForRenameRule(), RangeVarCallbackForRenameTrigger(), RangeVarCallbackOwnsRelation(), RangeVarCallbackOwnsTable(), RangeVarGetAndCheckCreationNamespace(), ReassignOwnedObjects(), recomputeNamespacePath(), REGRESS_exec_check_perms(), REGRESS_object_access_hook(), REGRESS_object_access_hook_str(), REGRESS_utility_command(), ReindexMultipleInternal(), ReindexMultipleTables(), RemoveObjects(), renameatt_check(), RenameDatabase(), RenameSchema(), RenameTableSpace(), RenameType(), RevalidateCachedQuery(), RI_Initial_Check(), ri_ReportViolation(), select_perl_context(), set_config_option(), set_foreign_rel_properties(), shell_check_detail(), ShowAllGUCConfig(), standard_ProcessUtility(), statext_is_compatible_clause(), superuser(), TargetPrivilegesCheck(), TerminateOtherDBBackends(), transformTableLikeClause(), truncate_check_perms(), user_mapping_ddl_aclcheck(), vacuum_is_relation_owner(), ValidateJoinEstimator(), and ValidateRestrictionEstimator().

◆ GetUserIdAndContext()

void GetUserIdAndContext ( Oid userid,
bool sec_def_context 
)

Definition at line 652 of file miscinit.c.

653 {
654  *userid = CurrentUserId;
655  *sec_def_context = InLocalUserIdChange();
656 }
bool InLocalUserIdChange(void)
Definition: miscinit.c:621

References CurrentUserId, and InLocalUserIdChange().

◆ GetUserIdAndSecContext()

◆ GetUserNameFromId()

char* GetUserNameFromId ( Oid  roleid,
bool  noerr 
)

Definition at line 913 of file miscinit.c.

914 {
915  HeapTuple tuple;
916  char *result;
917 
918  tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
919  if (!HeapTupleIsValid(tuple))
920  {
921  if (!noerr)
922  ereport(ERROR,
923  (errcode(ERRCODE_UNDEFINED_OBJECT),
924  errmsg("invalid role OID: %u", roleid)));
925  result = NULL;
926  }
927  else
928  {
929  result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
930  ReleaseSysCache(tuple);
931  }
932  return result;
933 }
#define NameStr(name)
Definition: c.h:681
#define ERROR
Definition: elog.h:33
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:649
NameData rolname
Definition: pg_authid.h:34
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:56
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1221
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1173
@ AUTHOID
Definition: syscache.h:45

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

Referenced by check_is_member_of_role(), current_user(), execute_extension_script(), getObjectDescription(), getObjectIdentityParts(), insert_username(), LogicalRepSyncTableStart(), regroleout(), session_user(), and TargetPrivilegesCheck().

◆ has_rolreplication()

bool has_rolreplication ( Oid  roleid)

Definition at line 679 of file miscinit.c.

680 {
681  bool result = false;
682  HeapTuple utup;
683 
684  utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
685  if (HeapTupleIsValid(utup))
686  {
687  result = ((Form_pg_authid) GETSTRUCT(utup))->rolreplication;
688  ReleaseSysCache(utup);
689  }
690  return result;
691 }
bool rolreplication
Definition: pg_authid.h:40

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

Referenced by CheckSlotPermissions(), and InitPostgres().

◆ InitializeSessionUserId()

void InitializeSessionUserId ( const char *  rolename,
Oid  roleid 
)

Definition at line 697 of file miscinit.c.

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

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

Referenced by InitPostgres().

◆ InitializeSessionUserIdStandalone()

void InitializeSessionUserIdStandalone ( void  )

Definition at line 800 of file miscinit.c.

801 {
802  /*
803  * This function should only be called in single-user mode, in autovacuum
804  * workers, and in background workers.
805  */
807 
808  /* call only once */
810 
811  AuthenticatedUserId = BOOTSTRAP_SUPERUSERID;
813 
814  SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
815 }
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3309
bool IsBackgroundWorker
Definition: globals.c:115

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

Referenced by InitPostgres().

◆ InitPostmasterChild()

void InitPostmasterChild ( void  )

Definition at line 95 of file miscinit.c.

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

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

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

◆ InitStandaloneProcess()

void InitStandaloneProcess ( const char *  argv0)

Definition at line 175 of file miscinit.c.

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

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

Referenced by BootstrapModeMain(), and PostgresSingleUserMain().

◆ InLocalUserIdChange()

bool InLocalUserIdChange ( void  )

Definition at line 621 of file miscinit.c.

622 {
624 }
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:312

References SECURITY_LOCAL_USERID_CHANGE, and SecurityRestrictionContext.

Referenced by GetUserIdAndContext(), and set_config_option().

◆ InNoForceRLSOperation()

bool InNoForceRLSOperation ( void  )

Definition at line 639 of file miscinit.c.

640 {
642 }
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:314

References SECURITY_NOFORCE_RLS, and SecurityRestrictionContext.

Referenced by check_enable_rls().

◆ InSecurityRestrictedOperation()

bool InSecurityRestrictedOperation ( void  )

◆ load_libraries()

static void load_libraries ( const char *  libraries,
const char *  gucname,
bool  restricted 
)
static

Definition at line 1631 of file miscinit.c.

1632 {
1633  char *rawstring;
1634  List *elemlist;
1635  ListCell *l;
1636 
1637  if (libraries == NULL || libraries[0] == '\0')
1638  return; /* nothing to do */
1639 
1640  /* Need a modifiable copy of string */
1641  rawstring = pstrdup(libraries);
1642 
1643  /* Parse string into list of filename paths */
1644  if (!SplitDirectoriesString(rawstring, ',', &elemlist))
1645  {
1646  /* syntax error in list */
1647  list_free_deep(elemlist);
1648  pfree(rawstring);
1649  ereport(LOG,
1650  (errcode(ERRCODE_SYNTAX_ERROR),
1651  errmsg("invalid list syntax in parameter \"%s\"",
1652  gucname)));
1653  return;
1654  }
1655 
1656  foreach(l, elemlist)
1657  {
1658  /* Note that filename was already canonicalized */
1659  char *filename = (char *) lfirst(l);
1660  char *expanded = NULL;
1661 
1662  /* If restricting, insert $libdir/plugins if not mentioned already */
1663  if (restricted && first_dir_separator(filename) == NULL)
1664  {
1665  expanded = psprintf("$libdir/plugins/%s", filename);
1666  filename = expanded;
1667  }
1668  load_file(filename, restricted);
1669  ereport(DEBUG1,
1670  (errmsg_internal("loaded library \"%s\"", filename)));
1671  if (expanded)
1672  pfree(expanded);
1673  }
1674 
1675  list_free_deep(elemlist);
1676  pfree(rawstring);
1677 }
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:144
int errmsg_internal(const char *fmt,...)
Definition: elog.c:991
#define DEBUG1
Definition: elog.h:24
void list_free_deep(List *list)
Definition: list.c:1519
void pfree(void *pointer)
Definition: mcxt.c:1175
#define lfirst(lc)
Definition: pg_list.h:169
char * first_dir_separator(const char *filename)
Definition: path.c:104
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
Definition: pg_list.h:51
bool SplitDirectoriesString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3842

References DEBUG1, ereport, errcode(), errmsg(), errmsg_internal(), filename, first_dir_separator(), lfirst, list_free_deep(), load_file(), LOG, pfree(), psprintf(), pstrdup(), and SplitDirectoriesString().

Referenced by process_session_preload_libraries(), and process_shared_preload_libraries().

◆ pg_bindtextdomain()

void pg_bindtextdomain ( const char *  domain)

Definition at line 1720 of file miscinit.c.

1721 {
1722 #ifdef ENABLE_NLS
1723  if (my_exec_path[0] != '\0')
1724  {
1725  char locale_path[MAXPGPATH];
1726 
1727  get_locale_path(my_exec_path, locale_path);
1728  bindtextdomain(domain, locale_path);
1729  pg_bind_textdomain_codeset(domain);
1730  }
1731 #endif
1732 }
void get_locale_path(const char *my_exec_path, char *ret_path)
Definition: path.c:888

References get_locale_path(), MAXPGPATH, and my_exec_path.

Referenced by _PG_init().

◆ process_session_preload_libraries()

void process_session_preload_libraries ( void  )

Definition at line 1697 of file miscinit.c.

1698 {
1700  "session_preload_libraries",
1701  false);
1703  "local_preload_libraries",
1704  true);
1705 }
char * session_preload_libraries_string
Definition: miscinit.c:1613
char * local_preload_libraries_string
Definition: miscinit.c:1615
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1631

References load_libraries(), local_preload_libraries_string, and session_preload_libraries_string.

Referenced by PostgresMain().

◆ process_shared_preload_libraries()

void process_shared_preload_libraries ( void  )

Definition at line 1683 of file miscinit.c.

1684 {
1687  "shared_preload_libraries",
1688  false);
1691 }
bool process_shared_preload_libraries_done
Definition: miscinit.c:1619
char * shared_preload_libraries_string
Definition: miscinit.c:1614
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1618

References load_libraries(), process_shared_preload_libraries_done, process_shared_preload_libraries_in_progress, and shared_preload_libraries_string.

Referenced by PostmasterMain().

◆ process_shmem_requests()

void process_shmem_requests ( void  )

Definition at line 1711 of file miscinit.c.

1712 {
1714  if (shmem_request_hook)
1717 }
bool process_shmem_requests_in_progress
Definition: miscinit.c:1622
shmem_request_hook_type shmem_request_hook
Definition: miscinit.c:1621

References process_shmem_requests_in_progress, and shmem_request_hook.

Referenced by PostmasterMain().

◆ RecheckDataDirLockFile()

bool RecheckDataDirLockFile ( void  )

Definition at line 1478 of file miscinit.c.

1479 {
1480  int fd;
1481  int len;
1482  long file_pid;
1483  char buffer[BLCKSZ];
1484 
1485  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1486  if (fd < 0)
1487  {
1488  /*
1489  * There are many foreseeable false-positive error conditions. For
1490  * safety, fail only on enumerated clearly-something-is-wrong
1491  * conditions.
1492  */
1493  switch (errno)
1494  {
1495  case ENOENT:
1496  case ENOTDIR:
1497  /* disaster */
1498  ereport(LOG,
1500  errmsg("could not open file \"%s\": %m",
1502  return false;
1503  default:
1504  /* non-fatal, at least for now */
1505  ereport(LOG,
1507  errmsg("could not open file \"%s\": %m; continuing anyway",
1509  return true;
1510  }
1511  }
1513  len = read(fd, buffer, sizeof(buffer) - 1);
1515  if (len < 0)
1516  {
1517  ereport(LOG,
1519  errmsg("could not read from file \"%s\": %m",
1521  close(fd);
1522  return true; /* treat read failure as nonfatal */
1523  }
1524  buffer[len] = '\0';
1525  close(fd);
1526  file_pid = atol(buffer);
1527  if (file_pid == getpid())
1528  return true; /* all is well */
1529 
1530  /* Trouble: someone's overwritten the lock file */
1531  ereport(LOG,
1532  (errmsg("lock file \"%s\" contains wrong PID: %ld instead of %ld",
1533  DIRECTORY_LOCK_FILE, file_pid, (long) getpid())));
1534  return false;
1535 }
@ WAIT_EVENT_LOCK_FILE_RECHECKDATADIR_READ
Definition: wait_event.h:188

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

Referenced by ServerLoop().

◆ SetCurrentRoleId()

void SetCurrentRoleId ( Oid  roleid,
bool  is_superuser 
)

Definition at line 878 of file miscinit.c.

879 {
880  /*
881  * Get correct info if it's SET ROLE NONE
882  *
883  * If SessionUserId hasn't been set yet, just do nothing --- the eventual
884  * SetSessionUserId call will fix everything. This is needed since we
885  * will get called during GUC initialization.
886  */
887  if (!OidIsValid(roleid))
888  {
890  return;
891 
892  roleid = SessionUserId;
894 
895  SetRoleIsActive = false;
896  }
897  else
898  SetRoleIsActive = true;
899 
900  SetOuterUserId(roleid);
901 
902  SetConfigOption("is_superuser",
903  is_superuser ? "on" : "off",
905 }
static void SetOuterUserId(Oid userid)
Definition: miscinit.c:511
static bool SessionUserIsSuperuser
Definition: miscinit.c:479
static bool is_superuser(Archive *fout)
Definition: pg_dump.c:4378

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

Referenced by assign_role(), and ParallelWorkerMain().

◆ SetDatabasePath()

void SetDatabasePath ( const char *  path)

Definition at line 305 of file miscinit.c.

306 {
307  /* This should happen only once per process */
310 }
char * DatabasePath
Definition: globals.c:97
MemoryContext TopMemoryContext
Definition: mcxt.c:48
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1292

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

Referenced by InitPostgres().

◆ SetDataDir()

void SetDataDir ( const char *  dir)

Definition at line 411 of file miscinit.c.

412 {
413  char *new;
414 
415  AssertArg(dir);
416 
417  /* If presented path is relative, convert to absolute */
418  new = make_absolute_path(dir);
419 
420  if (DataDir)
421  free(DataDir);
422  DataDir = new;
423 }
#define AssertArg(condition)
Definition: c.h:806
#define free(a)
Definition: header.h:65
char * make_absolute_path(const char *path)
Definition: path.c:729

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

Referenced by SelectConfigFiles().

◆ SetOuterUserId()

static void SetOuterUserId ( Oid  userid)
static

Definition at line 511 of file miscinit.c.

512 {
514  AssertArg(OidIsValid(userid));
515  OuterUserId = userid;
516 
517  /* We force the effective user ID to match, too */
518  CurrentUserId = userid;
519 }

References AssertArg, AssertState, CurrentUserId, OidIsValid, OuterUserId, and SecurityRestrictionContext.

Referenced by SetCurrentRoleId().

◆ SetSessionAuthorization()

void SetSessionAuthorization ( Oid  userid,
bool  is_superuser 
)

Definition at line 832 of file miscinit.c.

833 {
834  /* Must have authenticated already, else can't make permission check */
836 
837  if (userid != AuthenticatedUserId &&
839  ereport(ERROR,
840  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
841  errmsg("permission denied to set session authorization")));
842 
844 
845  SetConfigOption("is_superuser",
846  is_superuser ? "on" : "off",
848 }

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

Referenced by assign_session_authorization().

◆ SetSessionUserId()

static void SetSessionUserId ( Oid  userid,
bool  is_superuser 
)
static

Definition at line 534 of file miscinit.c.

535 {
537  AssertArg(OidIsValid(userid));
538  SessionUserId = userid;
540  SetRoleIsActive = false;
541 
542  /* We force the effective user IDs to match, too */
543  OuterUserId = userid;
544  CurrentUserId = userid;
545 }

References AssertArg, AssertState, CurrentUserId, is_superuser(), OidIsValid, OuterUserId, SecurityRestrictionContext, SessionUserId, SessionUserIsSuperuser, and SetRoleIsActive.

Referenced by InitializeSessionUserId(), InitializeSessionUserIdStandalone(), and SetSessionAuthorization().

◆ SetUserIdAndContext()

void SetUserIdAndContext ( Oid  userid,
bool  sec_def_context 
)

Definition at line 659 of file miscinit.c.

660 {
661  /* We throw the same error SET ROLE would. */
663  ereport(ERROR,
664  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
665  errmsg("cannot set parameter \"%s\" within security-restricted operation",
666  "role")));
667  CurrentUserId = userid;
668  if (sec_def_context)
670  else
672 }
bool InSecurityRestrictedOperation(void)
Definition: miscinit.c:630

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

◆ SetUserIdAndSecContext()

◆ SwitchBackToLocalLatch()

void SwitchBackToLocalLatch ( void  )

Definition at line 234 of file miscinit.c.

235 {
237  Assert(MyProc != NULL && MyLatch == &MyProc->procLatch);
238 
240 
241  if (FeBeWaitSet)
243  MyLatch);
244 
245  SetLatch(MyLatch);
246 }
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:947
void SetLatch(Latch *latch)
Definition: latch.c:566
#define WL_LATCH_SET
Definition: latch.h:125
#define FeBeWaitSetLatchPos
Definition: libpq.h:64
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:168
Latch procLatch
Definition: proc.h:168

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

Referenced by AuxiliaryProcKill(), and ProcKill().

◆ SwitchToSharedLatch()

void SwitchToSharedLatch ( void  )

Definition at line 214 of file miscinit.c.

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

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

Referenced by InitAuxiliaryProcess(), and InitProcess().

◆ TouchSocketLockFiles()

void TouchSocketLockFiles ( void  )

Definition at line 1322 of file miscinit.c.

1323 {
1324  ListCell *l;
1325 
1326  foreach(l, lock_files)
1327  {
1328  char *socketLockFile = (char *) lfirst(l);
1329 
1330  /* No need to touch the data directory lock file, we trust */
1331  if (strcmp(socketLockFile, DIRECTORY_LOCK_FILE) == 0)
1332  continue;
1333 
1334  /* we just ignore any error here */
1335  (void) utime(socketLockFile, NULL);
1336  }
1337 }

References DIRECTORY_LOCK_FILE, lfirst, and lock_files.

Referenced by ServerLoop().

◆ UnlinkLockFiles()

static void UnlinkLockFiles ( int  status,
Datum  arg 
)
static

Definition at line 955 of file miscinit.c.

956 {
957  ListCell *l;
958 
959  foreach(l, lock_files)
960  {
961  char *curfile = (char *) lfirst(l);
962 
963  unlink(curfile);
964  /* Should we complain if the unlink fails? */
965  }
966  /* Since we're about to exit, no need to reclaim storage */
967  lock_files = NIL;
968 
969  /*
970  * Lock file removal should always be the last externally visible action
971  * of a postmaster or standalone backend, while we won't come here at all
972  * when exiting postmaster child processes. Therefore, this is a good
973  * place to log completion of shutdown. We could alternatively teach
974  * proc_exit() to do it, but that seems uglier. In a standalone backend,
975  * use NOTICE elevel to be less chatty.
976  */
978  (errmsg("database system is shut down")));
979 }
#define NOTICE
Definition: elog.h:29

References ereport, errmsg(), IsPostmasterEnvironment, lfirst, lock_files, LOG, NIL, and NOTICE.

Referenced by CreateLockFile().

◆ ValidatePgVersion()

void ValidatePgVersion ( const char *  path)

Definition at line 1550 of file miscinit.c.

1551 {
1552  char full_path[MAXPGPATH];
1553  FILE *file;
1554  int ret;
1555  long file_major;
1556  long my_major;
1557  char *endptr;
1558  char file_version_string[64];
1559  const char *my_version_string = PG_VERSION;
1560 
1561  my_major = strtol(my_version_string, &endptr, 10);
1562 
1563  snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
1564 
1565  file = AllocateFile(full_path, "r");
1566  if (!file)
1567  {
1568  if (errno == ENOENT)
1569  ereport(FATAL,
1570  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1571  errmsg("\"%s\" is not a valid data directory",
1572  path),
1573  errdetail("File \"%s\" is missing.", full_path)));
1574  else
1575  ereport(FATAL,
1577  errmsg("could not open file \"%s\": %m", full_path)));
1578  }
1579 
1580  file_version_string[0] = '\0';
1581  ret = fscanf(file, "%63s", file_version_string);
1582  file_major = strtol(file_version_string, &endptr, 10);
1583 
1584  if (ret != 1 || endptr == file_version_string)
1585  ereport(FATAL,
1586  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1587  errmsg("\"%s\" is not a valid data directory",
1588  path),
1589  errdetail("File \"%s\" does not contain valid data.",
1590  full_path),
1591  errhint("You might need to initdb.")));
1592 
1593  FreeFile(file);
1594 
1595  if (my_major != file_major)
1596  ereport(FATAL,
1597  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1598  errmsg("database files are incompatible with server"),
1599  errdetail("The data directory was initialized by PostgreSQL version %s, "
1600  "which is not compatible with this version %s.",
1601  file_version_string, my_version_string)));
1602 }
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2461
int FreeFile(FILE *file)
Definition: fd.c:2660

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

Referenced by checkDataDir(), and InitPostgres().

Variable Documentation

◆ AuthenticatedUserId

◆ AuthenticatedUserIsSuperuser

bool AuthenticatedUserIsSuperuser = false
static

◆ CurrentUserId

◆ IgnoreSystemIndexes

◆ local_preload_libraries_string

char* local_preload_libraries_string = NULL

Definition at line 1615 of file miscinit.c.

Referenced by process_session_preload_libraries().

◆ LocalLatchData

Latch LocalLatchData
static

◆ lock_files

List* lock_files = NIL
static

Definition at line 66 of file miscinit.c.

Referenced by CreateLockFile(), TouchSocketLockFiles(), and UnlinkLockFiles().

◆ Mode

Definition at line 61 of file miscinit.c.

◆ MyBackendType

◆ OuterUserId

Oid OuterUserId = InvalidOid
static

Definition at line 474 of file miscinit.c.

Referenced by GetCurrentRoleId(), GetOuterUserId(), SetOuterUserId(), and SetSessionUserId().

◆ process_shared_preload_libraries_done

bool process_shared_preload_libraries_done = false

◆ process_shared_preload_libraries_in_progress

bool process_shared_preload_libraries_in_progress = false

◆ process_shmem_requests_in_progress

bool process_shmem_requests_in_progress = false

◆ SecurityRestrictionContext

◆ session_preload_libraries_string

char* session_preload_libraries_string = NULL

Definition at line 1613 of file miscinit.c.

Referenced by process_session_preload_libraries().

◆ SessionUserId

Oid SessionUserId = InvalidOid
static

Definition at line 473 of file miscinit.c.

Referenced by GetSessionUserId(), SetCurrentRoleId(), and SetSessionUserId().

◆ SessionUserIsSuperuser

bool SessionUserIsSuperuser = false
static

Definition at line 479 of file miscinit.c.

Referenced by SetCurrentRoleId(), and SetSessionUserId().

◆ SetRoleIsActive

bool SetRoleIsActive = false
static

Definition at line 484 of file miscinit.c.

Referenced by GetCurrentRoleId(), SetCurrentRoleId(), and SetSessionUserId().

◆ shared_preload_libraries_string

char* shared_preload_libraries_string = NULL

Definition at line 1614 of file miscinit.c.

Referenced by process_shared_preload_libraries().

◆ shmem_request_hook

shmem_request_hook_type shmem_request_hook = NULL

Definition at line 1621 of file miscinit.c.

Referenced by _PG_init(), and process_shmem_requests().