]> granicus.if.org Git - postgresql/blobdiff - src/backend/utils/init/miscinit.c
Repair some REINDEX problems per recent discussions. The relcache is
[postgresql] / src / backend / utils / init / miscinit.c
index 0ccbe753d0670497a519ede7f5ecab0f4ab0f00b..22baac3706f6e4f2ae21afdda46578235509386f 100644 (file)
@@ -3,44 +3,45 @@
  * miscinit.c
  *       miscellaneous initialization support stuff
  *
- * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
  * Portions Copyright (c) 1994, Regents of the University of California
  *
  *
  * IDENTIFICATION
- *       $Header: /cvsroot/pgsql/src/backend/utils/init/miscinit.c,v 1.83 2002/03/01 22:45:15 petere Exp $
+ *       $Header: /cvsroot/pgsql/src/backend/utils/init/miscinit.c,v 1.114 2003/09/24 18:54:01 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
 #include "postgres.h"
 
 #include <sys/param.h>
-#include <sys/types.h>
 #include <signal.h>
-#include <sys/stat.h>
 #include <sys/file.h>
+#include <sys/stat.h>
+#include <sys/time.h>
 #include <fcntl.h>
 #include <unistd.h>
 #include <grp.h>
 #include <pwd.h>
-#include <stdlib.h>
 #include <errno.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#ifdef HAVE_UTIME_H
+#include <utime.h>
+#endif
 
 #include "catalog/catname.h"
 #include "catalog/pg_shadow.h"
 #include "libpq/libpq-be.h"
 #include "miscadmin.h"
+#include "storage/ipc.h"
+#include "storage/pg_shmem.h"
 #include "utils/builtins.h"
 #include "utils/guc.h"
 #include "utils/lsyscache.h"
 #include "utils/syscache.h"
 
 
-#ifdef CYR_RECODE
-unsigned char RecodeForwTable[128];
-unsigned char RecodeBackTable[128];
-#endif
-
 ProcessingMode Mode = InitProcessing;
 
 /* Note: we rely on these to initialize as zeroes */
@@ -50,6 +51,11 @@ static char socketLockFile[MAXPGPATH];
 
 /* ----------------------------------------------------------------
  *             ignoring system indexes support stuff
+ *
+ * NOTE: "ignoring system indexes" means we do not use the system indexes
+ * for lookups (either in hardwired catalog accesses or in planner-generated
+ * plans).  We do, however, still update the indexes when a catalog
+ * modification is made.
  * ----------------------------------------------------------------
  */
 
@@ -60,15 +66,14 @@ static bool isIgnoringSystemIndexes = false;
  *             True if ignoring system indexes.
  */
 bool
-IsIgnoringSystemIndexes()
+IsIgnoringSystemIndexes(void)
 {
        return isIgnoringSystemIndexes;
 }
 
 /*
  * IgnoreSystemIndexes
- *     Set true or false whether PostgreSQL ignores system indexes.
- *
+ *             Set true or false whether PostgreSQL ignores system indexes.
  */
 void
 IgnoreSystemIndexes(bool mode)
@@ -76,6 +81,53 @@ IgnoreSystemIndexes(bool mode)
        isIgnoringSystemIndexes = mode;
 }
 
