LCOV - differential code coverage report
Current view: top level - src/backend/utils/init - postinit.c (source / functions) Coverage Total Hit UBC GBC GNC CBC DUB DCB
Current: Differential Code Coverage 16@8cea358b128 vs 17@8cea358b128 Lines: 89.4 % 395 353 42 13 32 308 1 17
Current Date: 2024-04-14 14:21:10 Functions: 95.7 % 23 22 1 2 3 17
Baseline: 16@8cea358b128 Branches: 64.2 % 268 172 96 8 22 142
Baseline Date: 2024-04-14 14:21:09 Line coverage date bins:
Legend: Lines: hit not hit | Branches: + taken - not taken # not executed [..60] days: 100.0 % 25 25 25
(180,240] days: 88.9 % 27 24 3 7 17
(240..) days: 88.6 % 343 304 39 13 291
Function coverage date bins:
[..60] days: 100.0 % 1 1 1
(240..) days: 95.5 % 22 21 1 2 2 17
Branch coverage date bins:
[..60] days: 100.0 % 20 20 20
(180,240] days: 61.5 % 26 16 10 2 14
(240..) days: 61.3 % 222 136 86 8 128

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

Generated by: LCOV version 2.1-beta2-3-g6141622