LCOV - differential code coverage report
Current view: top level - src/backend/utils/init - postinit.c (source / functions) Coverage Total Hit UNC UBC GNC CBC DUB DCB
Current: 380a8b2ea024c33a35e7abc8628e7c4f52f9f9f9 vs db5ed03217b9c238703df8b4b286115d6e940488 Lines: 91.7 % 397 364 2 31 25 339 1 6
Current Date: 2026-05-29 21:51:00 -0400 Functions: 95.5 % 22 21 1 5 16
Baseline: lcov-20260530-034037-baseline Branches: 66.1 % 298 197 11 90 25 172 4 6
Baseline Date: 2026-05-29 14:39:03 -0700 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 100.0 % 3 3 3
(30,360] days: 91.7 % 24 22 2 22
(360..) days: 91.6 % 370 339 31 339
Function coverage date bins:
(30,360] days: 100.0 % 2 2 2
(360..) days: 95.0 % 20 19 1 3 16
Branch coverage date bins:
(7,30] days: 50.0 % 2 1 1 1
(30,360] days: 70.6 % 34 24 10 24
(360..) days: 65.6 % 262 172 90 172

 Age         Owner                    Branch data    TLA  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
 6135 tgl@sss.pgh.pa.us         114                 :CBC       14302 : 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                 :          14302 :     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                 :                :      */
 2686 andres@anarazel.de        134                 :          14302 :     relation = table_open(DatabaseRelationId, AccessShareLock);
 6135 tgl@sss.pgh.pa.us         135                 :          14302 :     scan = systable_beginscan(relation, DatabaseNameIndexId,
                                136                 :                :                               criticalSharedRelcachesBuilt,
                                137                 :                :                               NULL,
                                138                 :                :                               1, key);
                                139                 :                : 
                                140                 :          14302 :     tuple = systable_getnext(scan);
                                141                 :                : 
                                142                 :                :     /* Must copy tuple before releasing buffer */
                                143         [ +  + ]:          14302 :     if (HeapTupleIsValid(tuple))
                                144                 :          14296 :         tuple = heap_copytuple(tuple);
                                145                 :                : 
                                146                 :                :     /* all done */
                                147                 :          14302 :     systable_endscan(scan);
 2686 andres@anarazel.de        148                 :          14302 :     table_close(relation, AccessShareLock);
                                149                 :                : 
 6135 tgl@sss.pgh.pa.us         150                 :          14302 :     return tuple;
                                151                 :                : }
                                152                 :                : 
                                153                 :                : /*
                                154                 :                :  * GetDatabaseTupleByOid -- as above, but search by database OID
                                155                 :                :  */
                                156                 :                : static HeapTuple
                                157                 :          16992 : 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                 :          16992 :     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                 :                :      */
 2686 andres@anarazel.de        177                 :          16992 :     relation = table_open(DatabaseRelationId, AccessShareLock);
 6135 tgl@sss.pgh.pa.us         178                 :          16992 :     scan = systable_beginscan(relation, DatabaseOidIndexId,
                                179                 :                :                               criticalSharedRelcachesBuilt,
                                180                 :                :                               NULL,
                                181                 :                :                               1, key);
                                182                 :                : 
                                183                 :          16992 :     tuple = systable_getnext(scan);
                                184                 :                : 
                                185                 :                :     /* Must copy tuple before releasing buffer */
                                186         [ +  - ]:          16992 :     if (HeapTupleIsValid(tuple))
                                187                 :          16992 :         tuple = heap_copytuple(tuple);
                                188                 :                : 
                                189                 :                :     /* all done */
                                190                 :          16992 :     systable_endscan(scan);
 2686 andres@anarazel.de        191                 :          16992 :     table_close(relation, AccessShareLock);
                                192                 :                : 
 6135 tgl@sss.pgh.pa.us         193                 :          16992 :     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
 6118                           203                 :          14946 : PerformAuthentication(Port *port)
                                204                 :                : {
                                205                 :                :     /* This should be set already, but let's make sure */
                                206                 :          14946 :     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 */
  444 melanieplageman@gmai      249                 :          14946 :     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                 :                :      */
 5066 alvherre@alvh.no-ip.      256                 :          14946 :     enable_timeout_after(STATEMENT_TIMEOUT, AuthenticationTimeout * 1000);
                                257                 :                : 
                                258                 :                :     /*
                                259                 :                :      * Now perform authentication exchange.
                                260                 :                :      */
 2271 peter@eisentraut.org      261                 :          14946 :     set_ps_display("authentication");
 6118 tgl@sss.pgh.pa.us         262                 :          14946 :     ClientAuthentication(port); /* might not return, if failure */
                                263                 :                : 
                                264                 :                :     /*
                                265                 :                :      * Done with authentication.  Disable the timeout, and log if needed.
                                266                 :                :      */
 5066 alvherre@alvh.no-ip.      267                 :          14739 :     disable_timeout(STATEMENT_TIMEOUT, false);
                                268                 :                : 
                                269                 :                :     /* Capture authentication end time for logging */
  444 melanieplageman@gmai      270                 :          14739 :     conn_timing.auth_end = GetCurrentTimestamp();
                                271                 :                : 
                                272         [ +  + ]:          14739 :     if (log_connections & LOG_CONNECTION_AUTHORIZATION)
                                273                 :                :     {
                                274                 :                :         StringInfoData logmsg;
                                275                 :                : 
 2005 sfrost@snowman.net        276                 :            408 :         initStringInfo(&logmsg);
 5611 magnus@hagander.net       277         [ -  + ]:            408 :         if (am_walsender)
 2005 sfrost@snowman.net        278                 :UBC           0 :             appendStringInfo(&logmsg, _("replication connection authorized: user=%s"),
                                279                 :                :                              port->user_name);
                                280                 :                :         else
 2005 sfrost@snowman.net        281                 :CBC         408 :             appendStringInfo(&logmsg, _("connection authorized: user=%s"),
                                282                 :                :                              port->user_name);
                                283         [ +  - ]:            408 :         if (!am_walsender)
                                284                 :            408 :             appendStringInfo(&logmsg, _(" database=%s"), port->database_name);
                                285                 :                : 
                                286         [ +  + ]:            408 :         if (port->application_name != NULL)
                                287                 :            405 :             appendStringInfo(&logmsg, _(" application_name=%s"),
                                288                 :                :                              port->application_name);
                                289                 :                : 
                                290                 :                : #ifdef USE_SSL
                                291         [ +  + ]:            408 :         if (port->ssl_in_use)
 1908 michael@paquier.xyz       292                 :            128 :             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
 1979 tgl@sss.pgh.pa.us         298         [ +  + ]:            408 :         if (port->gss)
                                299                 :                :         {
                                300                 :             90 :             const char *princ = be_gssapi_get_princ(port);
                                301                 :                : 
                                302         [ +  + ]:             90 :             if (princ)
                                303   [ +  +  +  +  :            117 :                 appendStringInfo(&logmsg,
                                              +  - ]
 1105                           304                 :             39 :                                  _(" GSS (authenticated=%s, encrypted=%s, delegated_credentials=%s, principal=%s)"),
 1979                           305                 :             78 :                                  be_gssapi_get_auth(port) ? _("yes") : _("no"),
                                306                 :             78 :                                  be_gssapi_get_enc(port) ? _("yes") : _("no"),
 1106 bruce@momjian.us          307                 :             78 :                                  be_gssapi_get_delegation(port) ? _("yes") : _("no"),
                                308                 :                :                                  princ);
                                309                 :                :             else
 1979 tgl@sss.pgh.pa.us         310   [ -  +  +  -  :            153 :                 appendStringInfo(&logmsg,
                                              -  + ]
 1105                           311                 :             51 :                                  _(" GSS (authenticated=%s, encrypted=%s, delegated_credentials=%s)"),
 1979                           312                 :            102 :                                  be_gssapi_get_auth(port) ? _("yes") : _("no"),
 1143 sfrost@snowman.net        313                 :            102 :                                  be_gssapi_get_enc(port) ? _("yes") : _("no"),
 1106 bruce@momjian.us          314                 :            102 :                                  be_gssapi_get_delegation(port) ? _("yes") : _("no"));
                                315                 :                :         }
                                316                 :                : #endif
                                317                 :                : 
 2005 sfrost@snowman.net        318         [ +  - ]:            408 :         ereport(LOG, errmsg_internal("%s", logmsg.data));
                                319                 :            408 :         pfree(logmsg.data);
                                320                 :                :     }
                                321                 :                : 
 2271 peter@eisentraut.org      322                 :          14739 :     set_ps_display("startup");
                                323                 :                : 
 3265 tgl@sss.pgh.pa.us         324                 :          14739 :     ClientAuthInProgress = false;   /* client_min_messages is active now */
 6118                           325                 :          14739 : }
                                326                 :                : 
                                327                 :                : 
                                328                 :                : /*
                                329                 :                :  * CheckMyDatabase -- fetch information from the pg_database entry for our DB
                                330                 :                :  */
                                331                 :                : static void
 2977 magnus@hagander.net       332                 :          16984 : 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 */
 5949 rhaas@postgresql.org      342                 :          16984 :     tup = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));
 7331 tgl@sss.pgh.pa.us         343         [ -  + ]:          16984 :     if (!HeapTupleIsValid(tup))
 7331 tgl@sss.pgh.pa.us         344         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
 7331 tgl@sss.pgh.pa.us         345                 :CBC       16984 :     dbform = (Form_pg_database) GETSTRUCT(tup);
                                346                 :                : 
                                347                 :                :     /* This recheck is strictly paranoia */
                                348         [ -  + ]:          16984 :     if (strcmp(name, NameStr(dbform->datname)) != 0)
 8345 tgl@sss.pgh.pa.us         349         [ #  # ]:UBC           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                 :                :      */
  518 tgl@sss.pgh.pa.us         363         [ +  + ]:CBC       16984 :     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                 :                :          */
 2977 magnus@hagander.net       370   [ +  +  +  + ]:          16908 :         if (!dbform->datallowconn && !override_allow_connections)
 7608 tgl@sss.pgh.pa.us         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                 :                :          */
  518                           381   [ +  +  +  +  :          17355 :         if (!am_superuser && !override_allow_connections &&
                                              -  + ]
 1294 peter@eisentraut.org      382                 :            448 :             object_aclcheck(DatabaseRelationId, MyDatabaseId, GetUserId(),
                                383                 :                :                             ACL_CONNECT) != ACLCHECK_OK)
 7335 tgl@sss.pgh.pa.us         384         [ #  # ]:UBC           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                 :                :          */
 7608 tgl@sss.pgh.pa.us         401         [ -  + ]:CBC       16907 :         if (dbform->datconnlimit >= 0 &&
  518 tgl@sss.pgh.pa.us         402         [ #  # ]:UBC           0 :             AmRegularBackendProcess() &&
 7335                           403         [ #  # ]:              0 :             !am_superuser &&
 3405 andrew@dunslane.net       404         [ #  # ]:              0 :             CountDBConnections(MyDatabaseId) > dbform->datconnlimit)
 7608 tgl@sss.pgh.pa.us         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                 :                :      */
 9328 tgl@sss.pgh.pa.us         415                 :CBC       16983 :     SetDatabaseEncoding(dbform->encoding);
                                416                 :                :     /* Record it as a GUC internal option, too */
 8436                           417                 :          16983 :     SetConfigOption("server_encoding", GetDatabaseEncodingName(),
                                418                 :                :                     PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
                                419                 :                :     /* If we have no other source of client_encoding, use server encoding */
 8779                           420                 :          16983 :     SetConfigOption("client_encoding", GetDatabaseEncodingName(),
                                421                 :                :                     PGC_BACKEND, PGC_S_DYNAMIC_DEFAULT);
                                422                 :                : 
                                423                 :                :     /* assign locale variables */
 1162 dgustafsson@postgres      424                 :          16983 :     datum = SysCacheGetAttrNotNull(DATABASEOID, tup, Anum_pg_database_datcollate);
 1584 peter@eisentraut.org      425                 :          16983 :     collate = TextDatumGetCString(datum);
 1162 dgustafsson@postgres      426                 :          16983 :     datum = SysCacheGetAttrNotNull(DATABASEOID, tup, Anum_pg_database_datctype);
 1584 peter@eisentraut.org      427                 :          16983 :     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                 :                : 
 6170 heikki.linnakangas@i      435         [ -  + ]:          16983 :     if (pg_perm_setlocale(LC_CTYPE, ctype) == NULL)
 6197 bruce@momjian.us          436         [ #  # ]:UBC           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                 :                : 
  671 jdavis@postgresql.or      442                 :CBC       16983 :     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                 :                :      */
 1566 peter@eisentraut.org      449                 :          16981 :     datum = SysCacheGetAttr(DATABASEOID, tup, Anum_pg_database_datcollversion,
                                450                 :                :                             &isnull);
                                451         [ +  + ]:          16981 :     if (!isnull)
                                452                 :                :     {
                                453                 :                :         char       *actual_versionstr;
                                454                 :                :         char       *collversionstr;
                                455                 :                :         char       *locale;
                                456                 :                : 
                                457                 :            928 :         collversionstr = TextDatumGetCString(datum);
                                458                 :                : 
  808 jdavis@postgresql.or      459         [ -  + ]:            928 :         if (dbform->datlocprovider == COLLPROVIDER_LIBC)
  808 jdavis@postgresql.or      460                 :UBC           0 :             locale = collate;
                                461                 :                :         else
                                462                 :                :         {
  671 jdavis@postgresql.or      463                 :CBC         928 :             datum = SysCacheGetAttrNotNull(DATABASEOID, tup, Anum_pg_database_datlocale);
                                464                 :            928 :             locale = TextDatumGetCString(datum);
                                465                 :                :         }
                                466                 :                : 
  808                           467                 :            928 :         actual_versionstr = get_collation_actual_version(dbform->datlocprovider, locale);
 1566 peter@eisentraut.org      468         [ -  + ]:            928 :         if (!actual_versionstr)
                                469                 :                :             /* should not happen */
 1361 alvherre@alvh.no-ip.      470         [ #  # ]:UBC           0 :             elog(WARNING,
                                471                 :                :                  "database \"%s\" has no actual collation version, but a version was recorded",
                                472                 :                :                  name);
 1559 peter@eisentraut.org      473         [ -  + ]:CBC         928 :         else if (strcmp(actual_versionstr, collversionstr) != 0)
 1566 peter@eisentraut.org      474         [ #  # ]:UBC           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                 :                : 
 7331 tgl@sss.pgh.pa.us         486                 :CBC       16981 :     ReleaseSysCache(tup);
 9745                           487                 :          16981 : }
                                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
 3988                           501                 :           4219 : pg_split_opts(char **argv, int *argcp, const char *optstr)
                                502                 :                : {
                                503                 :                :     StringInfoData s;
                                504                 :                : 
 4293 andres@anarazel.de        505                 :           4219 :     initStringInfo(&s);
                                506                 :                : 
 6118 tgl@sss.pgh.pa.us         507         [ +  + ]:          15454 :     while (*optstr)
                                508                 :                :     {
 4277                           509                 :          11235 :         bool        last_was_escape = false;
                                510                 :                : 
 4293 andres@anarazel.de        511                 :          11235 :         resetStringInfo(&s);
                                512                 :                : 
                                513                 :                :         /* skip over leading space */
 6118 tgl@sss.pgh.pa.us         514         [ +  + ]:          21470 :         while (isspace((unsigned char) *optstr))
                                515                 :          10235 :             optstr++;
                                516                 :                : 
                                517         [ -  + ]:          11235 :         if (*optstr == '\0')
 6118 tgl@sss.pgh.pa.us         518                 :UBC           0 :             break;
                                519                 :                : 
                                520                 :                :         /*
                                521                 :                :          * Parse a single option, stopping at the first space, unless it's
                                522                 :                :          * escaped.
                                523                 :                :          */
 4293 andres@anarazel.de        524         [ +  + ]:CBC      171703 :         while (*optstr)
                                525                 :                :         {
 4289 tgl@sss.pgh.pa.us         526   [ +  +  +  + ]:         167484 :             if (isspace((unsigned char) *optstr) && !last_was_escape)
 4293 andres@anarazel.de        527                 :           7016 :                 break;
                                528                 :                : 
                                529   [ +  +  +  + ]:         160468 :             if (!last_was_escape && *optstr == '\\')
                                530                 :             20 :                 last_was_escape = true;
                                531                 :                :             else
                                532                 :                :             {
                                533                 :         160448 :                 last_was_escape = false;
                                534                 :         160448 :                 appendStringInfoChar(&s, *optstr);
                                535                 :                :             }
                                536                 :                : 
 6118 tgl@sss.pgh.pa.us         537                 :         160468 :             optstr++;
                                538                 :                :         }
                                539                 :                : 
                                540                 :                :         /* now store the option in the next argv[] position */
 4293 andres@anarazel.de        541                 :          11235 :         argv[(*argcp)++] = pstrdup(s.data);
                                542                 :                :     }
                                543                 :                : 
 3988 tgl@sss.pgh.pa.us         544                 :           4219 :     pfree(s.data);
 6118                           545                 :           4219 : }
                                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
 4896 alvherre@alvh.no-ip.      559                 :           1246 : InitializeMaxBackends(void)
                                560                 :                : {
 1509 rhaas@postgresql.org      561         [ -  + ]:           1246 :     Assert(MaxBackends == 0);
                                562                 :                : 
                                563                 :                :     /* Note that this does not include "auxiliary" processes */
  509 nathan@postgresql.or      564                 :           1246 :     MaxBackends = MaxConnections + autovacuum_worker_slots +
  518 tgl@sss.pgh.pa.us         565                 :           1246 :         max_worker_processes + max_wal_senders + NUM_SPECIAL_WORKER_PROCS;
                                566                 :                : 
 1509 rhaas@postgresql.org      567         [ -  + ]:           1246 :     if (MaxBackends > MAX_BACKENDS)
  694 nathan@postgresql.or      568         [ #  # ]:UBC           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))));
 1355 tgl@sss.pgh.pa.us         575                 :CBC        1246 : }
                                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
  616 tomas.vondra@postgre      584                 :           1246 : InitializeFastPathLocks(void)
                                585                 :                : {
                                586                 :                :     /* Should be initialized only once. */
                                587         [ -  + ]:           1246 :     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 = 128 means 8 groups by default.
                                597                 :                :      */
  398 drowley@postgresql.o      598                 :           1246 :     FastPathLockGroupsPerBackend =
                                599   [ +  -  +  -  :           1246 :         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         [ -  + ]:           1246 :     Assert(FastPathLockGroupsPerBackend ==
                                604                 :                :            pg_nextpower2_32(FastPathLockGroupsPerBackend));
  616 tomas.vondra@postgre      605                 :           1246 : }
                                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
 9294 tgl@sss.pgh.pa.us         616                 :          23199 : BaseInit(void)
                                617                 :                : {
 1759 andres@anarazel.de        618         [ -  + ]:          23199 :     Assert(MyProc != NULL);
                                619                 :                : 
                                620                 :                :     /*
                                621                 :                :      * Initialize our input/output/debugging file descriptors.
                                622                 :                :      */
 9294 tgl@sss.pgh.pa.us         623                 :          23199 :     DebugFileOpen();
                                624                 :                : 
                                625                 :                :     /*
                                626                 :                :      * Initialize file access. Done early so other subsystems can access
                                627                 :                :      * files.
                                628                 :                :      */
 1757 andres@anarazel.de        629                 :          23199 :     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                 :                :      */
 1758                           637                 :          23199 :     pgstat_initialize();
                                638                 :                : 
                                639                 :                :     /*
                                640                 :                :      * Initialize AIO before infrastructure that might need to actually
                                641                 :                :      * execute AIO.
                                642                 :                :      */
  439                           643                 :          23199 :     pgaio_init_backend();
                                644                 :                : 
                                645                 :                :     /* Do local initialization of storage and buffer managers */
 2613 tmunro@postgresql.or      646                 :          23199 :     InitSync();
 9294 tgl@sss.pgh.pa.us         647                 :          23199 :     smgrinit();
  639 heikki.linnakangas@i      648                 :          23199 :     InitBufferManagerAccess();
                                649                 :                : 
                                650                 :                :     /*
                                651                 :                :      * Initialize temporary file access after pgstat, so that the temporary
                                652                 :                :      * file shutdown hook can report temporary file statistics.
                                653                 :                :      */
 1757 andres@anarazel.de        654                 :          23199 :     InitTemporaryFileAccess();
                                655                 :                : 
                                656                 :                :     /*
                                657                 :                :      * Initialize local buffers for WAL record construction, in case we ever
                                658                 :                :      * try to insert XLOG.
                                659                 :                :      */
 1656 rhaas@postgresql.org      660                 :          23199 :     InitXLogInsert();
                                661                 :                : 
                                662                 :                :     /* Initialize lock manager's local structs */
  639 heikki.linnakangas@i      663                 :          23199 :     InitLockManagerAccess();
                                664                 :                : 
                                665                 :                :     /*
                                666                 :                :      * Initialize replication slots after pgstat. The exit hook might need to
                                667                 :                :      * drop ephemeral slots, which in turn triggers stats reporting.
                                668                 :                :      */
 1566 andres@anarazel.de        669                 :          23199 :     ReplicationSlotInitialize();
 9294 tgl@sss.pgh.pa.us         670                 :          23199 : }
                                671                 :                : 
                                672                 :                : 
                                673                 :                : /* --------------------------------
                                674                 :                :  * InitPostgres
                                675                 :                :  *      Initialize POSTGRES.
                                676                 :                :  *
                                677                 :                :  * Parameters:
                                678                 :                :  *  in_dbname, dboid: specify database to connect to, as described below
                                679                 :                :  *  username, useroid: specify role to connect as, as described below
                                680                 :                :  *  flags:
                                681                 :                :  *    - INIT_PG_LOAD_SESSION_LIBS to honor [session|local]_preload_libraries.
                                682                 :                :  *    - INIT_PG_OVERRIDE_ALLOW_CONNS to connect despite !datallowconn.
                                683                 :                :  *    - INIT_PG_OVERRIDE_ROLE_LOGIN to connect despite !rolcanlogin.
                                684                 :                :  *  out_dbname: optional output parameter, see below; pass NULL if not used
                                685                 :                :  *
                                686                 :                :  * The database can be specified by name, using the in_dbname parameter, or by
                                687                 :                :  * OID, using the dboid parameter.  Specify NULL or InvalidOid respectively
                                688                 :                :  * for the unused parameter.  If dboid is provided, the actual database
                                689                 :                :  * name can be returned to the caller in out_dbname.  If out_dbname isn't
                                690                 :                :  * NULL, it must point to a buffer of size NAMEDATALEN.
                                691                 :                :  *
                                692                 :                :  * Similarly, the role can be passed by name, using the username parameter,
                                693                 :                :  * or by OID using the useroid parameter.
                                694                 :                :  *
                                695                 :                :  * In bootstrap mode the database and username parameters are NULL/InvalidOid.
                                696                 :                :  * The autovacuum launcher process doesn't specify these parameters either,
                                697                 :                :  * because it only goes far enough to be able to read pg_database; it doesn't
                                698                 :                :  * connect to any particular database.  An autovacuum worker specifies a
                                699                 :                :  * database but not a username; conversely, a physical walsender specifies
                                700                 :                :  * username but not database.
                                701                 :                :  *
                                702                 :                :  * By convention, INIT_PG_LOAD_SESSION_LIBS should be passed in "flags" in
                                703                 :                :  * "interactive" sessions (including standalone backends), but not in
                                704                 :                :  * background processes such as autovacuum.  Note in particular that it
                                705                 :                :  * shouldn't be true in parallel worker processes; those have another
                                706                 :                :  * mechanism for replicating their leader's set of loaded libraries.
                                707                 :                :  *
                                708                 :                :  * We expect that InitProcess() was already called, so we already have a
                                709                 :                :  * PGPROC struct ... but it's not completely filled in yet.
                                710                 :                :  *
                                711                 :                :  * Note:
                                712                 :                :  *      Be very careful with the order of calls in the InitPostgres function.
                                713                 :                :  * --------------------------------
                                714                 :                :  */
                                715                 :                : void
 1405                           716                 :          18793 : InitPostgres(const char *in_dbname, Oid dboid,
                                717                 :                :              const char *username, Oid useroid,
                                718                 :                :              uint32 flags,
                                719                 :                :              char *out_dbname)
                                720                 :                : {
 9634 peter_e@gmx.net           721                 :          18793 :     bool        bootstrap = IsBootstrapProcessingMode();
                                722                 :                :     bool        am_superuser;
                                723                 :                :     char       *fullpath;
                                724                 :                :     char        dbname[NAMEDATALEN];
 1226 rhaas@postgresql.org      725                 :          18793 :     int         nfree = 0;
                                726                 :                : 
 6118 tgl@sss.pgh.pa.us         727         [ +  + ]:          18793 :     elog(DEBUG3, "InitPostgres");
                                728                 :                : 
                                729                 :                :     /*
                                730                 :                :      * Add my PGPROC struct to the ProcArray.
                                731                 :                :      *
                                732                 :                :      * Once I have done this, I am visible to other backends!
                                733                 :                :      */
 7451                           734                 :          18793 :     InitProcessPhase2();
                                735                 :                : 
                                736                 :                :     /* Initialize status reporting */
  452 michael@paquier.xyz       737                 :          18793 :     pgstat_beinit();
                                738                 :                : 
                                739                 :                :     /*
                                740                 :                :      * And initialize an entry in the PgBackendStatus array.  That way, if
                                741                 :                :      * LWLocks or third-party authentication should happen to hang, it is
                                742                 :                :      * possible to retrieve some information about what is going on.
                                743                 :                :      */
                                744         [ +  + ]:          18793 :     if (!bootstrap)
                                745                 :                :     {
                                746                 :          18736 :         pgstat_bestart_initial();
  385                           747                 :          18736 :         INJECTION_POINT("init-pre-auth", NULL);
                                748                 :                :     }
                                749                 :                : 
                                750                 :                :     /*
                                751                 :                :      * Initialize my entry in the shared-invalidation manager's array of
                                752                 :                :      * per-backend data.
                                753                 :                :      */
 6006 simon@2ndQuadrant.co      754                 :          18793 :     SharedInvalBackendInit(false);
                                755                 :                : 
                                756                 :                :     /*
                                757                 :                :      * Prevent consuming interrupts between setting ProcSignalInit and setting
                                758                 :                :      * the initial local data checksum value.  If a barrier is emitted, and
                                759                 :                :      * absorbed, before local cached state is initialized the state transition
                                760                 :                :      * can be invalid.
                                761                 :                :      */
   30 dgustafsson@postgres      762                 :GNC       18793 :     HOLD_INTERRUPTS();
                                763                 :                : 
  423 heikki.linnakangas@i      764                 :CBC       18793 :     ProcSignalInit(MyCancelKey, MyCancelKeyLength);
                                765                 :                : 
                                766                 :                :     /*
                                767                 :                :      * Initialize a local cache of the data_checksum_version, to be updated by
                                768                 :                :      * the procsignal-based barriers.
                                769                 :                :      *
                                770                 :                :      * This intentionally happens after initializing the procsignal, otherwise
                                771                 :                :      * we might miss a state change. This means we can get a barrier for the
                                772                 :                :      * state we've just initialized.
                                773                 :                :      *
                                774                 :                :      * The postmaster (which is what gets forked into the new child process)
                                775                 :                :      * does not handle barriers, therefore it may not have the current value
                                776                 :                :      * of LocalDataChecksumState value (it'll have the value read from the
                                777                 :                :      * control file, which may be arbitrarily old).
                                778                 :                :      *
                                779                 :                :      * NB: Even if the postmaster handled barriers, the value might still be
                                780                 :                :      * stale, as it might have changed after this process forked.
                                781                 :                :      */
   57 dgustafsson@postgres      782                 :GNC       18793 :     InitLocalDataChecksumState();
                                783                 :                : 
   30                           784         [ -  + ]:          18793 :     RESUME_INTERRUPTS();
                                785                 :                : 
                                786                 :                :     /*
                                787                 :                :      * Also set up timeout handlers needed for backend operation.  We need
                                788                 :                :      * these in every case except bootstrap.
                                789                 :                :      */
 5066 alvherre@alvh.no-ip.      790         [ +  + ]:CBC       18793 :     if (!bootstrap)
                                791                 :                :     {
 4134 andres@anarazel.de        792                 :          18736 :         RegisterTimeout(DEADLOCK_TIMEOUT, CheckDeadLockAlert);
 5066 alvherre@alvh.no-ip.      793                 :          18736 :         RegisterTimeout(STATEMENT_TIMEOUT, StatementTimeoutHandler);
 4823 tgl@sss.pgh.pa.us         794                 :          18736 :         RegisterTimeout(LOCK_TIMEOUT, LockTimeoutHandler);
 3727 rhaas@postgresql.org      795                 :          18736 :         RegisterTimeout(IDLE_IN_TRANSACTION_SESSION_TIMEOUT,
                                796                 :                :                         IdleInTransactionSessionTimeoutHandler);
  835 akorotkov@postgresql      797                 :          18736 :         RegisterTimeout(TRANSACTION_TIMEOUT, TransactionTimeoutHandler);
 1970 tgl@sss.pgh.pa.us         798                 :          18736 :         RegisterTimeout(IDLE_SESSION_TIMEOUT, IdleSessionTimeoutHandler);
 1883 tmunro@postgresql.or      799                 :          18736 :         RegisterTimeout(CLIENT_CONNECTION_CHECK_TIMEOUT, ClientCheckTimeoutHandler);
 1515 andres@anarazel.de        800                 :          18736 :         RegisterTimeout(IDLE_STATS_UPDATE_TIMEOUT,
                                801                 :                :                         IdleStatsUpdateTimeoutHandler);
                                802                 :                :     }
                                803                 :                : 
                                804                 :                :     /*
                                805                 :                :      * If this is either a bootstrap process or a standalone backend, start up
                                806                 :                :      * the XLOG machinery, and register to have it closed down at exit. In
                                807                 :                :      * other cases, the startup process is responsible for starting up the
                                808                 :                :      * XLOG machinery, and the checkpointer for closing it down.
                                809                 :                :      */
 1629 rhaas@postgresql.org      810         [ +  + ]:          18793 :     if (!IsUnderPostmaster)
                                811                 :                :     {
                                812                 :                :         /*
                                813                 :                :          * We don't yet have an aux-process resource owner, but StartupXLOG
                                814                 :                :          * and ShutdownXLOG will need one.  Hence, create said resource owner
                                815                 :                :          * (and register a callback to clean it up after ShutdownXLOG runs).
                                816                 :                :          */
 2873 tgl@sss.pgh.pa.us         817                 :            133 :         CreateAuxProcessResourceOwner();
                                818                 :                : 
 5884                           819                 :            133 :         StartupXLOG();
                                820                 :                :         /* Release (and warn about) any buffer pins leaked in StartupXLOG */
 2873                           821                 :            133 :         ReleaseAuxProcessResources(true);
                                822                 :                :         /* Reset CurrentResourceOwner to nothing for the moment */
                                823                 :            133 :         CurrentResourceOwner = NULL;
                                824                 :                : 
                                825                 :                :         /*
                                826                 :                :          * Use before_shmem_exit() so that ShutdownXLOG() can rely on DSM
                                827                 :                :          * segments etc to work (which in turn is required for pgstats).
                                828                 :                :          */
 1515 andres@anarazel.de        829                 :            133 :         before_shmem_exit(pgstat_before_server_shutdown, 0);
 1891                           830                 :            133 :         before_shmem_exit(ShutdownXLOG, 0);
                                831                 :                :     }
                                832                 :                : 
                                833                 :                :     /*
                                834                 :                :      * Initialize the process-local logical info WAL logging state.
                                835                 :                :      *
                                836                 :                :      * This must be called after ProcSignalInit() so that the process can
                                837                 :                :      * participate in procsignal-based barriers that update this state.
                                838                 :                :      * Furthermore, in !IsUnderPostmaster cases, this must occur after
                                839                 :                :      * StartupXLOG() where the shared state is first established.
                                840                 :                :      */
   23 msawada@postgresql.o      841                 :GNC       18793 :     InitializeProcessXLogLogicalInfo();
                                842                 :                : 
                                843                 :                :     /*
                                844                 :                :      * Initialize the relation cache and the system catalog caches.  Note that
                                845                 :                :      * no catalog access happens here; we only set up the hashtable structure.
                                846                 :                :      * We must do this before starting a transaction because transaction abort
                                847                 :                :      * would try to touch these hashtables.
                                848                 :                :      */
 9044 tgl@sss.pgh.pa.us         849                 :CBC       18793 :     RelationCacheInitialize();
10492 bruce@momjian.us          850                 :          18793 :     InitCatalogCache();
 7018 tgl@sss.pgh.pa.us         851                 :          18793 :     InitPlanCache();
                                852                 :                : 
                                853                 :                :     /* Initialize portal manager */
 9114                           854                 :          18793 :     EnablePortalManager();
                                855                 :                : 
                                856                 :                :     /*
                                857                 :                :      * Load relcache entries for the shared system catalogs.  This must create
                                858                 :                :      * at least entries for pg_database and catalogs used for authentication.
                                859                 :                :      */
 6116                           860                 :          18793 :     RelationCacheInitializePhase2();
                                861                 :                : 
                                862                 :                :     /*
                                863                 :                :      * Set up process-exit callback to do pre-shutdown cleanup.  This is one
                                864                 :                :      * of the first before_shmem_exit callbacks we register; thus, this will
                                865                 :                :      * be one of the last things we do before low-level modules like the
                                866                 :                :      * buffer manager begin to close down.  We need to have this in place
                                867                 :                :      * before we begin our first transaction --- if we fail during the
                                868                 :                :      * initialization transaction, as is entirely possible, we need the
                                869                 :                :      * AbortTransaction call to clean up.
                                870                 :                :      */
 4546 rhaas@postgresql.org      871                 :          18793 :     before_shmem_exit(ShutdownPostgres, 0);
                                872                 :                : 
                                873                 :                :     /* The autovacuum launcher is done here */
  817 heikki.linnakangas@i      874         [ +  + ]:          18793 :     if (AmAutoVacuumLauncherProcess())
                                875                 :                :     {
                                876                 :                :         /* fill in the remainder of this entry in the PgBackendStatus array */
  452 michael@paquier.xyz       877                 :            480 :         pgstat_bestart_final();
                                878                 :                : 
 6115 tgl@sss.pgh.pa.us         879                 :           1523 :         return;
                                880                 :                :     }
                                881                 :                : 
                                882                 :                :     /*
                                883                 :                :      * Start a new transaction here before first access to db.
                                884                 :                :      */
 9656 inoue@tpf.co.jp           885         [ +  + ]:          18313 :     if (!bootstrap)
                                886                 :                :     {
                                887                 :                :         /* statement_timestamp must be set for timeouts to work correctly */
 5404 tgl@sss.pgh.pa.us         888                 :          18256 :         SetCurrentStatementStartTimestamp();
 8417                           889                 :          18256 :         StartTransactionCommand();
                                890                 :                : 
                                891                 :                :         /*
                                892                 :                :          * transaction_isolation will have been set to the default by the
                                893                 :                :          * above.  If the default is "serializable", and we are in hot
                                894                 :                :          * standby, we will fail if we don't change it to something lower.
                                895                 :                :          * Fortunately, "read committed" is plenty good enough.
                                896                 :                :          */
 5027                           897                 :          18256 :         XactIsoLevel = XACT_READ_COMMITTED;
                                898                 :                :     }
                                899                 :                : 
                                900                 :                :     /*
                                901                 :                :      * Perform client authentication if necessary, then figure out our
                                902                 :                :      * postgres user ID, and see if we are a superuser.
                                903                 :                :      *
                                904                 :                :      * In standalone mode, autovacuum worker processes and slot sync worker
                                905                 :                :      * process, we use a fixed ID, otherwise we figure it out from the
                                906                 :                :      * authenticated user name.
                                907                 :                :      */
  817 heikki.linnakangas@i      908   [ +  +  +  +  :          18313 :     if (bootstrap || AmAutoVacuumWorkerProcess() || AmLogicalSlotSyncWorkerProcess())
                                              +  + ]
                                909                 :                :     {
 5884 tgl@sss.pgh.pa.us         910                 :            126 :         InitializeSessionUserIdStandalone();
                                911                 :            126 :         am_superuser = true;
                                912                 :                :     }
                                913         [ +  + ]:          18187 :     else if (!IsUnderPostmaster)
                                914                 :                :     {
                                915                 :             76 :         InitializeSessionUserIdStandalone();
                                916                 :             76 :         am_superuser = true;
                                917         [ -  + ]:             76 :         if (!ThereIsAtLeastOneRole())
 5884 tgl@sss.pgh.pa.us         918   [ #  #  #  # ]:UBC           0 :             ereport(WARNING,
                                919                 :                :                     (errcode(ERRCODE_UNDEFINED_OBJECT),
                                920                 :                :                      errmsg("no roles are defined in this database system"),
                                921                 :                :                      errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
                                922                 :                :                              username != NULL ? username : "postgres")));
                                923                 :                :     }
   57 dgustafsson@postgres      924   [ +  +  +  +  :GNC       18111 :     else if (AmBackgroundWorkerProcess() || AmDataChecksumsWorkerProcess())
                                              +  + ]
                                925                 :                :     {
 4135 rhaas@postgresql.org      926   [ +  -  +  + ]:CBC        3165 :         if (username == NULL && !OidIsValid(useroid))
                                927                 :                :         {
 4923 alvherre@alvh.no-ip.      928                 :            560 :             InitializeSessionUserIdStandalone();
                                929                 :            560 :             am_superuser = true;
                                930                 :                :         }
                                931                 :                :         else
                                932                 :                :         {
  961 michael@paquier.xyz       933                 :           2605 :             InitializeSessionUserId(username, useroid,
                                934                 :           2605 :                                     (flags & INIT_PG_OVERRIDE_ROLE_LOGIN) != 0);
  518 tgl@sss.pgh.pa.us         935                 :           2603 :             am_superuser = superuser();
                                936                 :                :         }
                                937                 :                :     }
                                938                 :                :     else
                                939                 :                :     {
                                940                 :                :         /* normal multiuser case */
 5884                           941         [ -  + ]:          14946 :         Assert(MyProcPort != NULL);
                                942                 :          14946 :         PerformAuthentication(MyProcPort);
  961 michael@paquier.xyz       943                 :          14739 :         InitializeSessionUserId(username, useroid, false);
                                944                 :                :         /* ensure that auth_method is actually valid, aka authn_id is not NULL */
 1339                           945         [ +  + ]:          14735 :         if (MyClientConnectionInfo.authn_id)
                                946                 :            192 :             InitializeSystemUser(MyClientConnectionInfo.authn_id,
                                947                 :                :                                  hba_authname(MyClientConnectionInfo.auth_method));
 5884 tgl@sss.pgh.pa.us         948                 :          14735 :         am_superuser = superuser();
                                949                 :                :     }
                                950                 :                : 
                                951                 :                :     /* Report any SSL/GSS details for the session. */
  452 michael@paquier.xyz       952         [ +  + ]:          18100 :     if (MyProcPort != NULL)
                                953                 :                :     {
                                954         [ -  + ]:          14735 :         Assert(!bootstrap);
                                955                 :                : 
                                956                 :          14735 :         pgstat_bestart_security();
                                957                 :                :     }
                                958                 :                : 
                                959                 :                :     /*
                                960                 :                :      * Binary upgrades only allowed super-user connections
                                961                 :                :      */
 5514 bruce@momjian.us          962   [ +  +  -  + ]:          18100 :     if (IsBinaryUpgrade && !am_superuser)
                                963                 :                :     {
 5469 bruce@momjian.us          964         [ #  # ]:UBC           0 :         ereport(FATAL,
                                965                 :                :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
                                966                 :                :                  errmsg("must be superuser to connect in binary upgrade mode")));
                                967                 :                :     }
                                968                 :                : 
                                969                 :                :     /*
                                970                 :                :      * The last few regular connection slots are reserved for superusers and
                                971                 :                :      * roles with privileges of pg_use_reserved_connections.  We do not apply
                                972                 :                :      * these limits to background processes, since they all have their own
                                973                 :                :      * pools of PGPROC slots.
                                974                 :                :      *
                                975                 :                :      * Note: At this point, the new backend has already claimed a proc struct,
                                976                 :                :      * so we must check whether the number of free slots is strictly less than
                                977                 :                :      * the reserved connection limits.
                                978                 :                :      */
  518 tgl@sss.pgh.pa.us         979   [ +  +  +  + ]:CBC       18100 :     if (AmRegularBackendProcess() && !am_superuser &&
 1226 rhaas@postgresql.org      980         [ +  - ]:            415 :         (SuperuserReservedConnections + ReservedConnections) > 0 &&
                                981         [ +  + ]:            415 :         !HaveNFreeProcs(SuperuserReservedConnections + ReservedConnections, &nfree))
                                982                 :                :     {
                                983         [ +  + ]:              4 :         if (nfree < SuperuserReservedConnections)
                                984         [ +  - ]:              1 :             ereport(FATAL,
                                985                 :                :                     (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
                                986                 :                :                      errmsg("remaining connection slots are reserved for roles with the %s attribute",
                                987                 :                :                             "SUPERUSER")));
                                988                 :                : 
                                989         [ +  + ]:              3 :         if (!has_privs_of_role(GetUserId(), ROLE_PG_USE_RESERVED_CONNECTIONS))
                                990         [ +  - ]:              1 :             ereport(FATAL,
                                991                 :                :                     (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
                                992                 :                :                      errmsg("remaining connection slots are reserved for roles with privileges of the \"%s\" role",
                                993                 :                :                             "pg_use_reserved_connections")));
                                994                 :                :     }
                                995                 :                : 
                                996                 :                :     /* Check replication permissions needed for walsender processes. */
 5884 tgl@sss.pgh.pa.us         997         [ +  + ]:          18098 :     if (am_walsender)
                                998                 :                :     {
                                999         [ -  + ]:           1291 :         Assert(!bootstrap);
                               1000                 :                : 
 1171 peter@eisentraut.org     1001         [ -  + ]:           1291 :         if (!has_rolreplication(GetUserId()))
 5883 tgl@sss.pgh.pa.us        1002         [ #  # ]:UBC           0 :             ereport(FATAL,
                               1003                 :                :                     (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
                               1004                 :                :                      errmsg("permission denied to start WAL sender"),
                               1005                 :                :                      errdetail("Only roles with the %s attribute may start a WAL sender process.",
                               1006                 :                :                                "REPLICATION")));
                               1007                 :                :     }
                               1008                 :                : 
                               1009                 :                :     /*
                               1010                 :                :      * If this is a plain walsender only supporting physical replication, we
                               1011                 :                :      * don't want to connect to any particular database. Just finish the
                               1012                 :                :      * backend startup by processing any options from the startup packet, and
                               1013                 :                :      * we're done.
                               1014                 :                :      */
 4464 rhaas@postgresql.org     1015   [ +  +  +  + ]:CBC       18098 :     if (am_walsender && !am_db_walsender)
                               1016                 :                :     {
                               1017                 :                :         /* process any options passed in the startup packet */
 5738 heikki.linnakangas@i     1018         [ +  - ]:            513 :         if (MyProcPort != NULL)
                               1019                 :            513 :             process_startup_options(MyProcPort, am_superuser);
                               1020                 :                : 
                               1021                 :                :         /* Apply PostAuthDelay as soon as we've read all options */
                               1022         [ -  + ]:            513 :         if (PostAuthDelay > 0)
 5738 heikki.linnakangas@i     1023                 :UBC           0 :             pg_usleep(PostAuthDelay * 1000000L);
                               1024                 :                : 
                               1025                 :                :         /* initialize client encoding */
 5738 heikki.linnakangas@i     1026                 :CBC         513 :         InitializeClientEncoding();
                               1027                 :                : 
                               1028                 :                :         /* fill in the remainder of this entry in the PgBackendStatus array */
  452 michael@paquier.xyz      1029                 :            513 :         pgstat_bestart_final();
                               1030                 :                : 
                               1031                 :                :         /* close the transaction we started above */
 5884 tgl@sss.pgh.pa.us        1032                 :            513 :         CommitTransactionCommand();
                               1033                 :                : 
                               1034                 :                :         /* send any WARNINGs we've accumulated during initialization */
  108 nathan@postgresql.or     1035                 :GNC         513 :         EmitConnectionWarnings();
                               1036                 :                : 
 5884 tgl@sss.pgh.pa.us        1037                 :CBC         513 :         return;
                               1038                 :                :     }
                               1039                 :                : 
                               1040                 :                :     /*
                               1041                 :                :      * Set up the global variables holding database id and default tablespace.
                               1042                 :                :      * But note we won't actually try to touch the database just yet.
                               1043                 :                :      *
                               1044                 :                :      * We take a shortcut in the bootstrap case, otherwise we have to look up
                               1045                 :                :      * the db's entry in pg_database.
                               1046                 :                :      */
                               1047         [ +  + ]:          17585 :     if (bootstrap)
                               1048                 :                :     {
  999 michael@paquier.xyz      1049                 :             57 :         dboid = Template1DbOid;
 6135 tgl@sss.pgh.pa.us        1050                 :             57 :         MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
                               1051                 :                :     }
                               1052         [ +  + ]:          17528 :     else if (in_dbname != NULL)
                               1053                 :                :     {
                               1054                 :                :         HeapTuple   tuple;
                               1055                 :                :         Form_pg_database dbform;
                               1056                 :                : 
                               1057                 :          14302 :         tuple = GetDatabaseTuple(in_dbname);
                               1058         [ +  + ]:          14302 :         if (!HeapTupleIsValid(tuple))
                               1059         [ +  - ]:              6 :             ereport(FATAL,
                               1060                 :                :                     (errcode(ERRCODE_UNDEFINED_DATABASE),
                               1061                 :                :                      errmsg("database \"%s\" does not exist", in_dbname)));
                               1062                 :          14296 :         dbform = (Form_pg_database) GETSTRUCT(tuple);
  999 michael@paquier.xyz      1063                 :          14296 :         dboid = dbform->oid;
                               1064                 :                :     }
                               1065         [ +  + ]:           3226 :     else if (!OidIsValid(dboid))
                               1066                 :                :     {
                               1067                 :                :         /*
                               1068                 :                :          * If this is a background worker not bound to any particular
                               1069                 :                :          * database, we're done now.  Everything that follows only makes sense
                               1070                 :                :          * if we are bound to a specific database.  We do need to close the
                               1071                 :                :          * transaction we started before returning.
                               1072                 :                :          */
 3992 rhaas@postgresql.org     1073         [ +  - ]:            530 :         if (!bootstrap)
                               1074                 :                :         {
  452 michael@paquier.xyz      1075                 :            530 :             pgstat_bestart_final();
 3992 rhaas@postgresql.org     1076                 :            530 :             CommitTransactionCommand();
                               1077                 :                :         }
                               1078                 :            530 :         return;
                               1079                 :                :     }
                               1080                 :                : 
                               1081                 :                :     /*
                               1082                 :                :      * Now, take a writer's lock on the database we are trying to connect to.
                               1083                 :                :      * If there is a concurrently running DROP DATABASE on that database, this
                               1084                 :                :      * will block us until it finishes (and has committed its update of
                               1085                 :                :      * pg_database).
                               1086                 :                :      *
                               1087                 :                :      * Note that the lock is not held long, only until the end of this startup
                               1088                 :                :      * transaction.  This is OK since we will advertise our use of the
                               1089                 :                :      * database in the ProcArray before dropping the lock (in fact, that's the
                               1090                 :                :      * next thing to do).  Anyone trying a DROP DATABASE after this point will
                               1091                 :                :      * see us in the array once they have the lock.  Ordering is important for
                               1092                 :                :      * this because we don't want to advertise ourselves as being in this
                               1093                 :                :      * database until we have the lock; otherwise we create what amounts to a
                               1094                 :                :      * deadlock with CountOtherDBBackends().
                               1095                 :                :      *
                               1096                 :                :      * Note: use of RowExclusiveLock here is reasonable because we envision
                               1097                 :                :      * our session as being a concurrent writer of the database.  If we had a
                               1098                 :                :      * way of declaring a session as being guaranteed-read-only, we could use
                               1099                 :                :      * AccessShareLock for such sessions and thereby not conflict against
                               1100                 :                :      * CREATE DATABASE.
                               1101                 :                :      */
 5884 tgl@sss.pgh.pa.us        1102         [ +  + ]:          17049 :     if (!bootstrap)
  999 michael@paquier.xyz      1103                 :          16992 :         LockSharedObject(DatabaseRelationId, dboid, 0, RowExclusiveLock);
                               1104                 :                : 
                               1105                 :                :     /*
                               1106                 :                :      * Recheck pg_database to make sure the target database hasn't gone away.
                               1107                 :                :      * If there was a concurrent DROP DATABASE, this ensures we will die
                               1108                 :                :      * cleanly without creating a mess.
                               1109                 :                :      */
                               1110         [ +  + ]:          17049 :     if (!bootstrap)
                               1111                 :                :     {
                               1112                 :                :         HeapTuple   tuple;
                               1113                 :                :         Form_pg_database datform;
                               1114                 :                : 
                               1115                 :          16992 :         tuple = GetDatabaseTupleByOid(dboid);
                               1116         [ +  - ]:          16992 :         if (HeapTupleIsValid(tuple))
                               1117                 :          16992 :             datform = (Form_pg_database) GETSTRUCT(tuple);
                               1118                 :                : 
                               1119   [ +  -  +  + ]:          16992 :         if (!HeapTupleIsValid(tuple) ||
                               1120         [ -  + ]:          14296 :             (in_dbname && namestrcmp(&datform->datname, in_dbname)))
                               1121                 :                :         {
  999 michael@paquier.xyz      1122         [ #  # ]:UBC           0 :             if (in_dbname)
                               1123         [ #  # ]:              0 :                 ereport(FATAL,
                               1124                 :                :                         (errcode(ERRCODE_UNDEFINED_DATABASE),
                               1125                 :                :                          errmsg("database \"%s\" does not exist", in_dbname),
                               1126                 :                :                          errdetail("It seems to have just been dropped or renamed.")));
                               1127                 :                :             else
                               1128         [ #  # ]:              0 :                 ereport(FATAL,
                               1129                 :                :                         (errcode(ERRCODE_UNDEFINED_DATABASE),
                               1130                 :                :                          errmsg("database %u does not exist", dboid)));
                               1131                 :                :         }
                               1132                 :                : 
  999 michael@paquier.xyz      1133                 :CBC       16992 :         strlcpy(dbname, NameStr(datform->datname), sizeof(dbname));
                               1134                 :                : 
                               1135         [ +  + ]:          16992 :         if (database_is_invalid_form(datform))
                               1136                 :                :         {
                               1137         [ +  - ]:              5 :             ereport(FATAL,
                               1138                 :                :                     errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                               1139                 :                :                     errmsg("cannot connect to invalid database \"%s\"", dbname),
                               1140                 :                :                     errhint("Use DROP DATABASE to drop invalid databases."));
                               1141                 :                :         }
                               1142                 :                : 
                               1143                 :          16987 :         MyDatabaseTableSpace = datform->dattablespace;
  957 akorotkov@postgresql     1144                 :          16987 :         MyDatabaseHasLoginEventTriggers = datform->dathasloginevt;
                               1145                 :                :         /* pass the database name back to the caller */
  999 michael@paquier.xyz      1146         [ +  + ]:          16987 :         if (out_dbname)
                               1147                 :             63 :             strcpy(out_dbname, dbname);
                               1148                 :                :     }
                               1149                 :                : 
                               1150                 :                :     /*
                               1151                 :                :      * Now that we rechecked, we are certain to be connected to a database and
                               1152                 :                :      * thus can set MyDatabaseId.
                               1153                 :                :      *
                               1154                 :                :      * It is important that MyDatabaseId only be set once we are sure that the
                               1155                 :                :      * target database can no longer be concurrently dropped or renamed.  For
                               1156                 :                :      * example, without this guarantee, pgstat_update_dbstats() could create
                               1157                 :                :      * entries for databases that were just dropped in the pgstat shutdown
                               1158                 :                :      * callback, which could confuse other code paths like the autovacuum
                               1159                 :                :      * scheduler.
                               1160                 :                :      */
                               1161                 :          17044 :     MyDatabaseId = dboid;
                               1162                 :                : 
                               1163                 :                :     /*
                               1164                 :                :      * Now we can mark our PGPROC entry with the database ID.
                               1165                 :                :      *
                               1166                 :                :      * We assume this is an atomic store so no lock is needed; though actually
                               1167                 :                :      * things would work fine even if it weren't atomic.  Anyone searching the
                               1168                 :                :      * ProcArray for this database's ID should hold the database lock, so they
                               1169                 :                :      * would not be executing concurrently with this store.  A process looking
                               1170                 :                :      * for another database's ID could in theory see a chance match if it read
                               1171                 :                :      * a partially-updated databaseId value; but as long as all such searches
                               1172                 :                :      * wait and retry, as in CountOtherDBBackends(), they will certainly see
                               1173                 :                :      * the correct value on their next try.
                               1174                 :                :      */
 4012 tgl@sss.pgh.pa.us        1175                 :          17044 :     MyProc->databaseId = MyDatabaseId;
                               1176                 :                : 
                               1177                 :                :     /*
                               1178                 :                :      * We established a catalog snapshot while reading pg_authid and/or
                               1179                 :                :      * pg_database; but until we have set up MyDatabaseId, we won't react to
                               1180                 :                :      * incoming sinval messages for unshared catalogs, so we won't realize it
                               1181                 :                :      * if the snapshot has been invalidated.  Assume it's no good anymore.
                               1182                 :                :      */
                               1183                 :          17044 :     InvalidateCatalogSnapshot();
                               1184                 :                : 
                               1185                 :                :     /*
                               1186                 :                :      * Now we should be able to access the database directory safely. Verify
                               1187                 :                :      * it's there and looks reasonable.
                               1188                 :                :      */
 6135                          1189                 :          17044 :     fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace);
                               1190                 :                : 
 5884                          1191         [ +  + ]:          17044 :     if (!bootstrap)
                               1192                 :                :     {
 7331                          1193         [ -  + ]:          16987 :         if (access(fullpath, F_OK) == -1)
                               1194                 :                :         {
 7331 tgl@sss.pgh.pa.us        1195         [ #  # ]:UBC           0 :             if (errno == ENOENT)
                               1196         [ #  # ]:              0 :                 ereport(FATAL,
                               1197                 :                :                         (errcode(ERRCODE_UNDEFINED_DATABASE),
                               1198                 :                :                          errmsg("database \"%s\" does not exist",
                               1199                 :                :                                 dbname),
                               1200                 :                :                          errdetail("The database subdirectory \"%s\" is missing.",
                               1201                 :                :                                    fullpath)));
                               1202                 :                :             else
                               1203         [ #  # ]:              0 :                 ereport(FATAL,
                               1204                 :                :                         (errcode_for_file_access(),
                               1205                 :                :                          errmsg("could not access directory \"%s\": %m",
                               1206                 :                :                                 fullpath)));
                               1207                 :                :         }
                               1208                 :                : 
 7331 tgl@sss.pgh.pa.us        1209                 :CBC       16987 :         ValidatePgVersion(fullpath);
                               1210                 :                :     }
                               1211                 :                : 
 6135                          1212                 :          17044 :     SetDatabasePath(fullpath);
 1496 alvherre@alvh.no-ip.     1213                 :          17044 :     pfree(fullpath);
                               1214                 :                : 
                               1215                 :                :     /*
                               1216                 :                :      * It's now possible to do real access to the system catalogs.
                               1217                 :                :      *
                               1218                 :                :      * Load relcache entries for the system catalogs.  This must create at
                               1219                 :                :      * least the minimum set of "nailed-in" cache entries.
                               1220                 :                :      */
 6135 tgl@sss.pgh.pa.us        1221                 :          17044 :     RelationCacheInitializePhase3();
                               1222                 :                : 
                               1223                 :                :     /* set up ACL framework (so CheckMyDatabase can check permissions) */
 7335                          1224                 :          17041 :     initialize_acl();
                               1225                 :                : 
                               1226                 :                :     /*
                               1227                 :                :      * Re-read the pg_database row for our database, check permissions and set
                               1228                 :                :      * up database-specific GUC settings.  We can't do this until all the
                               1229                 :                :      * database-access infrastructure is up.  (Also, it wants to know if the
                               1230                 :                :      * user is a superuser, so the above stuff has to happen first.)
                               1231                 :                :      */
 5884                          1232         [ +  + ]:          17041 :     if (!bootstrap)
  962 michael@paquier.xyz      1233                 :          16984 :         CheckMyDatabase(dbname, am_superuser,
                               1234                 :          16984 :                         (flags & INIT_PG_OVERRIDE_ALLOW_CONNS) != 0);
                               1235                 :                : 
                               1236                 :                :     /*
                               1237                 :                :      * Now process any command-line switches and any additional GUC variable
                               1238                 :                :      * settings passed in the startup packet.   We couldn't do this before
                               1239                 :                :      * because we didn't know if client is a superuser.
                               1240                 :                :      */
 5738 heikki.linnakangas@i     1241         [ +  + ]:          17038 :     if (MyProcPort != NULL)
                               1242                 :          14209 :         process_startup_options(MyProcPort, am_superuser);
                               1243                 :                : 
                               1244                 :                :     /* Process pg_db_role_setting options */
                               1245                 :          17038 :     process_settings(MyDatabaseId, GetSessionUserId());
                               1246                 :                : 
                               1247                 :                :     /* Apply PostAuthDelay as soon as we've read all options */
                               1248         [ -  + ]:          17035 :     if (PostAuthDelay > 0)
 5738 heikki.linnakangas@i     1249                 :UBC           0 :         pg_usleep(PostAuthDelay * 1000000L);
                               1250                 :                : 
                               1251                 :                :     /*
                               1252                 :                :      * Initialize various default states that can't be set up until we've
                               1253                 :                :      * selected the active user and gotten the right GUC settings.
                               1254                 :                :      */
                               1255                 :                : 
                               1256                 :                :     /* set default namespace search path */
 5738 heikki.linnakangas@i     1257                 :CBC       17035 :     InitializeSearchPath();
                               1258                 :                : 
                               1259                 :                :     /* initialize client encoding */
                               1260                 :          17035 :     InitializeClientEncoding();
                               1261                 :                : 
                               1262                 :                :     /* Initialize this backend's session state. */
 3180 andres@anarazel.de       1263                 :          17035 :     InitializeSession();
                               1264                 :                : 
                               1265                 :                :     /*
                               1266                 :                :      * If this is an interactive session, load any libraries that should be
                               1267                 :                :      * preloaded at backend start.  Since those are determined by GUCs, this
                               1268                 :                :      * can't happen until GUC settings are complete, but we want it to happen
                               1269                 :                :      * during the initial transaction in case anything that requires database
                               1270                 :                :      * access needs to be done.
                               1271                 :                :      */
  962 michael@paquier.xyz      1272         [ +  + ]:          17035 :     if ((flags & INIT_PG_LOAD_SESSION_LIBS) != 0)
 1405 tgl@sss.pgh.pa.us        1273                 :          13505 :         process_session_preload_libraries();
                               1274                 :                : 
                               1275                 :                :     /* fill in the remainder of this entry in the PgBackendStatus array */
 5738 heikki.linnakangas@i     1276         [ +  + ]:          17035 :     if (!bootstrap)
  452 michael@paquier.xyz      1277                 :          16978 :         pgstat_bestart_final();
                               1278                 :                : 
                               1279                 :                :     /* close the transaction we started above */
 5738 heikki.linnakangas@i     1280         [ +  + ]:          17035 :     if (!bootstrap)
                               1281                 :          16978 :         CommitTransactionCommand();
                               1282                 :                : 
                               1283                 :                :     /* send any WARNINGs we've accumulated during initialization */
  108 nathan@postgresql.or     1284                 :GNC       17035 :     EmitConnectionWarnings();
                               1285                 :                : }
                               1286                 :                : 
                               1287                 :                : /*
                               1288                 :                :  * Process any command-line switches and any additional GUC variable
                               1289                 :                :  * settings passed in the startup packet.
                               1290                 :                :  */
                               1291                 :                : static void
 5738 heikki.linnakangas@i     1292                 :CBC       14722 : process_startup_options(Port *port, bool am_superuser)
                               1293                 :                : {
                               1294                 :                :     GucContext  gucctx;
                               1295                 :                :     ListCell   *gucopts;
                               1296                 :                : 
 4277 tgl@sss.pgh.pa.us        1297         [ +  + ]:          14722 :     gucctx = am_superuser ? PGC_SU_BACKEND : PGC_BACKEND;
                               1298                 :                : 
                               1299                 :                :     /*
                               1300                 :                :      * First process any command-line switches that were included in the
                               1301                 :                :      * startup packet, if we are in a regular backend.
                               1302                 :                :      */
 5738 heikki.linnakangas@i     1303         [ +  + ]:          14722 :     if (port->cmdline_options != NULL)
                               1304                 :                :     {
                               1305                 :                :         /*
                               1306                 :                :          * The maximum possible number of commandline arguments that could
                               1307                 :                :          * come from port->cmdline_options is (strlen + 1) / 2; see
                               1308                 :                :          * pg_split_opts().
                               1309                 :                :          */
                               1310                 :                :         char      **av;
                               1311                 :                :         int         maxac;
                               1312                 :                :         int         ac;
                               1313                 :                : 
                               1314                 :           4219 :         maxac = 2 + (strlen(port->cmdline_options) + 1) / 2;
                               1315                 :                : 
  171 michael@paquier.xyz      1316                 :GNC        4219 :         av = palloc_array(char *, maxac);
 6115 tgl@sss.pgh.pa.us        1317                 :CBC        4219 :         ac = 0;
                               1318                 :                : 
                               1319                 :           4219 :         av[ac++] = "postgres";
                               1320                 :                : 
 5738 heikki.linnakangas@i     1321                 :           4219 :         pg_split_opts(av, &ac, port->cmdline_options);
                               1322                 :                : 
 6115 tgl@sss.pgh.pa.us        1323                 :           4219 :         av[ac] = NULL;
                               1324                 :                : 
                               1325         [ -  + ]:           4219 :         Assert(ac < maxac);
                               1326                 :                : 
 4807                          1327                 :           4219 :         (void) process_postgres_switches(ac, av, gucctx, NULL);
                               1328                 :                :     }
                               1329                 :                : 
                               1330                 :                :     /*
                               1331                 :                :      * Process any additional GUC variable settings passed in startup packet.
                               1332                 :                :      * These are handled exactly like command-line variables.
                               1333                 :                :      */
 5738 heikki.linnakangas@i     1334                 :          14722 :     gucopts = list_head(port->guc_options);
                               1335         [ +  + ]:          35351 :     while (gucopts)
                               1336                 :                :     {
                               1337                 :                :         char       *name;
                               1338                 :                :         char       *value;
                               1339                 :                : 
                               1340                 :          20629 :         name = lfirst(gucopts);
 2511 tgl@sss.pgh.pa.us        1341                 :          20629 :         gucopts = lnext(port->guc_options, gucopts);
                               1342                 :                : 
 5738 heikki.linnakangas@i     1343                 :          20629 :         value = lfirst(gucopts);
 2511 tgl@sss.pgh.pa.us        1344                 :          20629 :         gucopts = lnext(port->guc_options, gucopts);
                               1345                 :                : 
 5738 heikki.linnakangas@i     1346                 :          20629 :         SetConfigOption(name, value, gucctx, PGC_S_CLIENT);
                               1347                 :                :     }
 9294 tgl@sss.pgh.pa.us        1348                 :          14722 : }
                               1349                 :                : 
                               1350                 :                : /*
                               1351                 :                :  * Load GUC settings from pg_db_role_setting.
                               1352                 :                :  *
                               1353                 :                :  * We try specific settings for the database/role combination, as well as
                               1354                 :                :  * general for this database and for this user.
                               1355                 :                :  */
                               1356                 :                : static void
 6079 alvherre@alvh.no-ip.     1357                 :          17038 : process_settings(Oid databaseid, Oid roleid)
                               1358                 :                : {
                               1359                 :                :     Relation    relsetting;
                               1360                 :                :     Snapshot    snapshot;
                               1361                 :                : 
                               1362         [ +  + ]:          17038 :     if (!IsUnderPostmaster)
                               1363                 :            131 :         return;
                               1364                 :                : 
 2686 andres@anarazel.de       1365                 :          16907 :     relsetting = table_open(DbRoleSettingRelationId, AccessShareLock);
                               1366                 :                : 
                               1367                 :                :     /* read all the settings under the same snapshot for efficiency */
 4715 rhaas@postgresql.org     1368                 :          16907 :     snapshot = RegisterSnapshot(GetCatalogSnapshot(DbRoleSettingRelationId));
                               1369                 :                : 
                               1370                 :                :     /* Later settings are ignored if set earlier. */
                               1371                 :          16907 :     ApplySetting(snapshot, databaseid, roleid, relsetting, PGC_S_DATABASE_USER);
                               1372                 :          16904 :     ApplySetting(snapshot, InvalidOid, roleid, relsetting, PGC_S_USER);
                               1373                 :          16904 :     ApplySetting(snapshot, databaseid, InvalidOid, relsetting, PGC_S_DATABASE);
                               1374                 :          16904 :     ApplySetting(snapshot, InvalidOid, InvalidOid, relsetting, PGC_S_GLOBAL);
                               1375                 :                : 
                               1376                 :          16904 :     UnregisterSnapshot(snapshot);
 2686 andres@anarazel.de       1377                 :          16904 :     table_close(relsetting, AccessShareLock);
                               1378                 :                : }
                               1379                 :                : 
                               1380                 :                : /*
                               1381                 :                :  * Backend-shutdown callback.  Do cleanup that we want to be sure happens
                               1382                 :                :  * before all the supporting modules begin to nail their doors shut via
                               1383                 :                :  * their own callbacks.
                               1384                 :                :  *
                               1385                 :                :  * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
                               1386                 :                :  * via separate callbacks that execute before this one.  We don't combine the
                               1387                 :                :  * callbacks because we still want this one to happen if the user-level
                               1388                 :                :  * cleanup fails.
                               1389                 :                :  */
                               1390                 :                : static void
 8205 peter_e@gmx.net          1391                 :          18793 : ShutdownPostgres(int code, Datum arg)
                               1392                 :                : {
                               1393                 :                :     /* Make sure we've killed any active transaction */
 7600 tgl@sss.pgh.pa.us        1394                 :          18793 :     AbortOutOfAnyTransaction();
                               1395                 :                : 
                               1396                 :                :     /*
                               1397                 :                :      * User locks are not released by transaction end, so be sure to release
                               1398                 :                :      * them explicitly.
                               1399                 :                :      */
                               1400                 :          18793 :     LockReleaseAll(USER_LOCKMETHOD, true);
 9733 vadim4o@yahoo.com        1401                 :          18793 : }
                               1402                 :                : 
                               1403                 :                : 
                               1404                 :                : /*
                               1405                 :                :  * STATEMENT_TIMEOUT handler: trigger a query-cancel interrupt.
                               1406                 :                :  */
                               1407                 :                : static void
 5066 alvherre@alvh.no-ip.     1408                 :              6 : StatementTimeoutHandler(void)
                               1409                 :                : {
 4025 bruce@momjian.us         1410                 :              6 :     int         sig = SIGINT;
                               1411                 :                : 
                               1412                 :                :     /*
                               1413                 :                :      * During authentication the timeout is used to deal with
                               1414                 :                :      * authentication_timeout - we want to quit in response to such timeouts.
                               1415                 :                :      */
 4134 andres@anarazel.de       1416         [ -  + ]:              6 :     if (ClientAuthInProgress)
 4134 andres@anarazel.de       1417                 :UBC           0 :         sig = SIGTERM;
                               1418                 :                : 
                               1419                 :                : #ifdef HAVE_SETSID
                               1420                 :                :     /* try to signal whole process group */
 4134 andres@anarazel.de       1421                 :CBC           6 :     kill(-MyProcPid, sig);
                               1422                 :                : #endif
                               1423                 :              6 :     kill(MyProcPid, sig);
 5066 alvherre@alvh.no-ip.     1424                 :              6 : }
                               1425                 :                : 
                               1426                 :                : /*
                               1427                 :                :  * LOCK_TIMEOUT handler: trigger a query-cancel interrupt.
                               1428                 :                :  */
                               1429                 :                : static void
 4823 tgl@sss.pgh.pa.us        1430                 :              4 : LockTimeoutHandler(void)
                               1431                 :                : {
                               1432                 :                : #ifdef HAVE_SETSID
                               1433                 :                :     /* try to signal whole process group */
                               1434                 :              4 :     kill(-MyProcPid, SIGINT);
                               1435                 :                : #endif
                               1436                 :              4 :     kill(MyProcPid, SIGINT);
                               1437                 :              4 : }
                               1438                 :                : 
                               1439                 :                : static void
  835 akorotkov@postgresql     1440                 :              1 : TransactionTimeoutHandler(void)
                               1441                 :                : {
                               1442                 :              1 :     TransactionTimeoutPending = true;
                               1443                 :              1 :     InterruptPending = true;
                               1444                 :              1 :     SetLatch(MyLatch);
                               1445                 :              1 : }
                               1446                 :                : 
                               1447                 :                : static void
 3727 rhaas@postgresql.org     1448                 :              1 : IdleInTransactionSessionTimeoutHandler(void)
                               1449                 :                : {
                               1450                 :              1 :     IdleInTransactionSessionTimeoutPending = true;
                               1451                 :              1 :     InterruptPending = true;
                               1452                 :              1 :     SetLatch(MyLatch);
                               1453                 :              1 : }
                               1454                 :                : 
                               1455                 :                : static void
 1970 tgl@sss.pgh.pa.us        1456                 :              1 : IdleSessionTimeoutHandler(void)
                               1457                 :                : {
                               1458                 :              1 :     IdleSessionTimeoutPending = true;
                               1459                 :              1 :     InterruptPending = true;
                               1460                 :              1 :     SetLatch(MyLatch);
                               1461                 :              1 : }
                               1462                 :                : 
                               1463                 :                : static void
 1515 andres@anarazel.de       1464                 :             26 : IdleStatsUpdateTimeoutHandler(void)
                               1465                 :                : {
                               1466                 :             26 :     IdleStatsUpdateTimeoutPending = true;
                               1467                 :             26 :     InterruptPending = true;
                               1468                 :             26 :     SetLatch(MyLatch);
                               1469                 :             26 : }
                               1470                 :                : 
                               1471                 :                : static void
 1883 tmunro@postgresql.or     1472                 :UBC           0 : ClientCheckTimeoutHandler(void)
                               1473                 :                : {
                               1474                 :              0 :     CheckClientConnectionPending = true;
                               1475                 :              0 :     InterruptPending = true;
                               1476                 :              0 :     SetLatch(MyLatch);
                               1477                 :              0 : }
                               1478                 :                : 
                               1479                 :                : /*
                               1480                 :                :  * Returns true if at least one role is defined in this database cluster.
                               1481                 :                :  */
                               1482                 :                : static bool
 7641 tgl@sss.pgh.pa.us        1483                 :CBC          76 : ThereIsAtLeastOneRole(void)
                               1484                 :                : {
                               1485                 :                :     Relation    pg_authid_rel;
                               1486                 :                :     TableScanDesc scan;
                               1487                 :                :     bool        result;
                               1488                 :                : 
 2686 andres@anarazel.de       1489                 :             76 :     pg_authid_rel = table_open(AuthIdRelationId, AccessShareLock);
                               1490                 :                : 
 2637                          1491                 :             76 :     scan = table_beginscan_catalog(pg_authid_rel, 0, NULL);
 8776 tgl@sss.pgh.pa.us        1492                 :             76 :     result = (heap_getnext(scan, ForwardScanDirection) != NULL);
                               1493                 :                : 
 2637 andres@anarazel.de       1494                 :             76 :     table_endscan(scan);
 2686                          1495                 :             76 :     table_close(pg_authid_rel, AccessShareLock);
                               1496                 :                : 
 9030 peter_e@gmx.net          1497                 :             76 :     return result;
                               1498                 :                : }
                               1499                 :                : 
                               1500                 :                : /*
                               1501                 :                :  * Stores a warning message to be sent later via EmitConnectionWarnings().
                               1502                 :                :  * Both msg and detail must be non-NULL.
                               1503                 :                :  *
                               1504                 :                :  * NB: Caller should ensure the strings are allocated in a long-lived context
                               1505                 :                :  * like TopMemoryContext.
                               1506                 :                :  */
                               1507                 :                : void
  108 nathan@postgresql.or     1508                 :GNC           2 : StoreConnectionWarning(char *msg, char *detail)
                               1509                 :                : {
                               1510                 :                :     MemoryContext oldcontext;
                               1511                 :                : 
                               1512         [ -  + ]:              2 :     Assert(msg);
                               1513         [ -  + ]:              2 :     Assert(detail);
                               1514                 :                : 
                               1515         [ -  + ]:              2 :     if (ConnectionWarningsEmitted)
  108 nathan@postgresql.or     1516         [ #  # ]:UNC           0 :         elog(ERROR, "StoreConnectionWarning() called after EmitConnectionWarnings()");
                               1517                 :                : 
  108 nathan@postgresql.or     1518                 :GNC           2 :     oldcontext = MemoryContextSwitchTo(TopMemoryContext);
                               1519                 :                : 
                               1520                 :              2 :     ConnectionWarningMessages = lappend(ConnectionWarningMessages, msg);
                               1521                 :              2 :     ConnectionWarningDetails = lappend(ConnectionWarningDetails, detail);
                               1522                 :                : 
                               1523                 :              2 :     MemoryContextSwitchTo(oldcontext);
                               1524                 :              2 : }
                               1525                 :                : 
                               1526                 :                : /*
                               1527                 :                :  * Sends the warning messages saved via StoreConnectionWarning() and frees the
                               1528                 :                :  * strings and lists.
                               1529                 :                :  *
                               1530                 :                :  * NB: This can only be called once per backend.
                               1531                 :                :  */
                               1532                 :                : static void
                               1533                 :          17548 : EmitConnectionWarnings(void)
                               1534                 :                : {
                               1535                 :                :     ListCell   *lc_msg;
                               1536                 :                :     ListCell   *lc_detail;
                               1537                 :                : 
                               1538         [ -  + ]:          17548 :     if (ConnectionWarningsEmitted)
  108 nathan@postgresql.or     1539         [ #  # ]:UNC           0 :         elog(ERROR, "EmitConnectionWarnings() called more than once");
                               1540                 :                :     else
  108 nathan@postgresql.or     1541                 :GNC       17548 :         ConnectionWarningsEmitted = true;
                               1542                 :                : 
                               1543                 :          17550 :     forboth(lc_msg, ConnectionWarningMessages,
                                      [ +  +  +  +  
                                     +  +  +  +  +  
                                        +  +  -  +  
                                                 + ]
                               1544                 :                :             lc_detail, ConnectionWarningDetails)
                               1545                 :                :     {
                               1546         [ +  - ]:              2 :         ereport(WARNING,
                               1547                 :                :                 (errmsg("%s", (char *) lfirst(lc_msg)),
                               1548                 :                :                  errdetail("%s", (char *) lfirst(lc_detail))));
                               1549                 :                :     }
                               1550                 :                : 
                               1551                 :          17548 :     list_free_deep(ConnectionWarningMessages);
                               1552                 :          17548 :     list_free_deep(ConnectionWarningDetails);
                               1553                 :          17548 : }
        

Generated by: LCOV version 2.5.0-beta