+/* ----------------------------------------------------------------
+ *             system index reindexing support
+ *
+ * When we are busy reindexing a system index, this code provides support
+ * for preventing catalog lookups from using that index.
+ * ----------------------------------------------------------------
+ */
+
+static Oid     currentlyReindexedHeap = InvalidOid;
+static Oid     currentlyReindexedIndex = InvalidOid;
+
+/*
+ * ReindexIsProcessingHeap
+ *             True if heap specified by OID is currently being reindexed.
+ */
+bool
+ReindexIsProcessingHeap(Oid heapOid)
+{
+       return heapOid == currentlyReindexedHeap;
+}
+
+/*
+ * ReindexIsProcessingIndex
+ *             True if index specified by OID is currently being reindexed.
+ */
+bool
+ReindexIsProcessingIndex(Oid indexOid)
+{
+       return indexOid == currentlyReindexedIndex;
+}
+
+/*
+ * SetReindexProcessing
+ *             Set flag that specified heap/index are being reindexed.
+ *             Pass InvalidOid to indicate that reindexing is not active.
+ */
+void
+SetReindexProcessing(Oid heapOid, Oid indexOid)
+{
+       /* Args should be both, or neither, InvalidOid */
+       Assert((heapOid == InvalidOid) == (indexOid == InvalidOid));
+       /* Reindexing is not re-entrant. */
+       Assert(indexOid == InvalidOid || currentlyReindexedIndex == InvalidOid);
+       currentlyReindexedHeap = heapOid;
+       currentlyReindexedIndex = indexOid;
+}
+
 /* ----------------------------------------------------------------
  *                             database path / name support stuff
  * ----------------------------------------------------------------
@@ -97,22 +149,6 @@ SetDatabasePath(const char *path)
        }
 }
 
-void
-SetDatabaseName(const char *name)
-{
-       if (DatabaseName)
-       {
-               free(DatabaseName);
-               DatabaseName = NULL;
-       }
-       /* use strdup since this is done before memory contexts are set up */
-       if (name)
-       {
-               DatabaseName = strdup(name);
-               AssertState(DatabaseName);
-       }
-}
-
 /*
  * Set data directory, but make sure it's an absolute path.  Use this,
  * never set DataDir directly.
@@ -121,10 +157,12 @@ void
 SetDataDir(const char *dir)
 {
        char       *new;
+       int                     newlen;
 
        AssertArg(dir);
 
-       if (dir[0] != '/')
+       /* If presented path is relative, convert to absolute */
+       if (!is_absolute_path(dir))
        {
                char       *buf;
                size_t          buflen;
@@ -134,7 +172,9 @@ SetDataDir(const char *dir)
                {
                        buf = malloc(buflen);
                        if (!buf)
-                               elog(FATAL, "out of memory");
+                               ereport(FATAL,
+                                               (errcode(ERRCODE_OUT_OF_MEMORY),
+                                                errmsg("out of memory")));
 
                        if (getcwd(buf, buflen))
                                break;
@@ -147,13 +187,15 @@ SetDataDir(const char *dir)
                        else
                        {
                                free(buf);
-                               elog(FATAL, "cannot get current working directory: %m");
+                               elog(FATAL, "could not get current working directory: %m");
                        }
                }
 
                new = malloc(strlen(buf) + 1 + strlen(dir) + 1);
                if (!new)
-                       elog(FATAL, "out of memory");
+                       ereport(FATAL,
+                                       (errcode(ERRCODE_OUT_OF_MEMORY),
+                                        errmsg("out of memory")));
                sprintf(new, "%s/%s", buf, dir);
                free(buf);
        }
@@ -161,253 +203,61 @@ SetDataDir(const char *dir)
        {
                new = strdup(dir);
                if (!new)
-                       elog(FATAL, "out of memory");
+                       ereport(FATAL,
+                                       (errcode(ERRCODE_OUT_OF_MEMORY),
+                                        errmsg("out of memory")));
        }
 
+       /*
+        * Strip any trailing slash.  Not strictly necessary, but avoids
+        * generating funny-looking paths to individual files.
+        */
+       newlen = strlen(new);
+       if (newlen > 1 && new[newlen - 1] == '/'
+#ifdef WIN32
+               || new[newlen - 1] == '\\'
+#endif
+               )
+               new[newlen - 1] = '\0';
+
        if (DataDir)
                free(DataDir);
        DataDir = new;
 }
 
 
