]> 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 ad0df82135029d193561f80fbd5c1bdb18d2a582..22baac3706f6e4f2ae21afdda46578235509386f 100644 (file)
@@ -3,12 +3,12 @@
  * miscinit.c
  *       miscellaneous initialization support stuff
  *
- * Portions Copyright (c) 1996-2002, 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.99 2003/01/25 05:19:46 tgl Exp $
+ *       $Header: /cvsroot/pgsql/src/backend/utils/init/miscinit.c,v 1.114 2003/09/24 18:54:01 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -48,16 +48,14 @@ ProcessingMode Mode = InitProcessing;
 static char directoryLockFile[MAXPGPATH];
 static char socketLockFile[MAXPGPATH];
 
-#ifdef CYR_RECODE
-static unsigned char RecodeForwTable[128];
-static unsigned char RecodeBackTable[128];
-
-static void GetCharSetByHost(char *TableName, int host, const char *DataDir);
-#endif
-
 
 /* ----------------------------------------------------------------
  *             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.
  * ----------------------------------------------------------------
  */
 
@@ -68,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)
@@ -84,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
  * ----------------------------------------------------------------
@@ -105,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.
@@ -134,7 +162,7 @@ SetDataDir(const char *dir)
        AssertArg(dir);
 
        /* If presented path is relative, convert to absolute */
-       if (dir[0] != '/')
+       if (!is_absolute_path(dir))
        {
                char       *buf;
                size_t          buflen;
@@ -144,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;
@@ -157,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);
        }
@@ -171,7 +203,9 @@ 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")));
        }
 
        /*
@@ -179,7 +213,11 @@ SetDataDir(const char *dir)
         * generating funny-looking paths to individual files.
         */
        newlen = strlen(new);
-       if (newlen > 1 && new[newlen - 1] == '/')
+       if (newlen > 1 && new[newlen - 1] == '/'
+#ifdef WIN32
+               || new[newlen - 1] == '\\'
+#endif
+               )
                new[newlen - 1] = '\0';
 
        if (DataDir)
@@ -187,295 +225,6 @@ SetDataDir(const char *dir)
        DataDir = new;
 }
 
