LCOV - code coverage report
Current view: top level - src/backend/utils/init - postinit.c (source / functions) Coverage Total Hit
Test: PostgreSQL 19devel Lines: 91.4 % 371 339
Test Date: 2026-03-19 23:16:18 Functions: 95.5 % 22 21
Legend: Lines:     hit not hit

            Line data    Source code
       1              : /*-------------------------------------------------------------------------
       2              :  *
       3              :  * postinit.c
       4              :  *    postgres initialization utilities
       5              :  *
       6              :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
       7              :  * Portions Copyright (c) 1994, Regents of the University of California
       8              :  *
       9              :  *
      10              :  * IDENTIFICATION
      11              :  *    src/backend/utils/init/postinit.c
      12              :  *
      13              :  *
      14              :  *-------------------------------------------------------------------------
      15              :  */
      16              : #include "postgres.h"
      17              : 
      18              : #include <ctype.h>
      19              : #include <fcntl.h>
      20              : #include <unistd.h>
      21              : 
      22              : #include "access/genam.h"
      23              : #include "access/heapam.h"
      24              : #include "access/htup_details.h"
      25              : #include "access/session.h"
      26              : #include "access/tableam.h"
      27              : #include "access/xact.h"
      28              : #include "access/xlog.h"
      29              : #include "access/xloginsert.h"
      30              : #include "catalog/namespace.h"
      31              : #include "catalog/pg_authid.h"
      32              : #include "catalog/pg_collation.h"
      33              : #include "catalog/pg_database.h"
      34              : #include "catalog/pg_db_role_setting.h"
      35              : #include "catalog/pg_tablespace.h"
      36              : #include "libpq/auth.h"
      37              : #include "libpq/libpq-be.h"
      38              : #include "mb/pg_wchar.h"
      39              : #include "miscadmin.h"
      40              : #include "pgstat.h"
      41              : #include "port/pg_bitutils.h"
      42              : #include "postmaster/autovacuum.h"
      43              : #include "postmaster/postmaster.h"
      44              : #include "replication/slot.h"
      45              : #include "replication/slotsync.h"
      46              : #include "replication/walsender.h"
      47              : #include "storage/aio_subsys.h"
      48              : #include "storage/bufmgr.h"
      49              : #include "storage/fd.h"
      50              : #include "storage/ipc.h"
      51              : #include "storage/lmgr.h"
      52              : #include "storage/proc.h"
      53              : #include "storage/procarray.h"
      54              : #include "storage/procnumber.h"
      55              : #include "storage/procsignal.h"
      56              : #include "storage/sinvaladt.h"
      57              : #include "storage/smgr.h"
      58              : #include "storage/sync.h"
      59              : #include "tcop/backend_startup.h"
      60              : #include "tcop/tcopprot.h"
      61              : #include "utils/acl.h"
      62              : #include "utils/builtins.h"
      63              : #include "utils/fmgroids.h"
      64              : #include "utils/guc_hooks.h"
      65              : #include "utils/injection_point.h"
      66              : #include "utils/memutils.h"
      67              : #include "utils/pg_locale.h"
      68              : #include "utils/portal.h"
      69              : #include "utils/ps_status.h"
      70              : #include "utils/snapmgr.h"
      71              : #include "utils/syscache.h"
      72              : #include "utils/timeout.h"
      73              : 
      74              : /* has this backend called EmitConnectionWarnings()? */
      75              : static bool ConnectionWarningsEmitted;
      76              : 
      77              : /* content of warnings to send via EmitConnectionWarnings() */
      78              : static List *ConnectionWarningMessages;
      79              : static List *ConnectionWarningDetails;
      80              : 
      81              : static HeapTuple GetDatabaseTuple(const char *dbname);
      82              : static HeapTuple GetDatabaseTupleByOid(Oid dboid);
      83              : static void PerformAuthentication(Port *port);
      84              : static void CheckMyDatabase(const char *name, bool am_superuser, bool override_allow_connections);
      85              : static void ShutdownPostgres(int code, Datum arg);
      86              : static void StatementTimeoutHandler(void);
      87              : static void LockTimeoutHandler(void);
      88              : static void IdleInTransactionSessionTimeoutHandler(void);
      89              : static void TransactionTimeoutHandler(void);
      90              : static void IdleSessionTimeoutHandler(void);
      91              : static void IdleStatsUpdateTimeoutHandler(void);
      92              : static void ClientCheckTimeoutHandler(void);
      93              : static bool ThereIsAtLeastOneRole(void);
      94              : static void process_startup_options(Port *port, bool am_superuser);
      95              : static void process_settings(Oid databaseid, Oid roleid);
      96              : static void EmitConnectionWarnings(void);
      97              : 
      98              : 
      99              : /*** InitPostgres support ***/
     100              : 
     101              : 
     102              : /*
     103              :  * GetDatabaseTuple -- fetch the pg_database row for a database
     104              :  *
     105              :  * This is used during backend startup when we don't yet have any access to
     106              :  * system catalogs in general.  In the worst case, we can seqscan pg_database
     107              :  * using nothing but the hard-wired descriptor that relcache.c creates for
     108              :  * pg_database.  In more typical cases, relcache.c was able to load
     109              :  * descriptors for both pg_database and its indexes from the shared relcache
     110              :  * cache file, and so we can do an indexscan.  criticalSharedRelcachesBuilt
     111              :  * tells whether we got the cached descriptors.
     112              :  */
     113              : static HeapTuple
     114        13827 : GetDatabaseTuple(const char *dbname)
     115              : {
     116              :     HeapTuple   tuple;
     117              :     Relation    relation;
     118              :     SysScanDesc scan;
     119              :     ScanKeyData key[1];
     120              : 
     121              :     /*
     122              :      * form a scan key
     123              :      */
     124        13827 :     ScanKeyInit(&key[0],
     125              :                 Anum_pg_database_datname,
     126              :                 BTEqualStrategyNumber, F_NAMEEQ,
     127              :                 CStringGetDatum(dbname));
     128              : 
     129              :     /*
     130              :      * Open pg_database and fetch a tuple.  Force heap scan if we haven't yet
     131              :      * built the critical shared relcache entries (i.e., we're starting up
     132              :      * without a shared relcache cache file).
     133              :      */
     134        13827 :     relation = table_open(DatabaseRelationId, AccessShareLock);
     135        13827 :     scan = systable_beginscan(relation, DatabaseNameIndexId,
     136              :                               criticalSharedRelcachesBuilt,
     137              :                               NULL,
     138              :                               1, key);
     139              : 
     140        13827 :     tuple = systable_getnext(scan);
     141              : 
     142              :     /* Must copy tuple before releasing buffer */
     143        13827 :     if (HeapTupleIsValid(tuple))
     144        13817 :         tuple = heap_copytuple(tuple);
     145              : 
     146              :     /* all done */
     147        13827 :     systable_endscan(scan);
     148        13827 :     table_close(relation, AccessShareLock);
     149              : 
     150        13827 :     return tuple;
     151              : }
     152              : 
     153              : /*
     154              :  * GetDatabaseTupleByOid -- as above, but search by database OID
     155              :  */
     156              : static HeapTuple
     157        17917 : GetDatabaseTupleByOid(Oid dboid)
     158              : {
     159              :     HeapTuple   tuple;
     160              :     Relation    relation;
     161              :     SysScanDesc scan;
     162              :     ScanKeyData key[1];
     163              : 
     164              :     /*
     165              :      * form a scan key
     166              :      */
     167        17917 :     ScanKeyInit(&key[0],
     168              :                 Anum_pg_database_oid,
     169              :                 BTEqualStrategyNumber, F_OIDEQ,
     170              :                 ObjectIdGetDatum(dboid));
     171              : 
     172              :     /*
     173              :      * Open pg_database and fetch a tuple.  Force heap scan if we haven't yet
     174              :      * built the critical shared relcache entries (i.e., we're starting up
     175              :      * without a shared relcache cache file).
     176              :      */
     177        17917 :     relation = table_open(DatabaseRelationId, AccessShareLock);
     178        17917 :     scan = systable_beginscan(relation, DatabaseOidIndexId,
     179              :                               criticalSharedRelcachesBuilt,
     180              :                               NULL,
     181              :                               1, key);
     182              : 
     183        17917 :     tuple = systable_getnext(scan);
     184              : 
     185              :     /* Must copy tuple before releasing buffer */
     186        17917 :     if (HeapTupleIsValid(tuple))
     187        17917 :         tuple = heap_copytuple(tuple);
     188              : 
     189              :     /* all done */
     190        17917 :     systable_endscan(scan);
     191        17917 :     table_close(relation, AccessShareLock);
     192              : 
     193        17917 :     return tuple;
     194              : }
     195              : 
     196              : 
     197              : /*
     198              :  * PerformAuthentication -- authenticate a remote client
     199              :  *
     200              :  * returns: nothing.  Will not return at all if there's any failure.
     201              :  */
     202              : static void
     203        14314 : PerformAuthentication(Port *port)
     204              : {
     205              :     /* This should be set already, but let's make sure */
     206        14314 :     ClientAuthInProgress = true;    /* limit visibility of log messages */
     207              : 
     208              :     /*
     209              :      * In EXEC_BACKEND case, we didn't inherit the contents of pg_hba.conf
     210              :      * etcetera from the postmaster, and have to load them ourselves.
     211              :      *
     212              :      * FIXME: [fork/exec] Ugh.  Is there a way around this overhead?
     213              :      */
     214              : #ifdef EXEC_BACKEND
     215              : 
     216              :     /*
     217              :      * load_hba() and load_ident() want to work within the PostmasterContext,
     218              :      * so create that if it doesn't exist (which it won't).  We'll delete it
     219              :      * again later, in PostgresMain.
     220              :      */
     221              :     if (PostmasterContext == NULL)
     222              :         PostmasterContext = AllocSetContextCreate(TopMemoryContext,
     223              :                                                   "Postmaster",
     224              :                                                   ALLOCSET_DEFAULT_SIZES);
     225              : 
     226              :     if (!load_hba())
     227              :     {
     228              :         /*
     229              :          * It makes no sense to continue if we fail to load the HBA file,
     230              :          * since there is no way to connect to the database in this case.
     231              :          */
     232              :         ereport(FATAL,
     233              :         /* translator: %s is a configuration file */
     234              :                 (errmsg("could not load %s", HbaFileName)));
     235              :     }
     236              : 
     237              :     if (!load_ident())
     238              :     {
     239              :         /*
     240              :          * It is ok to continue if we fail to load the IDENT file, although it
     241              :          * means that you cannot log in using any of the authentication
     242              :          * methods that need a user name mapping. load_ident() already logged
     243              :          * the details of error to the log.
     244              :          */
     245              :     }
     246              : #endif
     247              : 
     248              :     /* Capture authentication start time for logging */
     249        14314 :     conn_timing.auth_start = GetCurrentTimestamp();
     250              : 
     251              :     /*
     252              :      * Set up a timeout in case a buggy or malicious client fails to respond
     253              :      * during authentication.  Since we're inside a transaction and might do
     254              :      * database access, we have to use the statement_timeout infrastructure.
     255              :      */
     256        14314 :     enable_timeout_after(STATEMENT_TIMEOUT, AuthenticationTimeout * 1000);
     257              : 
     258              :     /*
     259              :      * Now perform authentication exchange.
     260              :      */
     261        14314 :     set_ps_display("authentication");
     262        14314 :     ClientAuthentication(port); /* might not return, if failure */
     263              : 
     264              :     /*
     265              :      * Done with authentication.  Disable the timeout, and log if needed.
     266              :      */
     267        14240 :     disable_timeout(STATEMENT_TIMEOUT, false);
     268              : 
     269              :     /* Capture authentication end time for logging */
     270        14240 :     conn_timing.auth_end = GetCurrentTimestamp();
     271              : 
     272        14240 :     if (log_connections & LOG_CONNECTION_AUTHORIZATION)
     273              :     {
     274              :         StringInfoData logmsg;
     275              : 
     276          242 :         initStringInfo(&logmsg);
     277          242 :         if (am_walsender)
     278            0 :             appendStringInfo(&logmsg, _("replication connection authorized: user=%s"),
     279              :                              port->user_name);
     280              :         else
     281          242 :             appendStringInfo(&logmsg, _("connection authorized: user=%s"),
     282              :                              port->user_name);
     283          242 :         if (!am_walsender)
     284          242 :             appendStringInfo(&logmsg, _(" database=%s"), port->database_name);
     285              : 
     286          242 :         if (port->application_name != NULL)
     287          242 :             appendStringInfo(&logmsg, _(" application_name=%s"),
     288              :                              port->application_name);
     289              : 
     290              : #ifdef USE_SSL
     291          242 :         if (port->ssl_in_use)
     292          111 :             appendStringInfo(&logmsg, _(" SSL enabled (protocol=%s, cipher=%s, bits=%d)"),
     293              :                              be_tls_get_version(port),
     294              :                              be_tls_get_cipher(port),
     295              :                              be_tls_get_cipher_bits(port));
     296              : #endif
     297              : #ifdef ENABLE_GSS
     298              :         if (port->gss)
     299              :         {
     300              :             const char *princ = be_gssapi_get_princ(port);
     301              : 
     302              :             if (princ)
     303              :                 appendStringInfo(&logmsg,
     304              :                                  _(" GSS (authenticated=%s, encrypted=%s, delegated_credentials=%s, principal=%s)"),
     305              :                                  be_gssapi_get_auth(port) ? _("yes") : _("no"),
     306              :                                  be_gssapi_get_enc(port) ? _("yes") : _("no"),
     307              :                                  be_gssapi_get_delegation(port) ? _("yes") : _("no"),
     308              :                                  princ);
     309              :             else
     310              :                 appendStringInfo(&logmsg,
     311              :                                  _(" GSS (authenticated=%s, encrypted=%s, delegated_credentials=%s)"),
     312              :                                  be_gssapi_get_auth(port) ? _("yes") : _("no"),
     313              :                                  be_gssapi_get_enc(port) ? _("yes") : _("no"),
     314              :                                  be_gssapi_get_delegation(port) ? _("yes") : _("no"));
     315              :         }
     316              : #endif
     317              : 
     318          242 :         ereport(LOG, errmsg_internal("%s", logmsg.data));
     319          242 :         pfree(logmsg.data);
     320              :     }
     321              : 
     322        14240 :     set_ps_display("startup");
     323              : 
     324        14240 :     ClientAuthInProgress = false;   /* client_min_messages is active now */
     325        14240 : }
     326              : 
     327              : 
     328              : /*
     329              :  * CheckMyDatabase -- fetch information from the pg_database entry for our DB
     330              :  */
     331              : static void
     332        17910 : CheckMyDatabase(const char *name, bool am_superuser, bool override_allow_connections)
     333              : {
     334              :     HeapTuple   tup;
     335              :     Form_pg_database dbform;
     336              :     Datum       datum;
     337              :     bool        isnull;
     338              :     char       *collate;
     339              :     char       *ctype;
     340              : 
     341              :     /* Fetch our pg_database row normally, via syscache */
     342        17910 :     tup = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));
     343        17910 :     if (!HeapTupleIsValid(tup))
     344            0 :         elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
     345        17910 :     dbform = (Form_pg_database) GETSTRUCT(tup);
     346              : 
     347              :     /* This recheck is strictly paranoia */
     348        17910 :     if (strcmp(name, NameStr(dbform->datname)) != 0)
     349            0 :         ereport(FATAL,
     350              :                 (errcode(ERRCODE_UNDEFINED_DATABASE),
     351              :                  errmsg("database \"%s\" has disappeared from pg_database",
     352              :                         name),
     353              :                  errdetail("Database OID %u now seems to belong to \"%s\".",
     354              :                            MyDatabaseId, NameStr(dbform->datname))));
     355              : 
     356              :     /*
     357              :      * Check permissions to connect to the database.
     358              :      *
     359              :      * These checks are not enforced when in standalone mode, so that there is
     360              :      * a way to recover from disabling all access to all databases, for
     361              :      * example "UPDATE pg_database SET datallowconn = false;".
     362              :      */
     363        17910 :     if (IsUnderPostmaster)
     364              :     {
     365              :         /*
     366              :          * Check that the database is currently allowing connections.
     367              :          * (Background processes can override this test and the next one by
     368              :          * setting override_allow_connections.)
     369              :          */
     370        17840 :         if (!dbform->datallowconn && !override_allow_connections)
     371            1 :             ereport(FATAL,
     372              :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     373              :                      errmsg("database \"%s\" is not currently accepting connections",
     374              :                             name)));
     375              : 
     376              :         /*
     377              :          * Check privilege to connect to the database.  (The am_superuser test
     378              :          * is redundant, but since we have the flag, might as well check it
     379              :          * and save a few cycles.)
     380              :          */
     381        18148 :         if (!am_superuser && !override_allow_connections &&
     382          309 :             object_aclcheck(DatabaseRelationId, MyDatabaseId, GetUserId(),
     383              :                             ACL_CONNECT) != ACLCHECK_OK)
     384            0 :             ereport(FATAL,
     385              :                     (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     386              :                      errmsg("permission denied for database \"%s\"", name),
     387              :                      errdetail("User does not have CONNECT privilege.")));
     388              : 
     389              :         /*
     390              :          * Check connection limit for this database.  We enforce the limit
     391              :          * only for regular backends, since other process types have their own
     392              :          * PGPROC pools.
     393              :          *
     394              :          * There is a race condition here --- we create our PGPROC before
     395              :          * checking for other PGPROCs.  If two backends did this at about the
     396              :          * same time, they might both think they were over the limit, while
     397              :          * ideally one should succeed and one fail.  Getting that to work
     398              :          * exactly seems more trouble than it is worth, however; instead we
     399              :          * just document that the connection limit is approximate.
     400              :          */
     401        17839 :         if (dbform->datconnlimit >= 0 &&
     402            0 :             AmRegularBackendProcess() &&
     403            0 :             !am_superuser &&
     404            0 :             CountDBConnections(MyDatabaseId) > dbform->datconnlimit)
     405            0 :             ereport(FATAL,
     406              :                     (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
     407              :                      errmsg("too many connections for database \"%s\"",
     408              :                             name)));
     409              :     }
     410              : 
     411              :     /*
     412              :      * OK, we're golden.  Next to-do item is to save the encoding info out of
     413              :      * the pg_database tuple.
     414              :      */
     415        17909 :     SetDatabaseEncoding(dbform->encoding);
     416              :     /* Record it as a GUC internal option, too */
     417        17909 :     SetConfigOption("server_encoding", GetDatabaseEncodingName(),
     418              :                     PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
     419              :     /* If we have no other source of client_encoding, use server encoding */
     420        17909 :     SetConfigOption("client_encoding", GetDatabaseEncodingName(),
     421              :                     PGC_BACKEND, PGC_S_DYNAMIC_DEFAULT);
     422              : 
     423              :     /* assign locale variables */
     424        17909 :     datum = SysCacheGetAttrNotNull(DATABASEOID, tup, Anum_pg_database_datcollate);
     425        17909 :     collate = TextDatumGetCString(datum);
     426        17909 :     datum = SysCacheGetAttrNotNull(DATABASEOID, tup, Anum_pg_database_datctype);
     427        17909 :     ctype = TextDatumGetCString(datum);
     428              : 
     429              :     /*
     430              :      * Historically, we set LC_COLLATE from datcollate, as well. That's no
     431              :      * longer necessary because all collation behavior is handled through
     432              :      * pg_locale_t.
     433              :      */
     434              : 
     435        17909 :     if (pg_perm_setlocale(LC_CTYPE, ctype) == NULL)
     436            0 :         ereport(FATAL,
     437              :                 (errmsg("database locale is incompatible with operating system"),
     438              :                  errdetail("The database was initialized with LC_CTYPE \"%s\", "
     439              :                            " which is not recognized by setlocale().", ctype),
     440              :                  errhint("Recreate the database with another locale or install the missing locale.")));
     441              : 
     442        17909 :     init_database_collation();
     443              : 
     444              :     /*
     445              :      * Check collation version.  See similar code in
     446              :      * pg_newlocale_from_collation().  Note that here we warn instead of error
     447              :      * in any case, so that we don't prevent connecting.
     448              :      */
     449        17907 :     datum = SysCacheGetAttr(DATABASEOID, tup, Anum_pg_database_datcollversion,
     450              :                             &isnull);
     451        17907 :     if (!isnull)
     452              :     {
     453              :         char       *actual_versionstr;
     454              :         char       *collversionstr;
     455              :         char       *locale;
     456              : 
     457        17083 :         collversionstr = TextDatumGetCString(datum);
     458              : 
     459        17083 :         if (dbform->datlocprovider == COLLPROVIDER_LIBC)
     460        16159 :             locale = collate;
     461              :         else
     462              :         {
     463          924 :             datum = SysCacheGetAttrNotNull(DATABASEOID, tup, Anum_pg_database_datlocale);
     464          924 :             locale = TextDatumGetCString(datum);
     465              :         }
     466              : 
     467        17083 :         actual_versionstr = get_collation_actual_version(dbform->datlocprovider, locale);
     468        17083 :         if (!actual_versionstr)
     469              :             /* should not happen */
     470            0 :             elog(WARNING,
     471              :                  "database \"%s\" has no actual collation version, but a version was recorded",
     472              :                  name);
     473        17083 :         else if (strcmp(actual_versionstr, collversionstr) != 0)
     474            0 :             ereport(WARNING,
     475              :                     (errmsg("database \"%s\" has a collation version mismatch",
     476              :                             name),
     477              :                      errdetail("The database was created using collation version %s, "
     478              :                                "but the operating system provides version %s.",
     479              :                                collversionstr, actual_versionstr),
     480              :                      errhint("Rebuild all objects in this database that use the default collation and run "
     481              :                              "ALTER DATABASE %s REFRESH COLLATION VERSION, "
     482              :                              "or build PostgreSQL with the right library version.",
     483              :                              quote_identifier(name))));
     484              :     }
     485              : 
     486        17907 :     ReleaseSysCache(tup);
     487        17907 : }
     488              : 
     489              : 
     490              : /*
     491              :  * pg_split_opts -- split a string of options and append it to an argv array
     492              :  *
     493              :  * The caller is responsible for ensuring the argv array is large enough.  The
     494              :  * maximum possible number of arguments added by this routine is
     495              :  * (strlen(optstr) + 1) / 2.
     496              :  *
     497              :  * Because some option values can contain spaces we allow escaping using
     498              :  * backslashes, with \\ representing a literal backslash.
     499              :  */
     500              : void
     501         4298 : pg_split_opts(char **argv, int *argcp, const char *optstr)
     502              : {
     503              :     StringInfoData s;
     504              : 
     505         4298 :     initStringInfo(&s);
     506              : 
     507        15690 :     while (*optstr)
     508              :     {
     509        11392 :         bool        last_was_escape = false;
     510              : 
     511        11392 :         resetStringInfo(&s);
     512              : 
     513              :         /* skip over leading space */
     514        21801 :         while (isspace((unsigned char) *optstr))
     515        10409 :             optstr++;
     516              : 
     517        11392 :         if (*optstr == '\0')
     518            0 :             break;
     519              : 
     520              :         /*
     521              :          * Parse a single option, stopping at the first space, unless it's
     522              :          * escaped.
     523              :          */
     524       174290 :         while (*optstr)
     525              :         {
     526       169992 :             if (isspace((unsigned char) *optstr) && !last_was_escape)
     527         7094 :                 break;
     528              : 
     529       162898 :             if (!last_was_escape && *optstr == '\\')
     530           20 :                 last_was_escape = true;
     531              :             else
     532              :             {
     533       162878 :                 last_was_escape = false;
     534       162878 :                 appendStringInfoChar(&s, *optstr);
     535              :             }
     536              : 
     537       162898 :             optstr++;
     538              :         }
     539              : 
     540              :         /* now store the option in the next argv[] position */
     541        11392 :         argv[(*argcp)++] = pstrdup(s.data);
     542              :     }
     543              : 
     544         4298 :     pfree(s.data);
     545         4298 : }
     546              : 
     547              : /*
     548              :  * Initialize MaxBackends value from config options.
     549              :  *
     550              :  * This must be called after modules have had the chance to alter GUCs in
     551              :  * shared_preload_libraries and before shared memory size is determined.
     552              :  *
     553              :  * Note that in EXEC_BACKEND environment, the value is passed down from
     554              :  * postmaster to subprocesses via BackendParameters in SubPostmasterMain; only
     555              :  * postmaster itself and processes not under postmaster control should call
     556              :  * this.
     557              :  */
     558              : void
     559         1178 : InitializeMaxBackends(void)
     560              : {
     561              :     Assert(MaxBackends == 0);
     562              : 
     563              :     /* Note that this does not include "auxiliary" processes */
     564         1178 :     MaxBackends = MaxConnections + autovacuum_worker_slots +
     565         1178 :         max_worker_processes + max_wal_senders + NUM_SPECIAL_WORKER_PROCS;
     566              : 
     567         1178 :     if (MaxBackends > MAX_BACKENDS)
     568            0 :         ereport(ERROR,
     569              :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     570              :                  errmsg("too many server processes configured"),
     571              :                  errdetail("\"max_connections\" (%d) plus \"autovacuum_worker_slots\" (%d) plus \"max_worker_processes\" (%d) plus \"max_wal_senders\" (%d) must be less than %d.",
     572              :                            MaxConnections, autovacuum_worker_slots,
     573              :                            max_worker_processes, max_wal_senders,
     574              :                            MAX_BACKENDS - (NUM_SPECIAL_WORKER_PROCS - 1))));
     575         1178 : }
     576              : 
     577              : /*
     578              :  * Initialize the number of fast-path lock slots in PGPROC.
     579              :  *
     580              :  * This must be called after modules have had the chance to alter GUCs in
     581              :  * shared_preload_libraries and before shared memory size is determined.
     582              :  */
     583              : void
     584         1178 : InitializeFastPathLocks(void)
     585              : {
     586              :     /* Should be initialized only once. */
     587              :     Assert(FastPathLockGroupsPerBackend == 0);
     588              : 
     589              :     /*
     590              :      * Based on the max_locks_per_transaction GUC, as that's a good indicator
     591              :      * of the expected number of locks, figure out the value for
     592              :      * FastPathLockGroupsPerBackend.  This must be a power-of-two.  We cap the
     593              :      * value at FP_LOCK_GROUPS_PER_BACKEND_MAX and insist the value is at
     594              :      * least 1.
     595              :      *
     596              :      * The default max_locks_per_transaction = 64 means 4 groups by default.
     597              :      */
     598         1178 :     FastPathLockGroupsPerBackend =
     599         1178 :         Max(Min(pg_nextpower2_32(max_locks_per_xact) / FP_LOCK_SLOTS_PER_GROUP,
     600              :                 FP_LOCK_GROUPS_PER_BACKEND_MAX), 1);
     601              : 
     602              :     /* Validate we did get a power-of-two */
     603              :     Assert(FastPathLockGroupsPerBackend ==
     604              :            pg_nextpower2_32(FastPathLockGroupsPerBackend));
     605         1178 : }
     606              : 
     607              : /*
     608              :  * Early initialization of a backend (either standalone or under postmaster).
     609              :  * This happens even before InitPostgres.
     610              :  *
     611              :  * This is separate from InitPostgres because it is also called by auxiliary
     612              :  * processes, such as the background writer process, which may not call
     613              :  * InitPostgres at all.
     614              :  */
     615              : void
     616        24284 : BaseInit(void)
     617              : {
     618              :     Assert(MyProc != NULL);
     619              : 
     620              :     /*
     621              :      * Initialize our input/output/debugging file descriptors.
     622              :      */
     623        24284 :     DebugFileOpen();
     624              : 
     625              :     /*
     626              :      * Initialize file access. Done early so other subsystems can access
     627              :      * files.
     628              :      */
     629        24284 :     InitFileAccess();
     630              : 
     631              :     /*
     632              :      * Initialize statistics reporting. This needs to happen early to ensure
     633              :      * that pgstat's shutdown callback runs after the shutdown callbacks of
     634              :      * all subsystems that can produce stats (like e.g. transaction commits
     635              :      * can).
     636              :      */
     637        24284 :     pgstat_initialize();
     638              : 
     639              :     /*
     640              :      * Initialize AIO before infrastructure that might need to actually
     641              :      * execute AIO.
     642              :      */
     643        24284 :     pgaio_init_backend();
     644              : 
     645              :     /* Do local initialization of storage and buffer managers */
     646        24284 :     InitSync();
     647        24284 :     smgrinit();
     648        24284 :     InitBufferManagerAccess();
     649              : 
     650              :     /*
     651              :      * Initialize temporary file access after pgstat, so that the temporary
     652              :      * file shutdown hook can report temporary file statistics.
     653              :      */
     654        24284 :     InitTemporaryFileAccess();
     655              : 
     656              :     /*
     657              :      * Initialize local buffers for WAL record construction, in case we ever
     658              :      * try to insert XLOG.
     659              :      */
     660        24284 :     InitXLogInsert();
     661              : 
     662              :     /* Initialize lock manager's local structs */
     663        24284 :     InitLockManagerAccess();
     664              : 
     665              :     /* Initialize logical info WAL logging state */
     666        24284 :     InitializeProcessXLogLogicalInfo();
     667              : 
     668              :     /*
     669              :      * Initialize replication slots after pgstat. The exit hook might need to
     670              :      * drop ephemeral slots, which in turn triggers stats reporting.
     671              :      */
     672        24284 :     ReplicationSlotInitialize();
     673        24284 : }
     674              : 
     675              : 
     676              : /* --------------------------------
     677              :  * InitPostgres
     678              :  *      Initialize POSTGRES.
     679              :  *
     680              :  * Parameters:
     681              :  *  in_dbname, dboid: specify database to connect to, as described below
     682              :  *  username, useroid: specify role to connect as, as described below
     683              :  *  flags:
     684              :  *    - INIT_PG_LOAD_SESSION_LIBS to honor [session|local]_preload_libraries.
     685              :  *    - INIT_PG_OVERRIDE_ALLOW_CONNS to connect despite !datallowconn.
     686              :  *    - INIT_PG_OVERRIDE_ROLE_LOGIN to connect despite !rolcanlogin.
     687              :  *  out_dbname: optional output parameter, see below; pass NULL if not used
     688              :  *
     689              :  * The database can be specified by name, using the in_dbname parameter, or by
     690              :  * OID, using the dboid parameter.  Specify NULL or InvalidOid respectively
     691              :  * for the unused parameter.  If dboid is provided, the actual database
     692              :  * name can be returned to the caller in out_dbname.  If out_dbname isn't
     693              :  * NULL, it must point to a buffer of size NAMEDATALEN.
     694              :  *
     695              :  * Similarly, the role can be passed by name, using the username parameter,
     696              :  * or by OID using the useroid parameter.
     697              :  *
     698              :  * In bootstrap mode the database and username parameters are NULL/InvalidOid.
     699              :  * The autovacuum launcher process doesn't specify these parameters either,
     700              :  * because it only goes far enough to be able to read pg_database; it doesn't
     701              :  * connect to any particular database.  An autovacuum worker specifies a
     702              :  * database but not a username; conversely, a physical walsender specifies
     703              :  * username but not database.
     704              :  *
     705              :  * By convention, INIT_PG_LOAD_SESSION_LIBS should be passed in "flags" in
     706              :  * "interactive" sessions (including standalone backends), but not in
     707              :  * background processes such as autovacuum.  Note in particular that it
     708              :  * shouldn't be true in parallel worker processes; those have another
     709              :  * mechanism for replicating their leader's set of loaded libraries.
     710              :  *
     711              :  * We expect that InitProcess() was already called, so we already have a
     712              :  * PGPROC struct ... but it's not completely filled in yet.
     713              :  *
     714              :  * Note:
     715              :  *      Be very careful with the order of calls in the InitPostgres function.
     716              :  * --------------------------------
     717              :  */
     718              : void
     719        19482 : InitPostgres(const char *in_dbname, Oid dboid,
     720              :              const char *username, Oid useroid,
     721              :              bits32 flags,
     722              :              char *out_dbname)
     723              : {
     724        19482 :     bool        bootstrap = IsBootstrapProcessingMode();
     725              :     bool        am_superuser;
     726              :     char       *fullpath;
     727              :     char        dbname[NAMEDATALEN];
     728        19482 :     int         nfree = 0;
     729              : 
     730        19482 :     elog(DEBUG3, "InitPostgres");
     731              : 
     732              :     /*
     733              :      * Add my PGPROC struct to the ProcArray.
     734              :      *
     735              :      * Once I have done this, I am visible to other backends!
     736              :      */
     737        19482 :     InitProcessPhase2();
     738              : 
     739              :     /* Initialize status reporting */
     740        19482 :     pgstat_beinit();
     741              : 
     742              :     /*
     743              :      * And initialize an entry in the PgBackendStatus array.  That way, if
     744              :      * LWLocks or third-party authentication should happen to hang, it is
     745              :      * possible to retrieve some information about what is going on.
     746              :      */
     747        19482 :     if (!bootstrap)
     748              :     {
     749        19431 :         pgstat_bestart_initial();
     750        19431 :         INJECTION_POINT("init-pre-auth", NULL);
     751              :     }
     752              : 
     753              :     /*
     754              :      * Initialize my entry in the shared-invalidation manager's array of
     755              :      * per-backend data.
     756              :      */
     757        19482 :     SharedInvalBackendInit(false);
     758              : 
     759        19482 :     ProcSignalInit(MyCancelKey, MyCancelKeyLength);
     760              : 
     761              :     /*
     762              :      * Also set up timeout handlers needed for backend operation.  We need
     763              :      * these in every case except bootstrap.
     764              :      */
     765        19482 :     if (!bootstrap)
     766              :     {
     767        19431 :         RegisterTimeout(DEADLOCK_TIMEOUT, CheckDeadLockAlert);
     768        19431 :         RegisterTimeout(STATEMENT_TIMEOUT, StatementTimeoutHandler);
     769        19431 :         RegisterTimeout(LOCK_TIMEOUT, LockTimeoutHandler);
     770        19431 :         RegisterTimeout(IDLE_IN_TRANSACTION_SESSION_TIMEOUT,
     771              :                         IdleInTransactionSessionTimeoutHandler);
     772        19431 :         RegisterTimeout(TRANSACTION_TIMEOUT, TransactionTimeoutHandler);
     773        19431 :         RegisterTimeout(IDLE_SESSION_TIMEOUT, IdleSessionTimeoutHandler);
     774        19431 :         RegisterTimeout(CLIENT_CONNECTION_CHECK_TIMEOUT, ClientCheckTimeoutHandler);
     775        19431 :         RegisterTimeout(IDLE_STATS_UPDATE_TIMEOUT,
     776              :                         IdleStatsUpdateTimeoutHandler);
     777              :     }
     778              : 
     779              :     /*
     780              :      * If this is either a bootstrap process or a standalone backend, start up
     781              :      * the XLOG machinery, and register to have it closed down at exit. In
     782              :      * other cases, the startup process is responsible for starting up the
     783              :      * XLOG machinery, and the checkpointer for closing it down.
     784              :      */
     785        19482 :     if (!IsUnderPostmaster)
     786              :     {
     787              :         /*
     788              :          * We don't yet have an aux-process resource owner, but StartupXLOG
     789              :          * and ShutdownXLOG will need one.  Hence, create said resource owner
     790              :          * (and register a callback to clean it up after ShutdownXLOG runs).
     791              :          */
     792          121 :         CreateAuxProcessResourceOwner();
     793              : 
     794          121 :         StartupXLOG();
     795              :         /* Release (and warn about) any buffer pins leaked in StartupXLOG */
     796          121 :         ReleaseAuxProcessResources(true);
     797              :         /* Reset CurrentResourceOwner to nothing for the moment */
     798          121 :         CurrentResourceOwner = NULL;
     799              : 
     800              :         /*
     801              :          * Use before_shmem_exit() so that ShutdownXLOG() can rely on DSM
     802              :          * segments etc to work (which in turn is required for pgstats).
     803              :          */
     804          121 :         before_shmem_exit(pgstat_before_server_shutdown, 0);
     805          121 :         before_shmem_exit(ShutdownXLOG, 0);
     806              :     }
     807              : 
     808              :     /*
     809              :      * Initialize the relation cache and the system catalog caches.  Note that
     810              :      * no catalog access happens here; we only set up the hashtable structure.
     811              :      * We must do this before starting a transaction because transaction abort
     812              :      * would try to touch these hashtables.
     813              :      */
     814        19482 :     RelationCacheInitialize();
     815        19482 :     InitCatalogCache();
     816        19482 :     InitPlanCache();
     817              : 
     818              :     /* Initialize portal manager */
     819        19482 :     EnablePortalManager();
     820              : 
     821              :     /*
     822              :      * Load relcache entries for the shared system catalogs.  This must create
     823              :      * at least entries for pg_database and catalogs used for authentication.
     824              :      */
     825        19482 :     RelationCacheInitializePhase2();
     826              : 
     827              :     /*
     828              :      * Set up process-exit callback to do pre-shutdown cleanup.  This is one
     829              :      * of the first before_shmem_exit callbacks we register; thus, this will
     830              :      * be one of the last things we do before low-level modules like the
     831              :      * buffer manager begin to close down.  We need to have this in place
     832              :      * before we begin our first transaction --- if we fail during the
     833              :      * initialization transaction, as is entirely possible, we need the
     834              :      * AbortTransaction call to clean up.
     835              :      */
     836        19482 :     before_shmem_exit(ShutdownPostgres, 0);
     837              : 
     838              :     /* The autovacuum launcher is done here */
     839        19482 :     if (AmAutoVacuumLauncherProcess())
     840              :     {
     841              :         /* fill in the remainder of this entry in the PgBackendStatus array */
     842          454 :         pgstat_bestart_final();
     843              : 
     844         1422 :         return;
     845              :     }
     846              : 
     847              :     /*
     848              :      * Start a new transaction here before first access to db.
     849              :      */
     850        19028 :     if (!bootstrap)
     851              :     {
     852              :         /* statement_timestamp must be set for timeouts to work correctly */
     853        18977 :         SetCurrentStatementStartTimestamp();
     854        18977 :         StartTransactionCommand();
     855              : 
     856              :         /*
     857              :          * transaction_isolation will have been set to the default by the
     858              :          * above.  If the default is "serializable", and we are in hot
     859              :          * standby, we will fail if we don't change it to something lower.
     860              :          * Fortunately, "read committed" is plenty good enough.
     861              :          */
     862        18977 :         XactIsoLevel = XACT_READ_COMMITTED;
     863              :     }
     864              : 
     865              :     /*
     866              :      * Perform client authentication if necessary, then figure out our
     867              :      * postgres user ID, and see if we are a superuser.
     868              :      *
     869              :      * In standalone mode, autovacuum worker processes and slot sync worker
     870              :      * process, we use a fixed ID, otherwise we figure it out from the
     871              :      * authenticated user name.
     872              :      */
     873        19028 :     if (bootstrap || AmAutoVacuumWorkerProcess() || AmLogicalSlotSyncWorkerProcess())
     874              :     {
     875         1555 :         InitializeSessionUserIdStandalone();
     876         1555 :         am_superuser = true;
     877              :     }
     878        17473 :     else if (!IsUnderPostmaster)
     879              :     {
     880           70 :         InitializeSessionUserIdStandalone();
     881           70 :         am_superuser = true;
     882           70 :         if (!ThereIsAtLeastOneRole())
     883            0 :             ereport(WARNING,
     884              :                     (errcode(ERRCODE_UNDEFINED_OBJECT),
     885              :                      errmsg("no roles are defined in this database system"),
     886              :                      errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
     887              :                              username != NULL ? username : "postgres")));
     888              :     }
     889        17403 :     else if (AmBackgroundWorkerProcess())
     890              :     {
     891         3089 :         if (username == NULL && !OidIsValid(useroid))
     892              :         {
     893          493 :             InitializeSessionUserIdStandalone();
     894          493 :             am_superuser = true;
     895              :         }
     896              :         else
     897              :         {
     898         2596 :             InitializeSessionUserId(username, useroid,
     899         2596 :                                     (flags & INIT_PG_OVERRIDE_ROLE_LOGIN) != 0);
     900         2594 :             am_superuser = superuser();
     901              :         }
     902              :     }
     903              :     else
     904              :     {
     905              :         /* normal multiuser case */
     906              :         Assert(MyProcPort != NULL);
     907        14314 :         PerformAuthentication(MyProcPort);
     908        14240 :         InitializeSessionUserId(username, useroid, false);
     909              :         /* ensure that auth_method is actually valid, aka authn_id is not NULL */
     910        14236 :         if (MyClientConnectionInfo.authn_id)
     911          129 :             InitializeSystemUser(MyClientConnectionInfo.authn_id,
     912              :                                  hba_authname(MyClientConnectionInfo.auth_method));
     913        14236 :         am_superuser = superuser();
     914              :     }
     915              : 
     916              :     /* Report any SSL/GSS details for the session. */
     917        18948 :     if (MyProcPort != NULL)
     918              :     {
     919              :         Assert(!bootstrap);
     920              : 
     921        14236 :         pgstat_bestart_security();
     922              :     }
     923              : 
     924              :     /*
     925              :      * Binary upgrades only allowed super-user connections
     926              :      */
     927        18948 :     if (IsBinaryUpgrade && !am_superuser)
     928              :     {
     929            0 :         ereport(FATAL,
     930              :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     931              :                  errmsg("must be superuser to connect in binary upgrade mode")));
     932              :     }
     933              : 
     934              :     /*
     935              :      * The last few regular connection slots are reserved for superusers and
     936              :      * roles with privileges of pg_use_reserved_connections.  We do not apply
     937              :      * these limits to background processes, since they all have their own
     938              :      * pools of PGPROC slots.
     939              :      *
     940              :      * Note: At this point, the new backend has already claimed a proc struct,
     941              :      * so we must check whether the number of free slots is strictly less than
     942              :      * the reserved connection limits.
     943              :      */
     944        18948 :     if (AmRegularBackendProcess() && !am_superuser &&
     945          276 :         (SuperuserReservedConnections + ReservedConnections) > 0 &&
     946          276 :         !HaveNFreeProcs(SuperuserReservedConnections + ReservedConnections, &nfree))
     947              :     {
     948            4 :         if (nfree < SuperuserReservedConnections)
     949            1 :             ereport(FATAL,
     950              :                     (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
     951              :                      errmsg("remaining connection slots are reserved for roles with the %s attribute",
     952              :                             "SUPERUSER")));
     953              : 
     954            3 :         if (!has_privs_of_role(GetUserId(), ROLE_PG_USE_RESERVED_CONNECTIONS))
     955            1 :             ereport(FATAL,
     956              :                     (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
     957              :                      errmsg("remaining connection slots are reserved for roles with privileges of the \"%s\" role",
     958              :                             "pg_use_reserved_connections")));
     959              :     }
     960              : 
     961              :     /* Check replication permissions needed for walsender processes. */
     962        18946 :     if (am_walsender)
     963              :     {
     964              :         Assert(!bootstrap);
     965              : 
     966         1260 :         if (!has_rolreplication(GetUserId()))
     967            0 :             ereport(FATAL,
     968              :                     (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     969              :                      errmsg("permission denied to start WAL sender"),
     970              :                      errdetail("Only roles with the %s attribute may start a WAL sender process.",
     971              :                                "REPLICATION")));
     972              :     }
     973              : 
     974              :     /*
     975              :      * If this is a plain walsender only supporting physical replication, we
     976              :      * don't want to connect to any particular database. Just finish the
     977              :      * backend startup by processing any options from the startup packet, and
     978              :      * we're done.
     979              :      */
     980        18946 :     if (am_walsender && !am_db_walsender)
     981              :     {
     982              :         /* process any options passed in the startup packet */
     983          482 :         if (MyProcPort != NULL)
     984          482 :             process_startup_options(MyProcPort, am_superuser);
     985              : 
     986              :         /* Apply PostAuthDelay as soon as we've read all options */
     987          482 :         if (PostAuthDelay > 0)
     988            0 :             pg_usleep(PostAuthDelay * 1000000L);
     989              : 
     990              :         /* initialize client encoding */
     991          482 :         InitializeClientEncoding();
     992              : 
     993              :         /* fill in the remainder of this entry in the PgBackendStatus array */
     994          482 :         pgstat_bestart_final();
     995              : 
     996              :         /* close the transaction we started above */
     997          482 :         CommitTransactionCommand();
     998              : 
     999              :         /* send any WARNINGs we've accumulated during initialization */
    1000          482 :         EmitConnectionWarnings();
    1001              : 
    1002          482 :         return;
    1003              :     }
    1004              : 
    1005              :     /*
    1006              :      * Set up the global variables holding database id and default tablespace.
    1007              :      * But note we won't actually try to touch the database just yet.
    1008              :      *
    1009              :      * We take a shortcut in the bootstrap case, otherwise we have to look up
    1010              :      * the db's entry in pg_database.
    1011              :      */
    1012        18464 :     if (bootstrap)
    1013              :     {
    1014           51 :         dboid = Template1DbOid;
    1015           51 :         MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
    1016              :     }
    1017        18413 :     else if (in_dbname != NULL)
    1018              :     {
    1019              :         HeapTuple   tuple;
    1020              :         Form_pg_database dbform;
    1021              : 
    1022        13827 :         tuple = GetDatabaseTuple(in_dbname);
    1023        13827 :         if (!HeapTupleIsValid(tuple))
    1024           10 :             ereport(FATAL,
    1025              :                     (errcode(ERRCODE_UNDEFINED_DATABASE),
    1026              :                      errmsg("database \"%s\" does not exist", in_dbname)));
    1027        13817 :         dbform = (Form_pg_database) GETSTRUCT(tuple);
    1028        13817 :         dboid = dbform->oid;
    1029              :     }
    1030         4586 :     else if (!OidIsValid(dboid))
    1031              :     {
    1032              :         /*
    1033              :          * If this is a background worker not bound to any particular
    1034              :          * database, we're done now.  Everything that follows only makes sense
    1035              :          * if we are bound to a specific database.  We do need to close the
    1036              :          * transaction we started before returning.
    1037              :          */
    1038          486 :         if (!bootstrap)
    1039              :         {
    1040          486 :             pgstat_bestart_final();
    1041          486 :             CommitTransactionCommand();
    1042              :         }
    1043          486 :         return;
    1044              :     }
    1045              : 
    1046              :     /*
    1047              :      * Now, take a writer's lock on the database we are trying to connect to.
    1048              :      * If there is a concurrently running DROP DATABASE on that database, this
    1049              :      * will block us until it finishes (and has committed its update of
    1050              :      * pg_database).
    1051              :      *
    1052              :      * Note that the lock is not held long, only until the end of this startup
    1053              :      * transaction.  This is OK since we will advertise our use of the
    1054              :      * database in the ProcArray before dropping the lock (in fact, that's the
    1055              :      * next thing to do).  Anyone trying a DROP DATABASE after this point will
    1056              :      * see us in the array once they have the lock.  Ordering is important for
    1057              :      * this because we don't want to advertise ourselves as being in this
    1058              :      * database until we have the lock; otherwise we create what amounts to a
    1059              :      * deadlock with CountOtherDBBackends().
    1060              :      *
    1061              :      * Note: use of RowExclusiveLock here is reasonable because we envision
    1062              :      * our session as being a concurrent writer of the database.  If we had a
    1063              :      * way of declaring a session as being guaranteed-read-only, we could use
    1064              :      * AccessShareLock for such sessions and thereby not conflict against
    1065              :      * CREATE DATABASE.
    1066              :      */
    1067        17968 :     if (!bootstrap)
    1068        17917 :         LockSharedObject(DatabaseRelationId, dboid, 0, RowExclusiveLock);
    1069              : 
    1070              :     /*
    1071              :      * Recheck pg_database to make sure the target database hasn't gone away.
    1072              :      * If there was a concurrent DROP DATABASE, this ensures we will die
    1073              :      * cleanly without creating a mess.
    1074              :      */
    1075        17968 :     if (!bootstrap)
    1076              :     {
    1077              :         HeapTuple   tuple;
    1078              :         Form_pg_database datform;
    1079              : 
    1080        17917 :         tuple = GetDatabaseTupleByOid(dboid);
    1081        17917 :         if (HeapTupleIsValid(tuple))
    1082        17917 :             datform = (Form_pg_database) GETSTRUCT(tuple);
    1083              : 
    1084        17917 :         if (!HeapTupleIsValid(tuple) ||
    1085        13817 :             (in_dbname && namestrcmp(&datform->datname, in_dbname)))
    1086              :         {
    1087            0 :             if (in_dbname)
    1088            0 :                 ereport(FATAL,
    1089              :                         (errcode(ERRCODE_UNDEFINED_DATABASE),
    1090              :                          errmsg("database \"%s\" does not exist", in_dbname),
    1091              :                          errdetail("It seems to have just been dropped or renamed.")));
    1092              :             else
    1093            0 :                 ereport(FATAL,
    1094              :                         (errcode(ERRCODE_UNDEFINED_DATABASE),
    1095              :                          errmsg("database %u does not exist", dboid)));
    1096              :         }
    1097              : 
    1098        17917 :         strlcpy(dbname, NameStr(datform->datname), sizeof(dbname));
    1099              : 
    1100        17917 :         if (database_is_invalid_form(datform))
    1101              :         {
    1102            6 :             ereport(FATAL,
    1103              :                     errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1104              :                     errmsg("cannot connect to invalid database \"%s\"", dbname),
    1105              :                     errhint("Use DROP DATABASE to drop invalid databases."));
    1106              :         }
    1107              : 
    1108        17911 :         MyDatabaseTableSpace = datform->dattablespace;
    1109        17911 :         MyDatabaseHasLoginEventTriggers = datform->dathasloginevt;
    1110              :         /* pass the database name back to the caller */
    1111        17911 :         if (out_dbname)
    1112         1499 :             strcpy(out_dbname, dbname);
    1113              :     }
    1114              : 
    1115              :     /*
    1116              :      * Now that we rechecked, we are certain to be connected to a database and
    1117              :      * thus can set MyDatabaseId.
    1118              :      *
    1119              :      * It is important that MyDatabaseId only be set once we are sure that the
    1120              :      * target database can no longer be concurrently dropped or renamed.  For
    1121              :      * example, without this guarantee, pgstat_update_dbstats() could create
    1122              :      * entries for databases that were just dropped in the pgstat shutdown
    1123              :      * callback, which could confuse other code paths like the autovacuum
    1124              :      * scheduler.
    1125              :      */
    1126        17962 :     MyDatabaseId = dboid;
    1127              : 
    1128              :     /*
    1129              :      * Now we can mark our PGPROC entry with the database ID.
    1130              :      *
    1131              :      * We assume this is an atomic store so no lock is needed; though actually
    1132              :      * things would work fine even if it weren't atomic.  Anyone searching the
    1133              :      * ProcArray for this database's ID should hold the database lock, so they
    1134              :      * would not be executing concurrently with this store.  A process looking
    1135              :      * for another database's ID could in theory see a chance match if it read
    1136              :      * a partially-updated databaseId value; but as long as all such searches
    1137              :      * wait and retry, as in CountOtherDBBackends(), they will certainly see
    1138              :      * the correct value on their next try.
    1139              :      */
    1140        17962 :     MyProc->databaseId = MyDatabaseId;
    1141              : 
    1142              :     /*
    1143              :      * We established a catalog snapshot while reading pg_authid and/or
    1144              :      * pg_database; but until we have set up MyDatabaseId, we won't react to
    1145              :      * incoming sinval messages for unshared catalogs, so we won't realize it
    1146              :      * if the snapshot has been invalidated.  Assume it's no good anymore.
    1147              :      */
    1148        17962 :     InvalidateCatalogSnapshot();
    1149              : 
    1150              :     /*
    1151              :      * Now we should be able to access the database directory safely. Verify
    1152              :      * it's there and looks reasonable.
    1153              :      */
    1154        17962 :     fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace);
    1155              : 
    1156        17962 :     if (!bootstrap)
    1157              :     {
    1158        17911 :         if (access(fullpath, F_OK) == -1)
    1159              :         {
    1160            0 :             if (errno == ENOENT)
    1161            0 :                 ereport(FATAL,
    1162              :                         (errcode(ERRCODE_UNDEFINED_DATABASE),
    1163              :                          errmsg("database \"%s\" does not exist",
    1164              :                                 dbname),
    1165              :                          errdetail("The database subdirectory \"%s\" is missing.",
    1166              :                                    fullpath)));
    1167              :             else
    1168            0 :                 ereport(FATAL,
    1169              :                         (errcode_for_file_access(),
    1170              :                          errmsg("could not access directory \"%s\": %m",
    1171              :                                 fullpath)));
    1172              :         }
    1173              : 
    1174        17911 :         ValidatePgVersion(fullpath);
    1175              :     }
    1176              : 
    1177        17962 :     SetDatabasePath(fullpath);
    1178        17962 :     pfree(fullpath);
    1179              : 
    1180              :     /*
    1181              :      * It's now possible to do real access to the system catalogs.
    1182              :      *
    1183              :      * Load relcache entries for the system catalogs.  This must create at
    1184              :      * least the minimum set of "nailed-in" cache entries.
    1185              :      */
    1186        17962 :     RelationCacheInitializePhase3();
    1187              : 
    1188              :     /* set up ACL framework (so CheckMyDatabase can check permissions) */
    1189        17961 :     initialize_acl();
    1190              : 
    1191              :     /*
    1192              :      * Re-read the pg_database row for our database, check permissions and set
    1193              :      * up database-specific GUC settings.  We can't do this until all the
    1194              :      * database-access infrastructure is up.  (Also, it wants to know if the
    1195              :      * user is a superuser, so the above stuff has to happen first.)
    1196              :      */
    1197        17961 :     if (!bootstrap)
    1198        17910 :         CheckMyDatabase(dbname, am_superuser,
    1199        17910 :                         (flags & INIT_PG_OVERRIDE_ALLOW_CONNS) != 0);
    1200              : 
    1201              :     /*
    1202              :      * Now process any command-line switches and any additional GUC variable
    1203              :      * settings passed in the startup packet.   We couldn't do this before
    1204              :      * because we didn't know if client is a superuser.
    1205              :      */
    1206        17958 :     if (MyProcPort != NULL)
    1207        13736 :         process_startup_options(MyProcPort, am_superuser);
    1208              : 
    1209              :     /* Process pg_db_role_setting options */
    1210        17958 :     process_settings(MyDatabaseId, GetSessionUserId());
    1211              : 
    1212              :     /* Apply PostAuthDelay as soon as we've read all options */
    1213        17958 :     if (PostAuthDelay > 0)
    1214            0 :         pg_usleep(PostAuthDelay * 1000000L);
    1215              : 
    1216              :     /*
    1217              :      * Initialize various default states that can't be set up until we've
    1218              :      * selected the active user and gotten the right GUC settings.
    1219              :      */
    1220              : 
    1221              :     /* set default namespace search path */
    1222        17958 :     InitializeSearchPath();
    1223              : 
    1224              :     /* initialize client encoding */
    1225        17958 :     InitializeClientEncoding();
    1226              : 
    1227              :     /* Initialize this backend's session state. */
    1228        17958 :     InitializeSession();
    1229              : 
    1230              :     /*
    1231              :      * If this is an interactive session, load any libraries that should be
    1232              :      * preloaded at backend start.  Since those are determined by GUCs, this
    1233              :      * can't happen until GUC settings are complete, but we want it to happen
    1234              :      * during the initial transaction in case anything that requires database
    1235              :      * access needs to be done.
    1236              :      */
    1237        17958 :     if ((flags & INIT_PG_LOAD_SESSION_LIBS) != 0)
    1238        13026 :         process_session_preload_libraries();
    1239              : 
    1240              :     /* fill in the remainder of this entry in the PgBackendStatus array */
    1241        17958 :     if (!bootstrap)
    1242        17907 :         pgstat_bestart_final();
    1243              : 
    1244              :     /* close the transaction we started above */
    1245        17958 :     if (!bootstrap)
    1246        17907 :         CommitTransactionCommand();
    1247              : 
    1248              :     /* send any WARNINGs we've accumulated during initialization */
    1249        17958 :     EmitConnectionWarnings();
    1250              : }
    1251              : 
    1252              : /*
    1253              :  * Process any command-line switches and any additional GUC variable
    1254              :  * settings passed in the startup packet.
    1255              :  */
    1256              : static void
    1257        14218 : process_startup_options(Port *port, bool am_superuser)
    1258              : {
    1259              :     GucContext  gucctx;
    1260              :     ListCell   *gucopts;
    1261              : 
    1262        14218 :     gucctx = am_superuser ? PGC_SU_BACKEND : PGC_BACKEND;
    1263              : 
    1264              :     /*
    1265              :      * First process any command-line switches that were included in the
    1266              :      * startup packet, if we are in a regular backend.
    1267              :      */
    1268        14218 :     if (port->cmdline_options != NULL)
    1269              :     {
    1270              :         /*
    1271              :          * The maximum possible number of commandline arguments that could
    1272              :          * come from port->cmdline_options is (strlen + 1) / 2; see
    1273              :          * pg_split_opts().
    1274              :          */
    1275              :         char      **av;
    1276              :         int         maxac;
    1277              :         int         ac;
    1278              : 
    1279         4298 :         maxac = 2 + (strlen(port->cmdline_options) + 1) / 2;
    1280              : 
    1281         4298 :         av = palloc_array(char *, maxac);
    1282         4298 :         ac = 0;
    1283              : 
    1284         4298 :         av[ac++] = "postgres";
    1285              : 
    1286         4298 :         pg_split_opts(av, &ac, port->cmdline_options);
    1287              : 
    1288         4298 :         av[ac] = NULL;
    1289              : 
    1290              :         Assert(ac < maxac);
    1291              : 
    1292         4298 :         (void) process_postgres_switches(ac, av, gucctx, NULL);
    1293              :     }
    1294              : 
    1295              :     /*
    1296              :      * Process any additional GUC variable settings passed in startup packet.
    1297              :      * These are handled exactly like command-line variables.
    1298              :      */
    1299        14218 :     gucopts = list_head(port->guc_options);
    1300        34534 :     while (gucopts)
    1301              :     {
    1302              :         char       *name;
    1303              :         char       *value;
    1304              : 
    1305        20316 :         name = lfirst(gucopts);
    1306        20316 :         gucopts = lnext(port->guc_options, gucopts);
    1307              : 
    1308        20316 :         value = lfirst(gucopts);
    1309        20316 :         gucopts = lnext(port->guc_options, gucopts);
    1310              : 
    1311        20316 :         SetConfigOption(name, value, gucctx, PGC_S_CLIENT);
    1312              :     }
    1313        14218 : }
    1314              : 
    1315              : /*
    1316              :  * Load GUC settings from pg_db_role_setting.
    1317              :  *
    1318              :  * We try specific settings for the database/role combination, as well as
    1319              :  * general for this database and for this user.
    1320              :  */
    1321              : static void
    1322        17958 : process_settings(Oid databaseid, Oid roleid)
    1323              : {
    1324              :     Relation    relsetting;
    1325              :     Snapshot    snapshot;
    1326              : 
    1327        17958 :     if (!IsUnderPostmaster)
    1328          119 :         return;
    1329              : 
    1330        17839 :     relsetting = table_open(DbRoleSettingRelationId, AccessShareLock);
    1331              : 
    1332              :     /* read all the settings under the same snapshot for efficiency */
    1333        17839 :     snapshot = RegisterSnapshot(GetCatalogSnapshot(DbRoleSettingRelationId));
    1334              : 
    1335              :     /* Later settings are ignored if set earlier. */
    1336        17839 :     ApplySetting(snapshot, databaseid, roleid, relsetting, PGC_S_DATABASE_USER);
    1337        17839 :     ApplySetting(snapshot, InvalidOid, roleid, relsetting, PGC_S_USER);
    1338        17839 :     ApplySetting(snapshot, databaseid, InvalidOid, relsetting, PGC_S_DATABASE);
    1339        17839 :     ApplySetting(snapshot, InvalidOid, InvalidOid, relsetting, PGC_S_GLOBAL);
    1340              : 
    1341        17839 :     UnregisterSnapshot(snapshot);
    1342        17839 :     table_close(relsetting, AccessShareLock);
    1343              : }
    1344              : 
    1345              : /*
    1346              :  * Backend-shutdown callback.  Do cleanup that we want to be sure happens
    1347              :  * before all the supporting modules begin to nail their doors shut via
    1348              :  * their own callbacks.
    1349              :  *
    1350              :  * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
    1351              :  * via separate callbacks that execute before this one.  We don't combine the
    1352              :  * callbacks because we still want this one to happen if the user-level
    1353              :  * cleanup fails.
    1354              :  */
    1355              : static void
    1356        19482 : ShutdownPostgres(int code, Datum arg)
    1357              : {
    1358              :     /* Make sure we've killed any active transaction */
    1359        19482 :     AbortOutOfAnyTransaction();
    1360              : 
    1361              :     /*
    1362              :      * User locks are not released by transaction end, so be sure to release
    1363              :      * them explicitly.
    1364              :      */
    1365        19482 :     LockReleaseAll(USER_LOCKMETHOD, true);
    1366        19482 : }
    1367              : 
    1368              : 
    1369              : /*
    1370              :  * STATEMENT_TIMEOUT handler: trigger a query-cancel interrupt.
    1371              :  */
    1372              : static void
    1373            6 : StatementTimeoutHandler(void)
    1374              : {
    1375            6 :     int         sig = SIGINT;
    1376              : 
    1377              :     /*
    1378              :      * During authentication the timeout is used to deal with
    1379              :      * authentication_timeout - we want to quit in response to such timeouts.
    1380              :      */
    1381            6 :     if (ClientAuthInProgress)
    1382            0 :         sig = SIGTERM;
    1383              : 
    1384              : #ifdef HAVE_SETSID
    1385              :     /* try to signal whole process group */
    1386            6 :     kill(-MyProcPid, sig);
    1387              : #endif
    1388            6 :     kill(MyProcPid, sig);
    1389            6 : }
    1390              : 
    1391              : /*
    1392              :  * LOCK_TIMEOUT handler: trigger a query-cancel interrupt.
    1393              :  */
    1394              : static void
    1395            4 : LockTimeoutHandler(void)
    1396              : {
    1397              : #ifdef HAVE_SETSID
    1398              :     /* try to signal whole process group */
    1399            4 :     kill(-MyProcPid, SIGINT);
    1400              : #endif
    1401            4 :     kill(MyProcPid, SIGINT);
    1402            4 : }
    1403              : 
    1404              : static void
    1405            1 : TransactionTimeoutHandler(void)
    1406              : {
    1407            1 :     TransactionTimeoutPending = true;
    1408            1 :     InterruptPending = true;
    1409            1 :     SetLatch(MyLatch);
    1410            1 : }
    1411              : 
    1412              : static void
    1413            1 : IdleInTransactionSessionTimeoutHandler(void)
    1414              : {
    1415            1 :     IdleInTransactionSessionTimeoutPending = true;
    1416            1 :     InterruptPending = true;
    1417            1 :     SetLatch(MyLatch);
    1418            1 : }
    1419              : 
    1420              : static void
    1421            1 : IdleSessionTimeoutHandler(void)
    1422              : {
    1423            1 :     IdleSessionTimeoutPending = true;
    1424            1 :     InterruptPending = true;
    1425            1 :     SetLatch(MyLatch);
    1426            1 : }
    1427              : 
    1428              : static void
    1429           13 : IdleStatsUpdateTimeoutHandler(void)
    1430              : {
    1431           13 :     IdleStatsUpdateTimeoutPending = true;
    1432           13 :     InterruptPending = true;
    1433           13 :     SetLatch(MyLatch);
    1434           13 : }
    1435              : 
    1436              : static void
    1437            0 : ClientCheckTimeoutHandler(void)
    1438              : {
    1439            0 :     CheckClientConnectionPending = true;
    1440            0 :     InterruptPending = true;
    1441            0 :     SetLatch(MyLatch);
    1442            0 : }
    1443              : 
    1444              : /*
    1445              :  * Returns true if at least one role is defined in this database cluster.
    1446              :  */
    1447              : static bool
    1448           70 : ThereIsAtLeastOneRole(void)
    1449              : {
    1450              :     Relation    pg_authid_rel;
    1451              :     TableScanDesc scan;
    1452              :     bool        result;
    1453              : 
    1454           70 :     pg_authid_rel = table_open(AuthIdRelationId, AccessShareLock);
    1455              : 
    1456           70 :     scan = table_beginscan_catalog(pg_authid_rel, 0, NULL);
    1457           70 :     result = (heap_getnext(scan, ForwardScanDirection) != NULL);
    1458              : 
    1459           70 :     table_endscan(scan);
    1460           70 :     table_close(pg_authid_rel, AccessShareLock);
    1461              : 
    1462           70 :     return result;
    1463              : }
    1464              : 
    1465              : /*
    1466              :  * Stores a warning message to be sent later via EmitConnectionWarnings().
    1467              :  * Both msg and detail must be non-NULL.
    1468              :  *
    1469              :  * NB: Caller should ensure the strings are allocated in a long-lived context
    1470              :  * like TopMemoryContext.
    1471              :  */
    1472              : void
    1473            2 : StoreConnectionWarning(char *msg, char *detail)
    1474              : {
    1475              :     MemoryContext oldcontext;
    1476              : 
    1477              :     Assert(msg);
    1478              :     Assert(detail);
    1479              : 
    1480            2 :     if (ConnectionWarningsEmitted)
    1481            0 :         elog(ERROR, "StoreConnectionWarning() called after EmitConnectionWarnings()");
    1482              : 
    1483            2 :     oldcontext = MemoryContextSwitchTo(TopMemoryContext);
    1484              : 
    1485            2 :     ConnectionWarningMessages = lappend(ConnectionWarningMessages, msg);
    1486            2 :     ConnectionWarningDetails = lappend(ConnectionWarningDetails, detail);
    1487              : 
    1488            2 :     MemoryContextSwitchTo(oldcontext);
    1489            2 : }
    1490              : 
    1491              : /*
    1492              :  * Sends the warning messages saved via StoreConnectionWarning() and frees the
    1493              :  * strings and lists.
    1494              :  *
    1495              :  * NB: This can only be called once per backend.
    1496              :  */
    1497              : static void
    1498        18440 : EmitConnectionWarnings(void)
    1499              : {
    1500              :     ListCell   *lc_msg;
    1501              :     ListCell   *lc_detail;
    1502              : 
    1503        18440 :     if (ConnectionWarningsEmitted)
    1504            0 :         elog(ERROR, "EmitConnectionWarnings() called more than once");
    1505              :     else
    1506        18440 :         ConnectionWarningsEmitted = true;
    1507              : 
    1508        18442 :     forboth(lc_msg, ConnectionWarningMessages,
    1509              :             lc_detail, ConnectionWarningDetails)
    1510              :     {
    1511            2 :         ereport(WARNING,
    1512              :                 (errmsg("%s", (char *) lfirst(lc_msg)),
    1513              :                  errdetail("%s", (char *) lfirst(lc_detail))));
    1514              :     }
    1515              : 
    1516        18440 :     list_free_deep(ConnectionWarningMessages);
    1517        18440 :     list_free_deep(ConnectionWarningDetails);
    1518        18440 : }
        

Generated by: LCOV version 2.0-1