]> granicus.if.org Git - postgresql/blobdiff - src/backend/utils/init/miscinit.c
Seems some C compilers think 'restrict' is a fully reserved word.
[postgresql] / src / backend / utils / init / miscinit.c
index b708ffb27913c6b9eff49d32e7235ced92ab8536..2d979afeada2f72952cf97d1d7d39b397c2fcf65 100644 (file)
  * miscinit.c
  *       miscellaneous initialization support stuff
  *
- * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1996-2006, 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.88 2002/05/03 20:43:30 tgl Exp $
+ *       $PostgreSQL: pgsql/src/backend/utils/init/miscinit.c,v 1.158 2006/08/16 04:32:48 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 "catalog/pg_authid.h"
 #include "miscadmin.h"
+#include "postmaster/autovacuum.h"
+#include "storage/fd.h"
+#include "storage/ipc.h"
+#include "storage/pg_shmem.h"
+#include "storage/proc.h"
+#include "storage/procarray.h"
 #include "utils/builtins.h"
 #include "utils/guc.h"
-#include "utils/lsyscache.h"
 #include "utils/syscache.h"
 
 
+#define DIRECTORY_LOCK_FILE            "postmaster.pid"
+
 ProcessingMode Mode = InitProcessing;
 
-/* Note: we rely on these to initialize as zeroes */
-static char directoryLockFile[MAXPGPATH];
+/* Note: we rely on this to initialize as zeroes */
 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.
+ * ----------------------------------------------------------------
+ */
 
+bool IgnoreSystemIndexes = false;
 
 /* ----------------------------------------------------------------
- *             ignoring system indexes support stuff
+ *             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 bool isIgnoringSystemIndexes = false;
+static Oid     currentlyReindexedHeap = InvalidOid;
+static Oid     currentlyReindexedIndex = InvalidOid;
 
 /*
- * IsIgnoringSystemIndexes
- *             True if ignoring system indexes.
+ * ReindexIsProcessingHeap
+ *             True if heap specified by OID is currently being reindexed.
  */
 bool
-IsIgnoringSystemIndexes()
+ReindexIsProcessingHeap(Oid heapOid)
 {
-       return isIgnoringSystemIndexes;
+       return heapOid == currentlyReindexedHeap;
 }
 
 /*
- * IgnoreSystemIndexes
- *     Set true or false whether PostgreSQL ignores system indexes.
- *
+ * 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.
  */
 void
-IgnoreSystemIndexes(bool mode)
+SetReindexProcessing(Oid heapOid, Oid indexOid)
 {
-       isIgnoringSystemIndexes = mode;
+       Assert(OidIsValid(heapOid) && OidIsValid(indexOid));
+       /* Reindexing is not re-entrant. */
+       if (OidIsValid(currentlyReindexedIndex))
+               elog(ERROR, "cannot reindex while reindexing");
+       currentlyReindexedHeap = heapOid;
+       currentlyReindexedIndex = indexOid;
+}
+
+/*
+ * ResetReindexProcessing
+ *             Unset reindexing status.
+ */
+void
+ResetReindexProcessing(void)
+{
+       currentlyReindexedHeap = InvalidOid;
+       currentlyReindexedIndex = InvalidOid;
 }
 
 /* ----------------------------------------------------------------
@@ -101,22 +140,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.
@@ -125,12 +148,55 @@ void
 SetDataDir(const char *dir)
 {
        char       *new;
-       int                     newlen;
 
        AssertArg(dir);
 
        /* If presented path is relative, convert to absolute */