-/* ----------------------------------------------------------------
- *                             MULTIBYTE stub code
- *
- * Even if MULTIBYTE is not enabled, these functions are necessary
- * since pg_proc.h has references to them.
- * ----------------------------------------------------------------
- */
-
-#ifndef MULTIBYTE
-
-Datum
-getdatabaseencoding(PG_FUNCTION_ARGS)
-{
-       return DirectFunctionCall1(namein, CStringGetDatum("SQL_ASCII"));
-}
-
-Datum
-pg_client_encoding(PG_FUNCTION_ARGS)
-{
-       return DirectFunctionCall1(namein, CStringGetDatum("SQL_ASCII"));
-}
-
-Datum
-PG_encoding_to_char(PG_FUNCTION_ARGS)
-{
-       return DirectFunctionCall1(namein, CStringGetDatum("SQL_ASCII"));
-}
-
-Datum
-PG_char_to_encoding(PG_FUNCTION_ARGS)
-{
-       PG_RETURN_INT32(0);
-}
-
-Datum
-pg_convert(PG_FUNCTION_ARGS)
-{
-       elog(ERROR, "convert is not supported. To use convert, you need to enable multibyte capability");
-       return DirectFunctionCall1(textin, CStringGetDatum(""));
-}
-
-Datum
-pg_convert2(PG_FUNCTION_ARGS)
-{
-       elog(ERROR, "convert is not supported. To use convert, you need to enable multibyte capability");
-       return DirectFunctionCall1(textin, CStringGetDatum(""));
-}
-#endif
-
-/* ----------------------------------------------------------------
- *                             CYR_RECODE support
- * ----------------------------------------------------------------
- */
-
-#ifdef CYR_RECODE
-
-#define MAX_TOKEN      80
-
-/*
- * Some standard C libraries, including GNU, have an isblank() function.
- * Others, including Solaris, do not.  So we have our own.
- */
-static bool
-isblank(const char c)
-{
-       return c == ' ' || c == '\t';
-}
-
-
-/*
- *     Grab one token out of fp.  Tokens are strings of non-blank
- *     characters bounded by blank characters, beginning of line, and end
- *     of line.        Blank means space or tab.  Return the token as *buf.
- *     Leave file positioned to character immediately after the token or
- *     EOF, whichever comes first.  If no more tokens on line, return null
- *     string as *buf and position file to beginning of next line or EOF,
- *     whichever comes first.
- */
-static void
-next_token(FILE *fp, char *buf, const int bufsz)
-{
-       int                     c;
-       char       *eb = buf + (bufsz - 1);
-
-       /* Move over initial token-delimiting blanks */
-       while ((c = getc(fp)) != EOF && isblank(c))
-               ;
-
-       if (c != EOF && c != '\n')
-       {
-               /*
-                * build a token in buf of next characters up to EOF, eol, or
-                * blank.  If the token gets too long, we still parse it
-                * correctly, but the excess characters are not stored into *buf.
-                */
-               while (c != EOF && c != '\n' && !isblank(c))
-               {
-                       if (buf < eb)
-                               *buf++ = c;
-                       c = getc(fp);
-               }
-
-               /*
-                * Put back the char right after the token (critical in case it is
-                * eol, since we need to detect end-of-line at next call).
-                */
-               if (c != EOF)
-                       ungetc(c, fp);
-       }
-       *buf = '\0';
-}
-
-
-static void
-read_through_eol(FILE *file)
-{
-       int                     c;
-
-       while ((c = getc(file)) != EOF && c != '\n')
-               ;
-}
-
-
-void
-SetCharSet(void)
-{
-       FILE       *file;
-       char       *p;
-       char       *map_file;
-       char            buf[MAX_TOKEN];
-       int                     i,
-                               c;
-       unsigned char FromChar,
-                               ToChar;
-       char            ChTable[80];
-
-       for (i = 0; i < 128; i++)
-       {
-               RecodeForwTable[i] = i + 128;
-               RecodeBackTable[i] = i + 128;
-       }
-
-       if (IsUnderPostmaster)
-       {
-               GetCharSetByHost(ChTable, MyProcPort->raddr.in.sin_addr.s_addr, DataDir);
-               p = ChTable;
-       }
-       else
-               p = getenv("PG_RECODETABLE");
-
-       if (p && *p != '\0')
-       {
-               map_file = palloc(strlen(DataDir) + strlen(p) + 2);
-               sprintf(map_file, "%s/%s", DataDir, p);
-               file = AllocateFile(map_file, PG_BINARY_R);
-               pfree(map_file);
-               if (file == NULL)
-                       return;
-               while ((c = getc(file)) != EOF)
-               {
-                       if (c == '#')
-                               read_through_eol(file);
-                       else
-                       {
-                               /* Read the FromChar */
-                               ungetc(c, file);
-                               next_token(file, buf, sizeof(buf));
-                               if (buf[0] != '\0')
-                               {
-                                       FromChar = strtoul(buf, 0, 0);
-                                       /* Read the ToChar */
-                                       next_token(file, buf, sizeof(buf));
-                                       if (buf[0] != '\0')
-                                       {
-                                               ToChar = strtoul(buf, 0, 0);
-                                               RecodeForwTable[FromChar - 128] = ToChar;
-                                               RecodeBackTable[ToChar - 128] = FromChar;
-                                               read_through_eol(file);
-                                       }
-                               }
-                       }
-               }
-               FreeFile(file);
-       }
-}
-
-char *
-convertstr(unsigned char *buff, int len, int dest)
-{
-       int                     i;
-       char       *ch = buff;
-
-       for (i = 0; i < len; i++, buff++)
-       {
-               if (*buff > 127)
-               {
-                       if (dest)
-                               *buff = RecodeForwTable[*buff - 128];
-                       else
-                               *buff = RecodeBackTable[*buff - 128];
-               }
-       }
-       return ch;
-}
-#endif
-
-
-
 /* ----------------------------------------------------------------
  *     User ID things
  *
- * The session user is determined at connection start and never
- * changes.  The current user may change when "setuid" functions
+ * The authenticated user is determined at connection start and never
+ * changes.  The session user can be changed only by SET SESSION
+ * AUTHORIZATION.  The current user may change when "setuid" functions
  * are implemented.  Conceptually there is a stack, whose bottom
  * is the session user.  You are yourself responsible to save and
  * restore the current user id if you need to change it.
  * ----------------------------------------------------------------
  */
-static Oid     CurrentUserId = InvalidOid;
-static Oid     SessionUserId = InvalidOid;
+static AclId AuthenticatedUserId = 0;
+static AclId SessionUserId = 0;
+static AclId CurrentUserId = 0;
 
 static bool AuthenticatedUserIsSuperuser = false;
 
 /*
  * This function is relevant for all privilege checks.
  */
-Oid
+AclId
 GetUserId(void)
 {
-       AssertState(OidIsValid(CurrentUserId));
+       AssertState(AclIdIsValid(CurrentUserId));
        return CurrentUserId;
 }
 
 
 void