-/* ----------------------------------------------------------------
- *                             CYR_RECODE support
- * ----------------------------------------------------------------
- */
-
-#ifdef CYR_RECODE
-
-void
-SetCharSet(void)
-{
-       FILE       *file;
-       char       *filename;
-       char       *map_file;
-       char            buf[MAX_TOKEN];
-       int                     i;
-       unsigned char FromChar,
-                               ToChar;
-       char            ChTable[MAX_TOKEN];
-
-       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);
-               filename = ChTable;
-       }
-       else
-               filename = getenv("PG_RECODETABLE");
-
-       if (filename && *filename != '\0')
-       {
-               map_file = palloc(strlen(DataDir) + strlen(filename) + 2);
-               sprintf(map_file, "%s/%s", DataDir, filename);
-               file = AllocateFile(map_file, "r");
-               pfree(map_file);
-               if (file == NULL)
-                       return;
-
-               while (!feof(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 to EOL */
-                                       while (!feof(file) && buf[0])
-                                       {
-                                               next_token(file, buf, sizeof(buf));
-                                               elog(LOG, "SetCharSet: unknown tag %s in file %s",
-                                                        buf, filename);
-                                       }
-                               }
-                       }
-               }
-               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;
-}
-
-#define CHARSET_FILE "charset.conf"
-#define MAX_CHARSETS   10
-#define KEY_HOST          1
-#define KEY_BASE          2
-#define KEY_TABLE         3
-
-struct CharsetItem
-{
-       char            Orig[MAX_TOKEN];
-       char            Dest[MAX_TOKEN];
-       char            Table[MAX_TOKEN];
-};
-
-
-static bool
-CharSetInRange(char *buf, int host)
-{
-       int                     valid,
-                               i,
-                               FromAddr,
-                               ToAddr,
-                               tmp;
-       struct in_addr file_ip_addr;
-       char       *p;
-       unsigned int one = 0x80000000,
-                               NetMask = 0;
-       unsigned char mask;
-
-       p = strchr(buf, '/');
-       if (p)
-       {
-               *p++ = '\0';
-               valid = inet_aton(buf, &file_ip_addr);
-               if (valid)
-               {
-                       mask = strtoul(p, 0, 0);
-                       FromAddr = ntohl(file_ip_addr.s_addr);
-                       ToAddr = ntohl(file_ip_addr.s_addr);
-                       for (i = 0; i < mask; i++)
-                       {
-                               NetMask |= one;
-                               one >>= 1;
-                       }
-                       FromAddr &= NetMask;
-                       ToAddr = ToAddr | ~NetMask;
-                       tmp = ntohl(host);
-                       return ((unsigned) tmp >= (unsigned) FromAddr &&
-                                       (unsigned) tmp <= (unsigned) ToAddr);
-               }
-       }
-       else
-       {
-               p = strchr(buf, '-');
-               if (p)
-               {
-                       *p++ = '\0';
-                       valid = inet_aton(buf, &file_ip_addr);
-                       if (valid)
-                       {
-                               FromAddr = ntohl(file_ip_addr.s_addr);
-                               valid = inet_aton(p, &file_ip_addr);
-                               if (valid)
-                               {
-                                       ToAddr = ntohl(file_ip_addr.s_addr);
-                                       tmp = ntohl(host);
-                                       return ((unsigned) tmp >= (unsigned) FromAddr &&
-                                                       (unsigned) tmp <= (unsigned) ToAddr);
-                               }
-                       }
-               }
-               else
-               {
-                       valid = inet_aton(buf, &file_ip_addr);
-                       if (valid)
-                       {
-                               FromAddr = file_ip_addr.s_addr;
-                               return (unsigned) FromAddr == (unsigned) host;
-                       }
-               }
-       }
-       return false;
-}
-
-
-static void
-GetCharSetByHost(char *TableName, int host, const char *DataDir)
-{
-       FILE       *file;
-       char            buf[MAX_TOKEN],
-                               BaseCharset[MAX_TOKEN],
-                               OrigCharset[MAX_TOKEN],
-                               DestCharset[MAX_TOKEN],
-                               HostCharset[MAX_TOKEN],
-                          *map_file;
-       int                     key,
-                               ChIndex = 0,
-                               i,
-                               bufsize;
-       struct CharsetItem *ChArray[MAX_CHARSETS];
-
-       *TableName = '\0';
-       bufsize = (strlen(DataDir) + strlen(CHARSET_FILE) + 2) * sizeof(char);
-       map_file = (char *) palloc(bufsize);
-       snprintf(map_file, bufsize, "%s/%s", DataDir, CHARSET_FILE);
-       file = AllocateFile(map_file, "r");
-       pfree(map_file);
-       if (file == NULL)
-       {
-               /* XXX should we log a complaint? */
-               return;
-       }
-
-       while (!feof(file))
-       {
-               next_token(file, buf, sizeof(buf));
-               if (buf[0] != '\0')
-               {
-                       key = 0;
-                       if (strcasecmp(buf, "HostCharset") == 0)
-                               key = KEY_HOST;
-                       else if (strcasecmp(buf, "BaseCharset") == 0)
-                               key = KEY_BASE;
-                       else if (strcasecmp(buf, "RecodeTable") == 0)
-                               key = KEY_TABLE;
-                       else
-                               elog(LOG, "GetCharSetByHost: unknown tag %s in file %s",
-                                        buf, CHARSET_FILE);
-
-                       switch (key)
-                       {
-                               case KEY_HOST:
-                                       /* Read the host */
-                                       next_token(file, buf, sizeof(buf));
-                                       if (buf[0] != '\0')
-                                       {
-                                               if (CharSetInRange(buf, host))
-                                               {
-                                                       /* Read the charset */
-                                                       next_token(file, buf, sizeof(buf));
-                                                       if (buf[0] != '\0')
-                                                               strcpy(HostCharset, buf);
-                                               }
-                                       }
-                                       break;
-                               case KEY_BASE:
-                                       /* Read the base charset */
-                                       next_token(file, buf, sizeof(buf));
-                                       if (buf[0] != '\0')
-                                               strcpy(BaseCharset, buf);
-                                       break;
-                               case KEY_TABLE:
-                                       /* Read the original charset */
-                                       next_token(file, buf, sizeof(buf));
-                                       if (buf[0] != '\0')
-                                       {
-                                               strcpy(OrigCharset, buf);
-                                               /* Read the destination charset */
-                                               next_token(file, buf, sizeof(buf));
-                                               if (buf[0] != '\0')
-                                               {
-                                                       strcpy(DestCharset, buf);
-                                                       /* Read the table filename */
-                                                       next_token(file, buf, sizeof(buf));
-                                                       if (buf[0] != '\0')
-                                                       {
-                                                               ChArray[ChIndex] =
-                                                                       (struct CharsetItem *) palloc(sizeof(struct CharsetItem));
-                                                               strcpy(ChArray[ChIndex]->Orig, OrigCharset);
-                                                               strcpy(ChArray[ChIndex]->Dest, DestCharset);
-                                                               strcpy(ChArray[ChIndex]->Table, buf);
-                                                               ChIndex++;
-                                                       }
-                                               }
-                                       }
-                                       break;
-                       }
-
-                       /* read to EOL */
-                       while (!feof(file) && buf[0])
-                       {
-                               next_token(file, buf, sizeof(buf));
-                               elog(LOG, "GetCharSetByHost: unknown tag %s in file %s",
-                                        buf, CHARSET_FILE);
-                       }
-               }
-       }
-       FreeFile(file);
-
-       for (i = 0; i < ChIndex; i++)
-       {
-               if (strcasecmp(BaseCharset, ChArray[i]->Orig) == 0 &&
-                       strcasecmp(HostCharset, ChArray[i]->Dest) == 0)
-                       strncpy(TableName, ChArray[i]->Table, 79);
-               pfree(ChArray[i]);
-       }
-}
-#endif   /* CYR_RECODE */
-
-
 
 /* ----------------------------------------------------------------
  *     User ID things
@@ -488,9 +237,9 @@ GetCharSetByHost(char *TableName, int host, const char *DataDir)
  * restore the current user id if you need to change it.
  * ----------------------------------------------------------------
  */