-       if (dir[0] != '/')
+       new = make_absolute_path(dir);
+
+       if (DataDir)
+               free(DataDir);
+       DataDir = new;
+}
+
+/*
+ * Change working directory to DataDir.  Most of the postmaster and backend
+ * code assumes that we are in DataDir so it can use relative paths to access
+ * stuff in and under the data directory.  For convenience during path
+ * setup, however, we don't force the chdir to occur during SetDataDir.
+ */
+void
+ChangeToDataDir(void)
+{
+       AssertState(DataDir);
+
+       if (chdir(DataDir) < 0)
+               ereport(FATAL,
+                               (errcode_for_file_access(),
+                                errmsg("could not change directory to \"%s\": %m",
+                                               DataDir)));
+}
+
+/*
+ * If the given pathname isn't already absolute, make it so, interpreting
+ * it relative to the current working directory.
+ *
+ * Also canonicalizes the path.  The result is always a malloc'd copy.
+ *
+ * Note: interpretation of relative-path arguments during postmaster startup
+ * should happen before doing ChangeToDataDir(), else the user will probably
+ * not like the results.
+ */
+char *
+make_absolute_path(const char *path)
+{
+       char       *new;
+
+       /* Returning null for null input is convenient for some callers */
+       if (path == NULL)
+               return NULL;
+
+       if (!is_absolute_path(path))
        {
                char       *buf;
                size_t          buflen;
@@ -140,7 +206,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;
@@ -153,413 +221,114 @@ 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);
+               new = malloc(strlen(buf) + strlen(path) + 2);
                if (!new)
-                       elog(FATAL, "out of memory");
-               sprintf(new, "%s/%s", buf, dir);
+                       ereport(FATAL,
+                                       (errcode(ERRCODE_OUT_OF_MEMORY),
+                                        errmsg("out of memory")));
+               sprintf(new, "%s/%s", buf, path);
                free(buf);
        }
        else
        {
-               new = strdup(dir);
+               new = strdup(path);
                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] == '/')
-               new[newlen-1] = '\0';
+       /* Make sure punctuation is canonical, too */
+       canonicalize_path(new);
 
-       if (DataDir)
-               free(DataDir);
-       DataDir = new;
+       return new;
 }
 
 
 /* ----------------------------------------------------------------
- *                             MULTIBYTE stub code
+ *     User ID state
+ *
+ * We have to track several different values associated with the concept
+ * of "user ID".
  *
- * Even if MULTIBYTE is not enabled, these functions are necessary
- * since pg_proc.h has references to them.
+ * AuthenticatedUserId is determined at connection start and never changes.
+ *
+ * SessionUserId is initially the same as AuthenticatedUserId, but can be
+ * changed by SET SESSION AUTHORIZATION (if AuthenticatedUserIsSuperuser).
+ * This is the ID reported by the SESSION_USER SQL function.
+ *
+ * OuterUserId is the current user ID in effect at the "outer level" (outside
+ * any transaction or function).  This is initially the same as SessionUserId,
+ * but can be changed by SET ROLE to any role that SessionUserId is a
+ * member of.  We store this mainly so that AtAbort_UserId knows what to
+ * reset CurrentUserId to.
+ *
+ * CurrentUserId is the current effective user ID; this is the one to use
+ * for all normal permissions-checking purposes.  At outer level this will
+ * be the same as OuterUserId, but it changes during calls to SECURITY
+ * DEFINER functions, as well as locally in some specialized commands.
  * ----------------------------------------------------------------
  */
+static Oid     AuthenticatedUserId = InvalidOid;
+static Oid     SessionUserId = InvalidOid;
+static Oid     OuterUserId = InvalidOid;
+static Oid     CurrentUserId = InvalidOid;
 
-#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);
-}
+/* We also have to remember the superuser state of some of these levels */
+static bool AuthenticatedUserIsSuperuser = false;
+static bool SessionUserIsSuperuser = false;
 
-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(""));
-}
+/* We also remember if a SET ROLE is currently active */
+static bool SetRoleIsActive = false;
 
-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
- * ----------------------------------------------------------------
+/*
+ * GetUserId/SetUserId - get/set the current effective user ID.
  */
-
-#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)
+Oid
+GetUserId(void)
 {
-       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;
+       AssertState(OidIsValid(CurrentUserId));
+       return CurrentUserId;
 }
 
 
