LCOV - differential code coverage report
Current view: top level - src/backend/utils/init - postinit.c (source / functions) Coverage Total Hit UBC GNC CBC DUB DCB
Current: c70b6db34ffeab48beef1fb4ce61bcad3772b8dd vs 06473f5a344df8c9594ead90a609b86f6724cff8 Lines: 87.7 % 374 328 46 328 1 1
Current Date: 2025-09-06 07:49:51 +0900 Functions: 80.0 % 20 16 4 1 15
Baseline: lcov-20250906-005545-baseline Branches: 66.0 % 268 177 91 177
Baseline Date: 2025-09-05 08:21:35 +0100 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(30,360] days: 96.4 % 28 27 1 27
(360..) days: 87.0 % 346 301 45 301
Function coverage date bins:
(30,360] days: 100.0 % 1 1 1
(360..) days: 78.9 % 19 15 4 1 14
Branch coverage date bins:
(30,360] days: 71.9 % 32 23 9 23
(360..) days: 65.3 % 236 154 82 154

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

Generated by: LCOV version 2.4-beta