-static AclId   AuthenticatedUserId = 0;
-static AclId   SessionUserId = 0;
-static AclId   CurrentUserId = 0;
+static AclId AuthenticatedUserId = 0;
+static AclId SessionUserId = 0;
+static AclId CurrentUserId = 0;
 
 static bool AuthenticatedUserIsSuperuser = false;
 
@@ -556,7 +305,9 @@ InitializeSessionUserId(const char *username)
                                                         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)));
 
        usesysid = ((Form_pg_shadow) GETSTRUCT(userTup))->usesysid;
 
@@ -565,9 +316,12 @@ InitializeSessionUserId(const char *username)
 
        SetSessionUserId(usesysid); /* sets CurrentUserId too */
 
-       /* Record username as a config option 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
@@ -606,20 +360,29 @@ InitializeSessionUserIdStandalone(void)
 /*
  * Change session auth ID while running
  *
- * Only a superuser may set auth ID to something other than himself.
+ * 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(AclId userid)
+SetSessionAuthorization(AclId userid, bool is_superuser)
 {
        /* Must have authenticated already, else can't make permission check */
        AssertState(AclIdIsValid(AuthenticatedUserId));
 
        if (userid != AuthenticatedUserId &&
                !AuthenticatedUserIsSuperuser)
-               elog(ERROR, "permission denied");
+               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);
 }
 
 