-SetUserId(Oid newid)
+SetUserId(AclId newid)
 {
-       AssertArg(OidIsValid(newid));
+       AssertArg(AclIdIsValid(newid));
        CurrentUserId = newid;
 }
 
@@ -415,21 +265,21 @@ SetUserId(Oid newid)
 /*
  * This value is only relevant for informational purposes.
  */
-Oid
+AclId
 GetSessionUserId(void)
 {
-       AssertState(OidIsValid(SessionUserId));
+       AssertState(AclIdIsValid(SessionUserId));
        return SessionUserId;
 }
 
 
 void
-SetSessionUserId(Oid newid)
+SetSessionUserId(AclId newid)
 {
-       AssertArg(OidIsValid(newid));
+       AssertArg(AclIdIsValid(newid));
        SessionUserId = newid;
        /* Current user defaults to session user. */
-       if (!OidIsValid(CurrentUserId))
+       if (!AclIdIsValid(CurrentUserId))
                CurrentUserId = newid;
 }
 
@@ -440,6 +290,7 @@ InitializeSessionUserId(const char *username)
        HeapTuple       userTup;
        Datum           datum;
        bool            isnull;
+       AclId           usesysid;
 
        /*
         * Don't do scans if we're bootstrapping, none of the system catalogs
@@ -448,30 +299,41 @@ InitializeSessionUserId(const char *username)
        AssertState(!IsBootstrapProcessingMode());
 
        /* call only once */
-       AssertState(!OidIsValid(SessionUserId));
+       AssertState(!OidIsValid(AuthenticatedUserId));
 
        userTup = SearchSysCache(SHADOWNAME,
                                                         PointerGetDatum(username),
                                                         0, 0, 0);
        if (!HeapTupleIsValid(userTup))
-               elog(FATAL, "user \"%s\" does not exist", username);
+               ereport(FATAL,
+                               (errcode(ERRCODE_UNDEFINED_OBJECT),
+                                errmsg("user \"%s\" does not exist", username)));
 
-       SetSessionUserId(((Form_pg_shadow) GETSTRUCT(userTup))->usesysid);
+       usesysid = ((Form_pg_shadow) GETSTRUCT(userTup))->usesysid;
 
+       AuthenticatedUserId = usesysid;
        AuthenticatedUserIsSuperuser = ((Form_pg_shadow) GETSTRUCT(userTup))->usesuper;
 
+       SetSessionUserId(usesysid); /* sets CurrentUserId too */
+
+       /* Record username and superuser status as GUC settings too */
+       SetConfigOption("session_authorization", username,
+                                       PGC_BACKEND, PGC_S_OVERRIDE);
+       SetConfigOption("is_superuser",
+                                       AuthenticatedUserIsSuperuser ? "on" : "off",
+                                       PGC_INTERNAL, PGC_S_OVERRIDE);
+
        /*
-        * Set up user-specific configuration variables.  This is a good
-        * place to do it so we don't have to read pg_shadow twice during
-        * session startup.
+        * Set up user-specific configuration variables.  This is a good place
+        * to do it so we don't have to read pg_shadow twice during session
+        * startup.
         */
        datum = SysCacheGetAttr(SHADOWNAME, userTup,
                                                        Anum_pg_shadow_useconfig, &isnull);
        if (!isnull)
        {
-               ArrayType *a;
+               ArrayType  *a = DatumGetArrayTypeP(datum);
 
-               a = (ArrayType *) pg_detoast_datum((struct varlena *)datum);
                ProcessGUCArray(a, PGC_S_USER);
        }
 
@@ -486,28 +348,41 @@ InitializeSessionUserIdStandalone(void)
        AssertState(!IsUnderPostmaster);
 
        /* call only once */
-       AssertState(!OidIsValid(SessionUserId));
+       AssertState(!OidIsValid(AuthenticatedUserId));
 
-       SetSessionUserId(BOOTSTRAP_USESYSID);
+       AuthenticatedUserId = BOOTSTRAP_USESYSID;
        AuthenticatedUserIsSuperuser = true;
+
+       SetSessionUserId(BOOTSTRAP_USESYSID);
 }
 
 
 /*
  * Change session auth ID while running
+ *
+ * Only a superuser may set auth ID to something other than himself.  Note
+ * that in case of multiple SETs in a single session, the original userid's
+ * superuserness is what matters.  But we set the GUC variable is_superuser
+ * to indicate whether the *current* session userid is a superuser.
  */
 void