-static void
-GetCharSetByHost(char *TableName, int host, const char *DataDir)
+void
+SetUserId(Oid userid)
 {
-       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]);
-       }
+       AssertArg(OidIsValid(userid));
+       CurrentUserId = userid;
 }
 
-#endif   /* CYR_RECODE */
-
-
-
-/* ----------------------------------------------------------------
- *     User ID things
- *
- * The session user is determined at connection start and never
- * changes.  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 bool AuthenticatedUserIsSuperuser = false;
 
 /*
- * This function is relevant for all privilege checks.
+ * GetOuterUserId/SetOuterUserId - get/set the outer-level user ID.
  */
 Oid
-GetUserId(void)
+GetOuterUserId(void)
 {
-       AssertState(OidIsValid(CurrentUserId));
-       return CurrentUserId;
+       AssertState(OidIsValid(OuterUserId));
+       return OuterUserId;
 }
 
 
-void
-SetUserId(Oid newid)
+static void
+SetOuterUserId(Oid userid)
 {
-       AssertArg(OidIsValid(newid));
-       CurrentUserId = newid;
+       AssertArg(OidIsValid(userid));
+       OuterUserId = userid;
+
+       /* We force the effective user ID to match, too */
+       CurrentUserId = userid;
 }
 
 
 /*
- * This value is only relevant for informational purposes.
+ * GetSessionUserId/SetSessionUserId - get/set the session user ID.
  */
 Oid
 GetSessionUserId(void)
@@ -569,23 +338,31 @@ GetSessionUserId(void)
 }
 
 
-void
-SetSessionUserId(Oid newid)
+static void
+SetSessionUserId(Oid userid, bool is_superuser)
 {
-       AssertArg(OidIsValid(newid));
-       SessionUserId = newid;
-       /* Current user defaults to session user. */
-       if (!OidIsValid(CurrentUserId))
-               CurrentUserId = newid;
+       AssertArg(OidIsValid(userid));
+       SessionUserId = userid;
+       SessionUserIsSuperuser = is_superuser;
+       SetRoleIsActive = false;
+
+       /* We force the effective user IDs to match, too */
+       OuterUserId = userid;
+       CurrentUserId = userid;
 }
 
 
+/*
+ * Initialize user identity during normal backend startup
+ */
 void
