LCOV - code coverage report
Current view: top level - src/backend/utils/init - postinit.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 91.6 % 381 349
Test Date: 2026-07-16 09:15:41 Functions: 95.5 % 22 21
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 66.8 % 256 171

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

Generated by: LCOV version 2.0-1