-SetSessionAuthorization(const char *username)
+SetSessionAuthorization(AclId userid, bool is_superuser)
 {
-       int32           userid;
-
-       if (!AuthenticatedUserIsSuperuser)
-               elog(ERROR, "permission denied");
+       /* Must have authenticated already, else can't make permission check */
+       AssertState(AclIdIsValid(AuthenticatedUserId));
 
-       userid = get_usesysid(username);
+       if (userid != AuthenticatedUserId &&
+               !AuthenticatedUserIsSuperuser)
+               ereport(ERROR,
+                               (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+                         errmsg("permission denied to set session authorization")));
 
        SetSessionUserId(userid);
        SetUserId(userid);
+
+       SetConfigOption("is_superuser",
+                                       is_superuser ? "on" : "off",
+                                       PGC_INTERNAL, PGC_S_OVERRIDE);
 }
 
 
@@ -515,7 +390,7 @@ SetSessionAuthorization(const char *username)
  * Get user name from user id
  */
 char *
-GetUserName(Oid userid)
+GetUserNameFromId(AclId userid)
 {
        HeapTuple       tuple;
        char       *result;
@@ -524,7 +399,9 @@ GetUserName(Oid userid)
                                                   ObjectIdGetDatum(userid),
                                                   0, 0, 0);
        if (!HeapTupleIsValid(tuple))
-               elog(ERROR, "invalid user id %u", (unsigned) userid);
+               ereport(ERROR,
+                               (errcode(ERRCODE_UNDEFINED_OBJECT),
+                                errmsg("invalid user id: %d", userid)));
 
        result = pstrdup(NameStr(((Form_pg_shadow) GETSTRUCT(tuple))->usename));
 
@@ -563,20 +440,26 @@ GetUserName(Oid userid)
 static void
 UnlinkLockFile(int status, Datum filename)
 {
-       unlink((char *) DatumGetPointer(filename));
-       /* Should we complain if the unlink fails? */
+       char       *fname = (char *) DatumGetPointer(filename);
+
+       if (fname != NULL)
+       {
+               if (unlink(fname) != 0)
+               {
+                       /* Should we complain if the unlink fails? */
+               }
+               free(fname);
+       }
 }
 
 /*
- * Create a lockfile, if possible
- *
- * Call CreateLockFile with the name of the lockfile to be created.
- * Returns true if successful, false if not (with a message on stderr).
+ * Create a lockfile.
  *
+ * filename is the name of the lockfile to create.
  * amPostmaster is used to determine how to encode the output PID.
  * isDDLock and refName are used to determine what error message to produce.
  */
-static bool
+static void
 CreateLockFile(const char *filename, bool amPostmaster,
                           bool isDDLock, const char *refName)
 {
@@ -606,7 +489,10 @@ CreateLockFile(const char *filename, bool amPostmaster,
                 * Couldn't create the pid file. Probably it already exists.
                 */
                if ((errno != EEXIST && errno != EACCES) || ntries > 100)
-                       elog(FATAL, "Can't create lock file %s: %m", filename);
+                       ereport(FATAL,
+                                       (errcode_for_file_access(),
+                                        errmsg("could not create lock file \"%s\": %m",
+                                                       filename)));
 
                /*
                 * Read the file to get the old owner's PID.  Note race condition
@@ -617,10 +503,16 @@ CreateLockFile(const char *filename, bool amPostmaster,
                {
                        if (errno == ENOENT)
                                continue;               /* race condition; try again */
-                       elog(FATAL, "Can't read lock file %s: %m", filename);
+                       ereport(FATAL,
+                                       (errcode_for_file_access(),
+                                        errmsg("could not open lock file \"%s\": %m",
+                                                       filename)));
                }
                if ((len = read(fd, buffer, sizeof(buffer) - 1)) <= 0)
-                       elog(FATAL, "Can't read lock file %s: %m", filename);
+                       ereport(FATAL,
+                                       (errcode_for_file_access(),
+                                        errmsg("could not read lock file \"%s\": %m",
+                                                       filename)));
                close(fd);
 
                buffer[len] = '\0';
@@ -630,7 +522,7 @@ CreateLockFile(const char *filename, bool amPostmaster,
                other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
 
                if (other_pid <= 0)
-                       elog(FATAL, "Bogus data in lock file %s", filename);
+                       elog(FATAL, "bogus data in lock file \"%s\"", filename);
 
                /*
                 * Check to see if the other process still exists
@@ -648,19 +540,17 @@ CreateLockFile(const char *filename, bool amPostmaster,
                                 ))
                        {
                                /* lockfile belongs to a live process */
-                               fprintf(stderr, "Lock file \"%s\" already exists.\n",
-                                               filename);
-                               if (isDDLock)
-                                       fprintf(stderr,
-                                                       "Is another %s (pid %d) running in \"%s\"?\n",
-                                                       (encoded_pid < 0 ? "postgres" : "postmaster"),
-                                                       (int) other_pid, refName);
-                               else
-                                       fprintf(stderr,
-                                                       "Is another %s (pid %d) using \"%s\"?\n",
-                                                       (encoded_pid < 0 ? "postgres" : "postmaster"),
-                                                       (int) other_pid, refName);
-                               return false;
+                               ereport(FATAL,
+                                               (errcode(ERRCODE_LOCK_FILE_EXISTS),
+                                                errmsg("lock file \"%s\" already exists",
+                                                               filename),
+                                                isDDLock ?
+                                        errhint("Is another %s (pid %d) running in \"%s\"?",
+                                                  (encoded_pid < 0 ? "postgres" : "postmaster"),
+                                                        (int) other_pid, refName) :
+                                                errhint("Is another %s (pid %d) using \"%s\"?",
+                                                  (encoded_pid < 0 ? "postgres" : "postmaster"),
+                                                                (int) other_pid, refName)));
                        }
                }
 