-InitializeSessionUserId(const char *username)
+InitializeSessionUserId(const char *rolename)
 {
-       HeapTuple       userTup;
+       HeapTuple       roleTup;
+       Form_pg_authid rform;
        Datum           datum;
        bool            isnull;
+       Oid                     roleid;
 
        /*
         * Don't do scans if we're bootstrapping, none of the system catalogs
@@ -594,91 +371,238 @@ InitializeSessionUserId(const char *username)
        AssertState(!IsBootstrapProcessingMode());
 
        /* call only once */
-       AssertState(!OidIsValid(SessionUserId));
+       AssertState(!OidIsValid(AuthenticatedUserId));
 
-       userTup = SearchSysCache(SHADOWNAME,
-                                                        PointerGetDatum(username),
+       roleTup = SearchSysCache(AUTHNAME,
+                                                        PointerGetDatum(rolename),
                                                         0, 0, 0);
-       if (!HeapTupleIsValid(userTup))
-               elog(FATAL, "user \"%s\" does not exist", username);
+       if (!HeapTupleIsValid(roleTup))
+               ereport(FATAL,
+                               (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
+                                errmsg("role \"%s\" does not exist", rolename)));
+
+       rform = (Form_pg_authid) GETSTRUCT(roleTup);
+       roleid = HeapTupleGetOid(roleTup);
 
-       SetSessionUserId(((Form_pg_shadow) GETSTRUCT(userTup))->usesysid);
+       AuthenticatedUserId = roleid;
+       AuthenticatedUserIsSuperuser = rform->rolsuper;
+
+       /* This sets OuterUserId/CurrentUserId too */
+       SetSessionUserId(roleid, AuthenticatedUserIsSuperuser);
+
+       /* Also mark our PGPROC entry with the authenticated user id */
+       /* (We assume this is an atomic store so no lock is needed) */
+       MyProc->roleId = roleid;
+
+       /*
+        * These next checks are not enforced when in standalone mode, so that
+        * there is a way to recover from sillinesses like "UPDATE pg_authid SET
+        * rolcanlogin = false;".
+        *
+        * We do not enforce them for the autovacuum process either.
+        */
+       if (IsUnderPostmaster && !IsAutoVacuumProcess())
+       {
+               /*
+                * Is role allowed to login at all?
+                */
+               if (!rform->rolcanlogin)
+                       ereport(FATAL,
+                                       (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
+                                        errmsg("role \"%s\" is not permitted to log in",
+                                                       rolename)));
+
+               /*
+                * Check connection limit for this role.
+                *
+                * There is a race condition here --- we create our PGPROC before
+                * checking for other PGPROCs.  If two backends did this at about the
+                * same time, they might both think they were over the limit, while
+                * ideally one should succeed and one fail.  Getting that to work
+                * exactly seems more trouble than it is worth, however; instead we
+                * just document that the connection limit is approximate.
+                */
+               if (rform->rolconnlimit >= 0 &&
+                       !AuthenticatedUserIsSuperuser &&
+                       CountUserBackends(roleid) > rform->rolconnlimit)
+                       ereport(FATAL,
+                                       (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
+                                        errmsg("too many connections for role \"%s\"",
+                                                       rolename)));
+       }
 
-       AuthenticatedUserIsSuperuser = ((Form_pg_shadow) GETSTRUCT(userTup))->usesuper;
+       /* Record username and superuser status as GUC settings too */
+       SetConfigOption("session_authorization", rolename,
+                                       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_authid twice during session startup.
         */
-       datum = SysCacheGetAttr(SHADOWNAME, userTup,
-                                                       Anum_pg_shadow_useconfig, &isnull);
+       datum = SysCacheGetAttr(AUTHNAME, roleTup,
+                                                       Anum_pg_authid_rolconfig, &isnull);
        if (!isnull)
        {
-               ArrayType *a = DatumGetArrayTypeP(datum);
+               ArrayType  *a = DatumGetArrayTypeP(datum);
 
                ProcessGUCArray(a, PGC_S_USER);
        }
 
-       ReleaseSysCache(userTup);
+       ReleaseSysCache(roleTup);
 }
 
 
+/*
+ * Initialize user identity during special backend startup
+ */
 void
 InitializeSessionUserIdStandalone(void)
 {
        /* This function should only be called in a single-user backend. */
-       AssertState(!IsUnderPostmaster);
+       AssertState(!IsUnderPostmaster || IsAutoVacuumProcess());
 
        /* call only once */
-       AssertState(!OidIsValid(SessionUserId));
+       AssertState(!OidIsValid(AuthenticatedUserId));
 
-       SetSessionUserId(BOOTSTRAP_USESYSID);
+       AuthenticatedUserId = BOOTSTRAP_SUPERUSERID;
        AuthenticatedUserIsSuperuser = true;
+
+       SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
+}
+
+
+/*
+ * Reset effective userid during AbortTransaction
+ *
+ * This is essentially SetUserId(GetOuterUserId()), but without the Asserts.
+ * The reason is that if a backend's InitPostgres transaction fails (eg,
+ * because an invalid user name was given), we have to be able to get through
+ * AbortTransaction without asserting.
+ */
+void
+AtAbort_UserId(void)
+{
+       CurrentUserId = OuterUserId;
 }
 
 
 /*
  * 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.
+ *
+ * Note: this is not an especially clean place to do the permission check.
+ * It's OK because the check does not require catalog access and can't
+ * fail during an end-of-transaction GUC reversion, but we may someday
+ * have to push it up into assign_session_authorization.
  */
 void
-SetSessionAuthorization(const char *username)
+SetSessionAuthorization(Oid userid, bool is_superuser)
 {
-       int32           userid;
+       /* Must have authenticated already, else can't make permission check */
+       AssertState(OidIsValid(AuthenticatedUserId));
 
-       if (!AuthenticatedUserIsSuperuser)
-               elog(ERROR, "permission denied");
+       if (userid != AuthenticatedUserId &&
+               !AuthenticatedUserIsSuperuser)
+               ereport(ERROR,
+                               (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+                                errmsg("permission denied to set session authorization")));
+
+       SetSessionUserId(userid, is_superuser);
+
+       SetConfigOption("is_superuser",
+                                       is_superuser ? "on" : "off",
+                                       PGC_INTERNAL, PGC_S_OVERRIDE);
+}
+
+/*
+ * Report current role id
+ *             This follows the semantics of SET ROLE, ie return the outer-level ID
+ *             not the current effective ID, and return InvalidOid when the setting
+ *             is logically SET ROLE NONE.
+ */
+Oid
+GetCurrentRoleId(void)
+{
+       if (SetRoleIsActive)
+               return OuterUserId;
+       else
+               return InvalidOid;
+}
+
+/*
+ * Change Role ID while running (SET ROLE)
+ *
+ * If roleid is InvalidOid, we are doing SET ROLE NONE: revert to the
+ * session user authorization. In this case the is_superuser argument
+ * is ignored.
+ *
+ * When roleid is not InvalidOid, the caller must have checked whether
+ * the session user has permission to become that role.  (We cannot check
+ * here because this routine must be able to execute in a failed transaction
+ * to restore a prior value of the ROLE GUC variable.)
+ */
+void
+SetCurrentRoleId(Oid roleid, bool is_superuser)
+{
+       /*
+        * Get correct info if it's SET ROLE NONE
+        *
+        * If SessionUserId hasn't been set yet, just do nothing --- the eventual
+        * SetSessionUserId call will fix everything.  This is needed since we
+        * will get called during GUC initialization.
+        */
+       if (!OidIsValid(roleid))
+       {
+               if (!OidIsValid(SessionUserId))
+                       return;
+
+               roleid = SessionUserId;
+               is_superuser = SessionUserIsSuperuser;
+
+               SetRoleIsActive = false;
+       }
+       else
+               SetRoleIsActive = true;
 
-       userid = get_usesysid(username);
+       SetOuterUserId(roleid);
 
-       SetSessionUserId(userid);
-       SetUserId(userid);
+       SetConfigOption("is_superuser",
+                                       is_superuser ? "on" : "off",
+                                       PGC_INTERNAL, PGC_S_OVERRIDE);
 }
 
 
 /*
- * Get user name from user id
+ * Get user name from user oid
  */
 char *
-GetUserName(Oid userid)
+GetUserNameFromId(Oid roleid)
 {
        HeapTuple       tuple;
        char       *result;
 
-       tuple = SearchSysCache(SHADOWSYSID,
-                                                  ObjectIdGetDatum(userid),
+       tuple = SearchSysCache(AUTHOID,
+                                                  ObjectIdGetDatum(roleid),
                                                   0, 0, 0);
        if (!HeapTupleIsValid(tuple))
-               elog(ERROR, "invalid user id %u", (unsigned) userid);
+               ereport(ERROR,
+                               (errcode(ERRCODE_UNDEFINED_OBJECT),
+                                errmsg("invalid role OID: %u", roleid)));
 
-       result = pstrdup(NameStr(((Form_pg_shadow) GETSTRUCT(tuple))->usename));
+       result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
 
        ReleaseSysCache(tuple);
        return result;
 }
 
 
-
 /*-------------------------------------------------------------------------
  *                             Interlock-file support
  *
@@ -708,20 +632,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)
 {
@@ -734,14 +664,17 @@ CreateLockFile(const char *filename, bool amPostmaster,
        pid_t           my_pid = getpid();
 
        /*
-        * We need a loop here because of race conditions.      But don't loop
-        * forever (for example, a non-writable $PGDATA directory might cause
-        * a failure that won't go away).  100 tries seems like plenty.
+        * We need a loop here because of race conditions.      But don't loop forever
+        * (for example, a non-writable $PGDATA directory might cause a failure
+        * that won't go away).  100 tries seems like plenty.
         */
        for (ntries = 0;; ntries++)
        {
                /*
                 * Try to create the lock file --- O_EXCL makes this atomic.
+                *
+                * Think not to make the file protection weaker than 0600.      See
+                * comments below.
                 */
                fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
                if (fd >= 0)
@@ -751,7 +684,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
@@ -762,10 +698,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);
+               if ((len = read(fd, buffer, sizeof(buffer) - 1)) < 0)
+                       ereport(FATAL,
+                                       (errcode_for_file_access(),
+                                        errmsg("could not read lock file \"%s\": %m",
+                                                       filename)));
                close(fd);
 
                buffer[len] = '\0';
@@ -775,85 +717,123 @@ 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\": \"%s\"",
+                                filename, buffer);
 
                /*
                 * Check to see if the other process still exists
                 *
+                * If the PID in the lockfile is our own PID or our parent's PID, then
+                * the file must be stale (probably left over from a previous system
+                * boot cycle).  We need this test because of the likelihood that a
+                * reboot will assign exactly the same PID as we had in the previous
+                * reboot.      Also, if there is just one more process launch in this
+                * reboot than in the previous one, the lockfile might mention our
+                * parent's PID.  We can reject that since we'd never be launched
+                * directly by a competing postmaster.  We can't detect grandparent
+                * processes unfortunately, but if the init script is written
+                * carefully then all but the immediate parent shell will be
+                * root-owned processes and so the kill test will fail with EPERM.
+                *
+                * We can treat the EPERM-error case as okay because that error
+                * implies that the existing process has a different userid than we
+                * do, which means it cannot be a competing postmaster.  A postmaster
+                * cannot successfully attach to a data directory owned by a userid
+                * other than its own.  (This is now checked directly in
+                * checkDataDir(), but has been true for a long time because of the
+                * restriction that the data directory isn't group- or
+                * world-accessible.)  Also, since we create the lockfiles mode 600,
+                * we'd have failed above if the lockfile belonged to another userid
+                * --- which means that whatever process kill() is reporting about
+                * isn't the one that made the lockfile.  (NOTE: this last
+                * consideration is the only one that keeps us from blowing away a
+                * Unix socket file belonging to an instance of Postgres being run by
+                * someone else, at least on machines where /tmp hasn't got a
+                * stickybit.)
+                *
+                * Windows hasn't got getppid(), but doesn't need it since it's not
+                * using real kill() either...
+                *
                 * Normally kill() will fail with ESRCH if the given PID doesn't
-                * exist.  BeOS returns EINVAL for some silly reason, however.
+                * exist.
                 */
-               if (other_pid != my_pid)
+               if (other_pid != my_pid
+#ifndef WIN32
+                       && other_pid != getppid()
+#endif
+                       )
                {
                        if (kill(other_pid, 0) == 0 ||
-                               (errno != ESRCH
-#ifdef __BEOS__
-                                && errno != EINVAL
-#endif
-                                ))
+                               (errno != ESRCH && errno != EPERM))
                        {
                                /* 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 ?
+                                                (encoded_pid < 0 ?
+                                                 errhint("Is another postgres (PID %d) running in data directory \"%s\"?",
+                                                                 (int) other_pid, refName) :
+                                                 errhint("Is another postmaster (PID %d) running in data directory \"%s\"?",
+                                                                 (int) other_pid, refName)) :
+                                                (encoded_pid < 0 ?
+                                                 errhint("Is another postgres (PID %d) using socket file \"%s\"?",
+                                                                 (int) other_pid, refName) :
+                                                 errhint("Is another postmaster (PID %d) using socket file \"%s\"?",
+                                                                 (int) other_pid, refName))));
                        }
                }
 
                /*
-                * No, the creating process did not exist.      However, it could be
-                * that the postmaster crashed (or more likely was kill -9'd by a
-                * clueless admin) but has left orphan backends behind.  Check for
-                * this by looking to see if there is an associated shmem segment
-                * that is still in use.
+                * No, the creating process did not exist.      However, it could be that
+                * the postmaster crashed (or more likely was kill -9'd by a clueless
+                * admin) but has left orphan backends behind.  Check for this by
+                * looking to see if there is an associated shmem segment that is
+                * still in use.
                 */
                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 "
+                                                                       "server processes still running, remove "
+                                                                                "the shared memory block with "
+                                                                         "the command \"ipcclean\", \"ipcrm\", "
+                                                                                "or just delete the file \"%s\".",
+                                                                                filename)));
                                }
                        }
                }
 
                /*
-                * Looks like nobody's home.  Unlink the file and try again to
-                * create it.  Need a loop because of possible race condition
-                * against other would-be creators.
+                * Looks like nobody's home.  Unlink the file and try again to create
+                * it.  Need a loop because of possible race condition 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 "
+                                                  "it could not be removed. Please remove the file "
+                                                        "by hand and try again.")));
        }
 
        /*
@@ -871,104 +851,128 @@ 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)));
+       }
+       if (close(fd))
+       {
+               int                     save_errno = errno;
+
+               unlink(filename);
+               errno = save_errno;
+               ereport(FATAL,
+                               (errcode_for_file_access(),
+                                errmsg("could not write lock file \"%s\": %m", filename)));
        }
-       close(fd);
 
        /*
         * Arrange for automatic removal of lockfile at proc_exit.
         */
        on_proc_exit(UnlinkLockFile, PointerGetDatum(strdup(filename)));
