LCOV - differential code coverage report
Current view: top level - src/backend/utils/init - postinit.c (source / functions) Coverage Total Hit UNC LBC UBC GBC GNC CBC DCB
Current: f76c13edadc2b319036e0d238703ed56bb23f934 vs 9e17d25e79d4756be08b4a5521b4b58450217137 Lines: 88.2 % 406 358 5 43 2 4 352 1
Current Date: 2026-09-20 14:13:17 +0900 Functions: 90.9 % 22 20 1 1 1 19
Baseline: lcov-20260920-baseline Branches: 63.4 % 298 189 1 108 5 7 177
Baseline Date: 2026-09-20 14:13:13 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 50.0 % 2 1 1 1
(30,360] days: 94.1 % 34 32 2 4 28
(360..) days: 87.8 % 370 325 5 40 2 323
Function coverage date bins:
(30,360] days: 100.0 % 2 2 2
(360..) days: 90.0 % 20 18 1 1 1 17
Branch coverage date bins:
(7,30] days: 25.0 % 4 1 3 1
(30,360] days: 68.8 % 32 22 1 9 7 15
(360..) days: 63.4 % 262 166 96 5 161

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

Generated by: LCOV version 2.0-1