@@ -674,27 +564,27 @@ CreateLockFile(const char *filename, bool amPostmaster,
                if (isDDLock)
                {
                        char       *ptr;
-                       unsigned long shmKey,
-                                               shmId;
+                       unsigned long id1,
+                                               id2;
 
                        ptr = strchr(buffer, '\n');
                        if (ptr != NULL &&
                                (ptr = strchr(ptr + 1, '\n')) != NULL)
                        {
                                ptr++;
-                               if (sscanf(ptr, "%lu %lu", &shmKey, &shmId) == 2)
+                               if (sscanf(ptr, "%lu %lu", &id1, &id2) == 2)
                                {
-                                       if (SharedMemoryIsInUse((IpcMemoryKey) shmKey,
-                                                                                       (IpcMemoryId) shmId))
-                                       {
-                                               fprintf(stderr,
-                                                               "Found a pre-existing shared memory block (ID %d) still in use.\n"
-                                                               "If you're sure there are no old backends still running,\n"
-                                                               "remove the shared memory block with ipcrm(1), or just\n"
-                                                               "delete \"%s\".\n",
-                                                               (int) shmId, filename);
-                                               return false;
-                                       }
+                                       if (PGSharedMemoryIsInUse(id1, id2))
+                                               ereport(FATAL,
+                                                               (errcode(ERRCODE_LOCK_FILE_EXISTS),
+                                                          errmsg("pre-existing shared memory block "
+                                                                         "(key %lu, id %lu) is still in use",
+                                                                         id1, id2),
+                                                          errhint("If you're sure there are no old "
+                                                                          "backends still running, remove "
+                                                                          "the shared memory block with "
+                                                                          "ipcrm(1), or just delete \"%s\".",
+                                                                          filename)));
                                }
                        }
                }
@@ -705,10 +595,13 @@ CreateLockFile(const char *filename, bool amPostmaster,
                 * against other would-be creators.
                 */
                if (unlink(filename) < 0)
-                       elog(FATAL, "Can't remove old lock file %s: %m"
-                                "\n\tThe file seems accidentally left, but I couldn't remove it."
-                                "\n\tPlease remove the file by hand and try again.",
-                                filename);
+                       ereport(FATAL,
+                                       (errcode_for_file_access(),
+                                        errmsg("could not remove old lock file \"%s\": %m",
+                                                       filename),
+                                        errhint("The file seems accidentally left over, but "
+                                                 "I couldn't remove it. Please remove the file "
+                                                        "by hand and try again.")));
        }
 
        /*
@@ -726,7 +619,9 @@ CreateLockFile(const char *filename, bool amPostmaster,
                unlink(filename);
                /* if write didn't set errno, assume problem is no disk space */
                errno = save_errno ? save_errno : ENOSPC;
-               elog(FATAL, "Can't write lock file %s: %m", filename);
+               ereport(FATAL,
+                               (errcode_for_file_access(),
+                         errmsg("could not write lock file \"%s\": %m", filename)));
        }
        close(fd);
 
@@ -734,58 +629,67 @@ CreateLockFile(const char *filename, bool amPostmaster,
         * Arrange for automatic removal of lockfile at proc_exit.
         */
        on_proc_exit(UnlinkLockFile, PointerGetDatum(strdup(filename)));
-
-       return true;                            /* Success! */
 }
 
-bool
+void
 CreateDataDirLockFile(const char *datadir, bool amPostmaster)
 {
        char            lockfile[MAXPGPATH];
 
        snprintf(lockfile, sizeof(lockfile), "%s/postmaster.pid", datadir);
-       if (!CreateLockFile(lockfile, amPostmaster, true, datadir))
-               return false;
+       CreateLockFile(lockfile, amPostmaster, true, datadir);
        /* Save name of lockfile for RecordSharedMemoryInLockFile */
        strcpy(directoryLockFile, lockfile);
-       return true;
 }
 