-
-       return true;                            /* Success! */
 }
 
-bool
-CreateDataDirLockFile(const char *datadir, bool amPostmaster)
+/*
+ * Create the data directory lockfile.
+ *
+ * When this is called, we must have already switched the working
+ * directory to DataDir, so we can just use a relative path.  This
+ * helps ensure that we are locking the directory we should be.
+ */
+void
+CreateDataDirLockFile(bool amPostmaster)
 {
-       char            lockfile[MAXPGPATH];
-
-       snprintf(lockfile, sizeof(lockfile), "%s/postmaster.pid", datadir);
-       if (!CreateLockFile(lockfile, amPostmaster, true, datadir))
-               return false;
-       /* Save name of lockfile for RecordSharedMemoryInLockFile */
-       strcpy(directoryLockFile, lockfile);
-       return true;
+       CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, true, DataDir);
 }
 
-bool
+/*
+ * Create a lockfile for the specified Unix socket file.
+ */
+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 */
        }
 }
 
 /*
  * Append information about a shared memory segment to the data directory
- * lock file (if we have created one).
+ * lock file.
  *
  * 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;
        char       *ptr;
        char            buffer[BLCKSZ];
 
-       /*
-        * Do nothing if we did not create a lockfile (probably because we are
-        * running standalone).
-        */
-       if (directoryLockFile[0] == '\0')
-               return;
-
-       fd = open(directoryLockFile, O_RDWR | PG_BINARY, 0);
+       fd = open(DIRECTORY_LOCK_FILE, 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 open file \"%s\": %m",
+                                               DIRECTORY_LOCK_FILE)));
                return;
        }
        len = read(fd, buffer, sizeof(buffer) - 100);