@@ -636,7 +399,9 @@ GetUserNameFromId(AclId userid)
                                                   ObjectIdGetDatum(userid),
                                                   0, 0, 0);
        if (!HeapTupleIsValid(tuple))
-               elog(ERROR, "invalid user id %d", userid);
+               ereport(ERROR,
+                               (errcode(ERRCODE_UNDEFINED_OBJECT),
+                                errmsg("invalid user id: %d", userid)));
 
        result = pstrdup(NameStr(((Form_pg_shadow) GETSTRUCT(tuple))->usename));
 
@@ -675,20 +440,26 @@ GetUserNameFromId(AclId 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)
 {
@@ -718,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
@@ -729,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';
@@ -742,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
@@ -760,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)));
                        }
                }
 
@@ -797,15 +575,16 @@ CreateLockFile(const char *filename, bool amPostmaster,
                                if (sscanf(ptr, "%lu %lu", &id1, &id2) == 2)
                                {
                                        if (PGSharedMemoryIsInUse(id1, id2))
-                                       {
-                                               fprintf(stderr,
-                                                               "Found a pre-existing shared memory block (key %lu, id %lu) 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",
-                                                               id1, id2, filename);
-                                               return false;
-                                       }
+                                               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)));
                                }
                        }
                }
@@ -816,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.")));
        }
 
        /*
@@ -837,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);
 
@@ -845,34 +629,28 @@ 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;
 }
 
 /*
@@ -890,17 +668,17 @@ TouchSocketLockFile(void)
        if (socketLockFile[0] != '\0')
        {
                /*
-                * 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.
+                * 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 */
+#else                                                  /* !HAVE_UTIME */
 #ifdef HAVE_UTIMES
                utimes(socketLockFile, NULL);
-#else /* !HAVE_UTIMES */
+#else                                                  /* !HAVE_UTIMES */
                int                     fd;
                char            buffer[1];
 
@@ -910,8 +688,8 @@ TouchSocketLockFile(void)
                        read(fd, buffer, sizeof(buffer));
                        close(fd);
                }
-#endif /* HAVE_UTIMES */
-#endif /* HAVE_UTIME */
+#endif   /* HAVE_UTIMES */
+#endif   /* HAVE_UTIME */
        }
 }
 
@@ -943,13 +721,19 @@ RecordSharedMemoryInLockFile(unsigned long id1, unsigned long id2)
        fd = open(directoryLockFile, O_RDWR | PG_BINARY, 0);
        if (fd < 0)
        {
-               elog(LOG, "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(LOG, "Failed to read %s: %m", directoryLockFile);
+               ereport(LOG,
+                               (errcode_for_file_access(),
+                                errmsg("could not read \"%s\": %m",
+                                               directoryLockFile)));
                close(fd);
                return;
        }
@@ -962,7 +746,7 @@ RecordSharedMemoryInLockFile(unsigned long id1, unsigned long id2)
        if (ptr == NULL ||
                (ptr = strchr(ptr + 1, '\n')) == NULL)
        {
-               elog(LOG, "Bogus data in %s", directoryLockFile);
+               elog(LOG, "bogus data in \"%s\"", directoryLockFile);
                close(fd);
                return;
        }
@@ -986,7 +770,10 @@ RecordSharedMemoryInLockFile(unsigned long id1, unsigned long id2)
                /* if write didn't set errno, assume problem is no disk space */
                if (errno == 0)
                        errno = ENOSPC;
-               elog(LOG, "Failed to write %s: %m", directoryLockFile);
+               ereport(LOG,
+                               (errcode_for_file_access(),
+                                errmsg("could not write \"%s\": %m",
+                                               directoryLockFile)));
                close(fd);
                return;
        }
@@ -1003,7 +790,7 @@ RecordSharedMemoryInLockFile(unsigned long id1, unsigned long id2)
  * 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)
@@ -1022,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);
 }