-bool
+void
 CreateSocketLockFile(const char *socketfile, bool amPostmaster)
 {
        char            lockfile[MAXPGPATH];
 
        snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
-       if (!CreateLockFile(lockfile, amPostmaster, false, socketfile))
-               return false;
+       CreateLockFile(lockfile, amPostmaster, false, socketfile);
        /* Save name of lockfile for TouchSocketLockFile */
        strcpy(socketLockFile, lockfile);
-       return true;
 }
 
 /*
- * Re-read the socket lock file.  This should be called every so often
- * to ensure that the lock file has a recent access date.  That saves it
+ * TouchSocketLockFile -- mark socket lock file as recently accessed
+ *
+ * This routine should be called every so often to ensure that the lock file
+ * has a recent mod or access date.  That saves it
  * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
  * (Another reason we should never have put the socket file in /tmp...)
  */
 void
 TouchSocketLockFile(void)
 {
-       int                     fd;
-       char            buffer[1];
-
        /* Do nothing if we did not create a socket... */
        if (socketLockFile[0] != '\0')
        {
-               /* XXX any need to complain about errors here? */
+               /*
+                * utime() is POSIX standard, utimes() is a common alternative; if
+                * we have neither, fall back to actually reading the file (which
+                * only sets the access time not mod time, but that should be
+                * enough in most cases).  In all paths, we ignore errors.
+                */
+#ifdef HAVE_UTIME
+               utime(socketLockFile, NULL);
+#else                                                  /* !HAVE_UTIME */
+#ifdef HAVE_UTIMES
+               utimes(socketLockFile, NULL);
+#else                                                  /* !HAVE_UTIMES */
+               int                     fd;
+               char            buffer[1];
+
                fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
                if (fd >= 0)
                {
                        read(fd, buffer, sizeof(buffer));
                        close(fd);
                }
+#endif   /* HAVE_UTIMES */
+#endif   /* HAVE_UTIME */
        }
 }
 
@@ -796,11 +700,11 @@ TouchSocketLockFile(void)
  * This may be called multiple times in the life of a postmaster, if we
  * delete and recreate shmem due to backend crash.     Therefore, be prepared
  * to overwrite existing information.  (As of 7.1, a postmaster only creates
- * one shm seg anyway; but for the purposes here, if we did have more than
+ * one shm seg at a time; but for the purposes here, if we did have more than
  * one then any one of them would do anyway.)
  */
 void
-RecordSharedMemoryInLockFile(IpcMemoryKey shmKey, IpcMemoryId shmId)
+RecordSharedMemoryInLockFile(unsigned long id1, unsigned long id2)
 {
        int                     fd;
        int                     len;
@@ -817,13 +721,19 @@ RecordSharedMemoryInLockFile(IpcMemoryKey shmKey, IpcMemoryId shmId)
        fd = open(directoryLockFile, O_RDWR | PG_BINARY, 0);
        if (fd < 0)
        {
-               elog(DEBUG, "Failed to rewrite %s: %m", directoryLockFile);
+               ereport(LOG,
+                               (errcode_for_file_access(),
+                                errmsg("could not rewrite \"%s\": %m",
+                                               directoryLockFile)));
                return;
        }
        len = read(fd, buffer, sizeof(buffer) - 100);
        if (len <= 0)
        {
-               elog(DEBUG, "Failed to read %s: %m", directoryLockFile);
+               ereport(LOG,
+                               (errcode_for_file_access(),
+                                errmsg("could not read \"%s\": %m",
+                                               directoryLockFile)));
                close(fd);
                return;
        }
@@ -836,18 +746,17 @@ RecordSharedMemoryInLockFile(IpcMemoryKey shmKey, IpcMemoryId shmId)
        if (ptr == NULL ||
                (ptr = strchr(ptr + 1, '\n')) == NULL)
        {
-               elog(DEBUG, "Bogus data in %s", directoryLockFile);
+               elog(LOG, "bogus data in \"%s\"", directoryLockFile);
                close(fd);
                return;
        }
        ptr++;
 
        /*
-        * Append shm key and ID.  Format to try to keep it the same length
+        * Append key information.      Format to try to keep it the same length
         * always (trailing junk won't hurt, but might confuse humans).
         */
-       sprintf(ptr, "%9lu %9lu\n",
-                       (unsigned long) shmKey, (unsigned long) shmId);
+       sprintf(ptr, "%9lu %9lu\n", id1, id2);
 
        /*
         * And rewrite the data.  Since we write in a single kernel call, this
@@ -861,7 +770,10 @@ RecordSharedMemoryInLockFile(IpcMemoryKey shmKey, IpcMemoryId shmId)
                /* if write didn't set errno, assume problem is no disk space */
                if (errno == 0)
                        errno = ENOSPC;
-               elog(DEBUG, "Failed to write %s: %m", directoryLockFile);
+               ereport(LOG,
+                               (errcode_for_file_access(),
+                                errmsg("could not write \"%s\": %m",
+                                               directoryLockFile)));
                close(fd);
                return;
        }