-       if (len <= 0)
+       if (len < 0)
        {
-               elog(LOG, "Failed to read %s: %m", directoryLockFile);
+               ereport(LOG,
+                               (errcode_for_file_access(),
+                                errmsg("could not read from file \"%s\": %m",
+                                               DIRECTORY_LOCK_FILE)));
                close(fd);
                return;
        }
@@ -981,18 +985,17 @@ RecordSharedMemoryInLockFile(IpcMemoryKey shmKey, IpcMemoryId shmId)
        if (ptr == NULL ||
                (ptr = strchr(ptr + 1, '\n')) == NULL)
        {
-               elog(LOG, "Bogus data in %s", directoryLockFile);
+               elog(LOG, "bogus data in \"%s\"", DIRECTORY_LOCK_FILE);
                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
@@ -1006,11 +1009,20 @@ RecordSharedMemoryInLockFile(IpcMemoryKey shmKey, IpcMemoryId shmId)
                /* 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 to file \"%s\": %m",
+                                               DIRECTORY_LOCK_FILE)));
                close(fd);
                return;
        }
-       close(fd);
+       if (close(fd))
+       {
+               ereport(LOG,
+                               (errcode_for_file_access(),
+                                errmsg("could not write to file \"%s\": %m",
+                                               DIRECTORY_LOCK_FILE)));
+       }
 }
 
 
@@ -1023,7 +1035,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)
@@ -1042,25 +1054,134 @@ 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 file \"%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
+ *-------------------------------------------------------------------------
+ */
+
+/* 
+ * GUC variables: lists of library names to be preloaded at postmaster
+ * start and at backend start
+ */
+char      *shared_preload_libraries_string = NULL;
+char      *local_preload_libraries_string = NULL;
+
+/*
+ * load the shared libraries listed in 'libraries'
+ *
+ * 'gucname': name of GUC variable, for error reports
+ * 'restricted': if true, force libraries to be in $libdir/plugins/
+ */
+static void
+load_libraries(const char *libraries, const char *gucname, bool restricted)
+{
+       char       *rawstring;
+       List       *elemlist;
+       ListCell   *l;
+
+       if (libraries == NULL || libraries[0] == '\0')
+               return;                                 /* nothing to do */
+
+       /* Need a modifiable copy of string */
+       rawstring = pstrdup(libraries);
+
+       /* Parse string into list of identifiers */
+       if (!SplitIdentifierString(rawstring, ',', &elemlist))
+       {
+               /* syntax error in list */
+               pfree(rawstring);
+               list_free(elemlist);
+               ereport(LOG,
+                               (errcode(ERRCODE_SYNTAX_ERROR),
+                                errmsg("invalid list syntax in parameter \"%s\"",
+                                               gucname)));
+               return;
+       }
+
+       foreach(l, elemlist)
+       {
+               char       *tok = (char *) lfirst(l);
+               char       *filename;
+
+               filename = pstrdup(tok);
+               canonicalize_path(filename);
+               /* If restricting, insert $libdir/plugins if not mentioned already */
+               if (restricted && first_dir_separator(filename) == NULL)
+               {
+                       char   *expanded;
+
+                       expanded = palloc(strlen("$libdir/plugins/") + strlen(filename) + 1);
+                       strcpy(expanded, "$libdir/plugins/");
+                       strcat(expanded, filename);
+                       pfree(filename);
+                       filename = expanded;
+               }
+               load_file(filename, restricted);
+               ereport(LOG,
+                               (errmsg("loaded library \"%s\"", filename)));
+               pfree(filename);
+       }
+
+       pfree(rawstring);
+       list_free(elemlist);
+}
+
+/*
+ * process any libraries that should be preloaded at postmaster start
+ */
+void
+process_shared_preload_libraries(void)
+{
+       load_libraries(shared_preload_libraries_string,
+                                  "shared_preload_libraries",
+                                  false);
+}
+
+/*
+ * process any libraries that should be preloaded at backend start
+ */
+void
+process_local_preload_libraries(void)
+{
+       load_libraries(local_preload_libraries_string,
+                                  "local_preload_libraries",
+                                  true);
 }