@@ -878,7 +790,7 @@ RecordSharedMemoryInLockFile(IpcMemoryKey shmKey, IpcMemoryId shmId)
  * Determine whether the PG_VERSION file in directory `path' indicates
  * a data version compatible with the version of this program.
  *
- * If compatible, return. Otherwise, elog(FATAL).
+ * If compatible, return. Otherwise, ereport(FATAL).
  */
 void
 ValidatePgVersion(const char *path)
@@ -897,25 +809,138 @@ ValidatePgVersion(const char *path)
        if (*endptr == '.')
                my_minor = strtol(endptr + 1, NULL, 10);
 
-       snprintf(full_path, MAXPGPATH, "%s/PG_VERSION", path);
+       snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
 
        file = AllocateFile(full_path, "r");
        if (!file)
        {
                if (errno == ENOENT)
-                       elog(FATAL, "File %s is missing. This is not a valid data directory.", full_path);
+                       ereport(FATAL,
+                                       (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+                                        errmsg("\"%s\" is not a valid data directory",
+                                                       path),
+                                        errdetail("File \"%s\" is missing.", full_path)));
                else
-                       elog(FATAL, "cannot open %s: %m", full_path);
+                       ereport(FATAL,
+                                       (errcode_for_file_access(),
+                                        errmsg("could not open \"%s\": %m", full_path)));
        }
 
        ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
        if (ret != 2)
-               elog(FATAL, "File %s does not contain valid data. You need to initdb.", full_path);
+               ereport(FATAL,
+                               (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+                                errmsg("\"%s\" is not a valid data directory",
+                                               path),
+                                errdetail("File \"%s\" does not contain valid data.",
+                                                  full_path),
+                                errhint("You may need to initdb.")));
 
        FreeFile(file);
 
        if (my_major != file_major || my_minor != file_minor)
-               elog(FATAL, "The data directory was initialized by PostgreSQL version %ld.%ld, "
-                        "which is not compatible with this version %s.",
-                        file_major, file_minor, version_string);
+               ereport(FATAL,
+                               (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+                                errmsg("database files are incompatible with server"),
+                                errdetail("The data directory was initialized by PostgreSQL version %ld.%ld, "
+                                                "which is not compatible with this version %s.",
+                                                  file_major, file_minor, version_string)));
+}
+
+/*-------------------------------------------------------------------------
+ *                             Library preload support
+ *-------------------------------------------------------------------------
+ */
+
+#if defined(__mc68000__) && defined(__ELF__)
+typedef int32 ((*func_ptr) ());
+
+#else
+typedef char *((*func_ptr) ());
+#endif
+
+/*
+ * process any libraries that should be preloaded and
+ * optionally pre-initialized
+ */
+void
+process_preload_libraries(char *preload_libraries_string)
+{
+       char       *rawstring;
+       List       *elemlist;
+       List       *l;
+
+       if (preload_libraries_string == NULL)
+               return;
+
+       /* Need a modifiable copy of string */
+       rawstring = pstrdup(preload_libraries_string);
+
+       /* Parse string into list of identifiers */
+       if (!SplitIdentifierString(rawstring, ',', &elemlist))
+       {
+               /* syntax error in list */
+               pfree(rawstring);
+               freeList(elemlist);
+               ereport(LOG,
+                               (errcode(ERRCODE_SYNTAX_ERROR),
+                                errmsg("invalid list syntax for preload_libraries configuration option")));
+               return;
+       }
+
+       foreach(l, elemlist)
+       {
+               char       *tok = (char *) lfirst(l);
+               char       *sep = strstr(tok, ":");
+               char       *filename = NULL;
+               char       *funcname = NULL;
+               func_ptr        initfunc;
+
+               if (sep)
+               {
+                       /*
+                        * a colon separator implies there is an initialization
+                        * function that we need to run in addition to loading the
+                        * library
+                        */
+                       size_t          filename_len = sep - tok;
+                       size_t          funcname_len = strlen(tok) - filename_len - 1;
+
+                       filename = (char *) palloc(filename_len + 1);
+                       memcpy(filename, tok, filename_len);
+                       filename[filename_len] = '\0';
+
+                       funcname = (char *) palloc(funcname_len + 1);
+                       strcpy(funcname, sep + 1);
+               }
+               else
+               {
+                       /*
+                        * no separator -- just load the library
+                        */
+                       filename = pstrdup(tok);
+                       funcname = NULL;
+               }
+
+               initfunc = (func_ptr) load_external_function(filename, funcname,
+                                                                                                        true, NULL);
+               if (initfunc)
+                       (*initfunc) ();
+
+               if (funcname)
+                       ereport(LOG,
+                                       (errmsg("preloaded library \"%s\" with initialization function \"%s\"",
+                                                       filename, funcname)));
+               else
+                       ereport(LOG,
+                                       (errmsg("preloaded library \"%s\"",
+                                                       filename)));
+
+               pfree(filename);
+               if (funcname)
+                       pfree(funcname);
+       }
+
+       pfree(rawstring);
+       freeList(elemlist);
 }