LCOV - code coverage report
Current view: top level - src/backend/backup - basebackup.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 83.8 % 690 578
Test Date: 2026-11-29 03:16:06 Functions: 93.8 % 16 15
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 60.3 % 622 375

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  *
       3                 :             :  * basebackup.c
       4                 :             :  *    code for taking a base backup and streaming it to a standby
       5                 :             :  *
       6                 :             :  * Portions Copyright (c) 2010-2026, PostgreSQL Global Development Group
       7                 :             :  *
       8                 :             :  * IDENTIFICATION
       9                 :             :  *    src/backend/backup/basebackup.c
      10                 :             :  *
      11                 :             :  *-------------------------------------------------------------------------
      12                 :             :  */
      13                 :             : #include "postgres.h"
      14                 :             : 
      15                 :             : #include <sys/stat.h>
      16                 :             : #include <unistd.h>
      17                 :             : #include <time.h>
      18                 :             : 
      19                 :             : #include "access/xlog_internal.h"
      20                 :             : #include "access/xlogbackup.h"
      21                 :             : #include "backup/backup_manifest.h"
      22                 :             : #include "backup/basebackup.h"
      23                 :             : #include "backup/basebackup_incremental.h"
      24                 :             : #include "backup/basebackup_sink.h"
      25                 :             : #include "backup/basebackup_target.h"
      26                 :             : #include "catalog/pg_control.h"
      27                 :             : #include "catalog/pg_tablespace_d.h"
      28                 :             : #include "commands/defrem.h"
      29                 :             : #include "common/compression.h"
      30                 :             : #include "common/controldata_utils.h"
      31                 :             : #include "common/file_perm.h"
      32                 :             : #include "common/file_utils.h"
      33                 :             : #include "lib/stringinfo.h"
      34                 :             : #include "miscadmin.h"
      35                 :             : #include "nodes/pg_list.h"
      36                 :             : #include "pgstat.h"
      37                 :             : #include "pgtar.h"
      38                 :             : #include "postmaster/syslogger.h"
      39                 :             : #include "postmaster/walsummarizer.h"
      40                 :             : #include "replication/slot.h"
      41                 :             : #include "replication/walsender.h"
      42                 :             : #include "replication/walsender_private.h"
      43                 :             : #include "storage/bufpage.h"
      44                 :             : #include "storage/checksum.h"
      45                 :             : #include "storage/dsm_impl.h"
      46                 :             : #include "storage/ipc.h"
      47                 :             : #include "storage/lwlock.h"
      48                 :             : #include "storage/reinit.h"
      49                 :             : #include "utils/builtins.h"
      50                 :             : #include "utils/guc.h"
      51                 :             : #include "utils/injection_point.h"
      52                 :             : #include "utils/ps_status.h"
      53                 :             : #include "utils/relcache.h"
      54                 :             : #include "utils/resowner.h"
      55                 :             : #include "utils/wait_event.h"
      56                 :             : 
      57                 :             : /*
      58                 :             :  * How much data do we want to send in one CopyData message? Note that
      59                 :             :  * this may also result in reading the underlying files in chunks of this
      60                 :             :  * size.
      61                 :             :  *
      62                 :             :  * NB: The buffer size is required to be a multiple of the system block
      63                 :             :  * size, so use that value instead if it's bigger than our preference.
      64                 :             :  */
      65                 :             : #define SINK_BUFFER_LENGTH          Max(32768, BLCKSZ)
      66                 :             : 
      67                 :             : typedef struct
      68                 :             : {
      69                 :             :     const char *label;
      70                 :             :     bool        progress;
      71                 :             :     bool        fastcheckpoint;
      72                 :             :     bool        nowait;
      73                 :             :     bool        includewal;
      74                 :             :     bool        incremental;
      75                 :             :     uint32      maxrate;
      76                 :             :     bool        sendtblspcmapfile;
      77                 :             :     bool        send_to_client;
      78                 :             :     bool        use_copytblspc;
      79                 :             :     BaseBackupTargetHandle *target_handle;
      80                 :             :     backup_manifest_option manifest;
      81                 :             :     pg_compress_algorithm compression;
      82                 :             :     pg_compress_specification compression_specification;
      83                 :             :     pg_checksum_type manifest_checksum_type;
      84                 :             : } basebackup_options;
      85                 :             : 
      86                 :             : #define TAR_NUM_TERMINATION_BLOCKS 2
      87                 :             : 
      88                 :             : StaticAssertDecl(TAR_NUM_TERMINATION_BLOCKS * TAR_BLOCK_SIZE <= BLCKSZ,
      89                 :             :                  "BLCKSZ too small for " CppAsString2(TAR_NUM_TERMINATION_BLOCKS) " tar termination blocks");
      90                 :             : 
      91                 :             : static int64 sendTablespace(bbsink *sink, char *path, Oid spcoid, bool sizeonly,
      92                 :             :                             struct backup_manifest_info *manifest,
      93                 :             :                             IncrementalBackupInfo *ib);
      94                 :             : static int64 sendDir(bbsink *sink, const char *path, int basepathlen, bool sizeonly,
      95                 :             :                      List *tablespaces, bool sendtblspclinks,
      96                 :             :                      backup_manifest_info *manifest, Oid spcoid,
      97                 :             :                      IncrementalBackupInfo *ib);
      98                 :             : static bool sendFile(bbsink *sink, const char *readfilename, const char *tarfilename,
      99                 :             :                      const struct stat *statbuf, bool missing_ok,
     100                 :             :                      Oid dboid, Oid spcoid, RelFileNumber relfilenumber,
     101                 :             :                      unsigned segno,
     102                 :             :                      backup_manifest_info *manifest,
     103                 :             :                      unsigned num_incremental_blocks,
     104                 :             :                      BlockNumber *incremental_blocks,
     105                 :             :                      unsigned truncation_block_length);
     106                 :             : static off_t read_file_data_into_buffer(bbsink *sink,
     107                 :             :                                         const char *readfilename, int fd,
     108                 :             :                                         off_t offset, size_t length,
     109                 :             :                                         BlockNumber blkno,
     110                 :             :                                         bool verify_checksum,
     111                 :             :                                         int *checksum_failures);
     112                 :             : static void push_to_sink(bbsink *sink, pg_checksum_context *checksum_ctx,
     113                 :             :                          size_t *bytes_done, void *data, size_t length);
     114                 :             : static bool backup_checksums_verifiable(XLogRecPtr start_lsn);
     115                 :             : static bool verify_page_checksum(Page page, XLogRecPtr start_lsn,
     116                 :             :                                  BlockNumber blkno,
     117                 :             :                                  uint16 *expected_checksum);
     118                 :             : static void sendFileWithContent(bbsink *sink, const char *filename,
     119                 :             :                                 const char *content, int len,
     120                 :             :                                 backup_manifest_info *manifest);
     121                 :             : static int64 _tarWriteHeader(bbsink *sink, const char *filename,
     122                 :             :                              const char *linktarget, struct stat *statbuf,
     123                 :             :                              bool sizeonly);
     124                 :             : static void _tarWritePadding(bbsink *sink, int len);
     125                 :             : static void convert_link_to_directory(const char *pathbuf, struct stat *statbuf);
     126                 :             : static void perform_base_backup(basebackup_options *opt, bbsink *sink,
     127                 :             :                                 IncrementalBackupInfo *ib);
     128                 :             : static void parse_basebackup_options(List *options, basebackup_options *opt);
     129                 :             : static int  compareWalFileNames(const ListCell *a, const ListCell *b);
     130                 :             : static ssize_t basebackup_read_file(int fd, char *buf, size_t nbytes, off_t offset,
     131                 :             :                                     const char *filename, bool partial_read_ok);
     132                 :             : 
     133                 :             : /* Was the backup currently in-progress initiated in recovery mode? */
     134                 :             : static bool backup_started_in_recovery = false;
     135                 :             : 
     136                 :             : /* Total number of checksum failures during base backup. */
     137                 :             : static long long int total_checksum_failures;
     138                 :             : 
     139                 :             : /* Do not verify checksums. */
     140                 :             : static bool noverify_checksums = false;
     141                 :             : 
     142                 :             : /*
     143                 :             :  * Definition of one element part of an exclusion list, used for paths part
     144                 :             :  * of checksum validation or base backups.  "name" is the name of the file
     145                 :             :  * or path to check for exclusion.  If "match_prefix" is true, any items
     146                 :             :  * matching the name as prefix are excluded.
     147                 :             :  */
     148                 :             : struct exclude_list_item
     149                 :             : {
     150                 :             :     const char *name;
     151                 :             :     bool        match_prefix;
     152                 :             : };
     153                 :             : 
     154                 :             : /*
     155                 :             :  * The contents of these directories are removed or recreated during server
     156                 :             :  * start so they are not included in backups.  The directories themselves are
     157                 :             :  * kept and included as empty to preserve access permissions.
     158                 :             :  *
     159                 :             :  * Note: this list should be kept in sync with the filter lists in pg_rewind's
     160                 :             :  * filemap.c.
     161                 :             :  */
     162                 :             : static const char *const excludeDirContents[] =
     163                 :             : {
     164                 :             :     /*
     165                 :             :      * Skip temporary statistics files. PG_STAT_TMP_DIR must be skipped
     166                 :             :      * because extensions like pg_stat_statements store data there.
     167                 :             :      */
     168                 :             :     PG_STAT_TMP_DIR,
     169                 :             : 
     170                 :             :     /*
     171                 :             :      * It is generally not useful to backup the contents of this directory
     172                 :             :      * even if the intention is to restore to another primary. See backup.sgml
     173                 :             :      * for a more detailed description.
     174                 :             :      */
     175                 :             :     PG_REPLSLOT_DIR,
     176                 :             : 
     177                 :             :     /* Contents removed on startup, see dsm_cleanup_for_mmap(). */
     178                 :             :     PG_DYNSHMEM_DIR,
     179                 :             : 
     180                 :             :     /* Contents removed on startup, see AsyncShmemInit(). */
     181                 :             :     "pg_notify",
     182                 :             : 
     183                 :             :     /*
     184                 :             :      * Old contents are loaded for possible debugging but are not required for
     185                 :             :      * normal operation, see SerialInit().
     186                 :             :      */
     187                 :             :     "pg_serial",
     188                 :             : 
     189                 :             :     /* Contents removed on startup, see DeleteAllExportedSnapshotFiles(). */
     190                 :             :     "pg_snapshots",
     191                 :             : 
     192                 :             :     /* Contents zeroed on startup, see StartupSUBTRANS(). */
     193                 :             :     "pg_subtrans",
     194                 :             : 
     195                 :             :     /* end of list */
     196                 :             :     NULL
     197                 :             : };
     198                 :             : 
     199                 :             : /*
     200                 :             :  * List of files excluded from backups.
     201                 :             :  */
     202                 :             : static const struct exclude_list_item excludeFiles[] =
     203                 :             : {
     204                 :             :     /* Skip auto conf temporary file. */
     205                 :             :     {PG_AUTOCONF_FILENAME ".tmp", false},
     206                 :             : 
     207                 :             :     /* Skip current log file temporary file */
     208                 :             :     {LOG_METAINFO_DATAFILE_TMP, false},
     209                 :             : 
     210                 :             :     /*
     211                 :             :      * Skip relation cache because it is rebuilt on startup.  This includes
     212                 :             :      * temporary files.
     213                 :             :      */
     214                 :             :     {RELCACHE_INIT_FILENAME, true},
     215                 :             : 
     216                 :             :     /*
     217                 :             :      * backup_label and tablespace_map should not exist in a running cluster
     218                 :             :      * capable of doing an online backup, but exclude them just in case.
     219                 :             :      */
     220                 :             :     {BACKUP_LABEL_FILE, false},
     221                 :             :     {TABLESPACE_MAP, false},
     222                 :             : 
     223                 :             :     /*
     224                 :             :      * If there's a backup_manifest, it belongs to a backup that was used to
     225                 :             :      * start this server. It is *not* correct for this backup. Our
     226                 :             :      * backup_manifest is injected into the backup separately if users want
     227                 :             :      * it.
     228                 :             :      */
     229                 :             :     {"backup_manifest", false},
     230                 :             : 
     231                 :             :     {"postmaster.pid", false},
     232                 :             :     {"postmaster.opts", false},
     233                 :             : 
     234                 :             :     /* end of list */
     235                 :             :     {NULL, false}
     236                 :             : };
     237                 :             : 
     238                 :             : /*
     239                 :             :  * Actually do a base backup for the specified tablespaces.
     240                 :             :  *
     241                 :             :  * This is split out mainly to avoid complaints about "variable might be
     242                 :             :  * clobbered by longjmp" from stupider versions of gcc.
     243                 :             :  */
     244                 :             : static void
     245                 :         202 : perform_base_backup(basebackup_options *opt, bbsink *sink,
     246                 :             :                     IncrementalBackupInfo *ib)
     247                 :             : {
     248                 :             :     bbsink_state state;
     249                 :             :     XLogRecPtr  endptr;
     250                 :             :     TimeLineID  endtli;
     251                 :             :     backup_manifest_info manifest;
     252                 :             :     BackupState *backup_state;
     253                 :             :     StringInfoData tablespace_map;
     254                 :             : 
     255                 :             :     /* Initial backup state, insofar as we know it now. */
     256                 :         202 :     state.tablespaces = NIL;
     257                 :         202 :     state.tablespace_num = 0;
     258                 :         202 :     state.bytes_done = 0;
     259                 :         202 :     state.bytes_total = 0;
     260                 :         202 :     state.bytes_total_is_valid = false;
     261                 :             : 
     262                 :             :     /* we're going to use a BufFile, so we need a ResourceOwner */
     263                 :             :     Assert(AuxProcessResourceOwner != NULL);
     264                 :             :     Assert(CurrentResourceOwner == AuxProcessResourceOwner ||
     265                 :             :            CurrentResourceOwner == NULL);
     266                 :         202 :     CurrentResourceOwner = AuxProcessResourceOwner;
     267                 :             : 
     268                 :         202 :     backup_started_in_recovery = RecoveryInProgress();
     269                 :             : 
     270                 :         202 :     InitializeBackupManifest(&manifest, opt->manifest,
     271                 :             :                              opt->manifest_checksum_type);
     272                 :             : 
     273                 :         202 :     total_checksum_failures = 0;
     274                 :             : 
     275                 :             :     /* Allocate backup related variables. */
     276                 :         202 :     backup_state = palloc0_object(BackupState);
     277                 :         202 :     initStringInfo(&tablespace_map);
     278                 :             : 
     279                 :         202 :     basebackup_progress_wait_checkpoint();
     280                 :         202 :     do_pg_backup_start(opt->label, opt->fastcheckpoint, &state.tablespaces,
     281                 :             :                        backup_state, &tablespace_map);
     282                 :             : 
     283                 :         202 :     state.startptr = backup_state->startpoint;
     284                 :         202 :     state.starttli = backup_state->starttli;
     285                 :             : 
     286                 :             :     /*
     287                 :             :      * Once do_pg_backup_start has been called, ensure that any failure causes
     288                 :             :      * us to abort the backup so we don't "leak" a backup counter. For this
     289                 :             :      * reason, *all* functionality between do_pg_backup_start() and the end of
     290                 :             :      * do_pg_backup_stop() should be inside the error cleanup block!
     291                 :             :      */
     292                 :             : 
     293         [ +  + ]:         202 :     PG_ENSURE_ERROR_CLEANUP(do_pg_abort_backup, BoolGetDatum(false));
     294                 :             :     {
     295                 :             :         ListCell   *lc;
     296                 :             :         tablespaceinfo *newti;
     297                 :             : 
     298                 :             :         /* If this is an incremental backup, execute preparatory steps. */
     299         [ +  + ]:         202 :         if (ib != NULL)
     300                 :          16 :             PrepareForIncrementalBackup(ib, backup_state);
     301                 :             : 
     302                 :             :         /* Add a node for the base directory at the end */
     303                 :         200 :         newti = palloc0_object(tablespaceinfo);
     304                 :         200 :         newti->size = -1;
     305                 :         200 :         state.tablespaces = lappend(state.tablespaces, newti);
     306                 :             : 
     307                 :             :         /*
     308                 :             :          * Calculate the total backup size by summing up the size of each
     309                 :             :          * tablespace
     310                 :             :          */
     311         [ +  + ]:         200 :         if (opt->progress)
     312                 :             :         {
     313                 :         199 :             basebackup_progress_estimate_backup_size();
     314                 :             : 
     315   [ +  -  +  +  :         436 :             foreach(lc, state.tablespaces)
                   +  + ]
     316                 :             :             {
     317                 :         237 :                 tablespaceinfo *tmp = (tablespaceinfo *) lfirst(lc);
     318                 :             : 
     319         [ +  + ]:         237 :                 if (tmp->path == NULL)
     320                 :         199 :                     tmp->size = sendDir(sink, ".", 1, true, state.tablespaces,
     321                 :             :                                         true, NULL, InvalidOid, ib);
     322                 :             :                 else
     323                 :          38 :                     tmp->size = sendTablespace(sink, tmp->path, tmp->oid, true,
     324                 :             :                                                NULL, ib);
     325                 :         237 :                 state.bytes_total += tmp->size;
     326                 :             :             }
     327                 :         199 :             state.bytes_total_is_valid = true;
     328                 :             :         }
     329                 :             : 
     330                 :             :         /* notify basebackup sink about start of backup */
     331                 :         200 :         bbsink_begin_backup(sink, &state, SINK_BUFFER_LENGTH);
     332                 :             : 
     333                 :             :         /*
     334                 :             :          * Allow tests to hold the backup after the starting checkpoint but
     335                 :             :          * before any file data is sent.
     336                 :             :          */
     337                 :         200 :         INJECTION_POINT("basebackup-before-send-files", NULL);
     338                 :             : 
     339                 :             :         /* Send off our tablespaces one by one */
     340   [ +  -  +  +  :         432 :         foreach(lc, state.tablespaces)
                   +  + ]
     341                 :             :         {
     342                 :         238 :             tablespaceinfo *ti = (tablespaceinfo *) lfirst(lc);
     343                 :             : 
     344         [ +  + ]:         238 :             if (ti->path == NULL)
     345                 :             :             {
     346                 :         200 :                 bool        sendtblspclinks = true;
     347                 :             :                 char       *backup_label;
     348                 :             :                 ControlFileData *controlData;
     349                 :             :                 bool        crc_ok;
     350                 :             :                 char       *controlFile;
     351                 :             : 
     352                 :         200 :                 bbsink_begin_archive(sink, "base.tar");
     353                 :             : 
     354                 :             :                 /* In the main tar, include the backup_label first... */
     355                 :         200 :                 backup_label = build_backup_content(backup_state, false);
     356                 :         200 :                 sendFileWithContent(sink, BACKUP_LABEL_FILE,
     357                 :             :                                     backup_label, -1, &manifest);
     358                 :         200 :                 pfree(backup_label);
     359                 :             : 
     360                 :             :                 /* Then the tablespace_map file, if required... */
     361         [ +  + ]:         200 :                 if (opt->sendtblspcmapfile)
     362                 :             :                 {
     363                 :          30 :                     sendFileWithContent(sink, TABLESPACE_MAP,
     364                 :          30 :                                         tablespace_map.data, -1, &manifest);
     365                 :          30 :                     sendtblspclinks = false;
     366                 :             :                 }
     367                 :             : 
     368                 :             :                 /* Then the bulk of the files... */
     369                 :         200 :                 sendDir(sink, ".", 1, false, state.tablespaces,
     370                 :             :                         sendtblspclinks, &manifest, InvalidOid, ib);
     371                 :             : 
     372                 :             :                 /* ... and pg_control after everything else. */
     373                 :         194 :                 LWLockAcquire(ControlFileLock, LW_SHARED);
     374                 :         194 :                 controlData = get_controlfile(DataDir, &crc_ok);
     375                 :         194 :                 LWLockRelease(ControlFileLock);
     376                 :             : 
     377         [ -  + ]:         194 :                 if (!crc_ok)
     378         [ #  # ]:           0 :                     ereport(ERROR,
     379                 :             :                             (errcode(ERRCODE_DATA_CORRUPTED),
     380                 :             :                              errmsg("calculated CRC checksum does not match value stored in file")));
     381                 :             : 
     382                 :             :                 /* Send the full file, zero-padded as it is on disk */
     383                 :         194 :                 controlFile = palloc0(PG_CONTROL_FILE_SIZE);
     384                 :         194 :                 memcpy(controlFile, controlData, sizeof(ControlFileData));
     385                 :         194 :                 pfree(controlData);
     386                 :             : 
     387                 :         194 :                 sendFileWithContent(sink, XLOG_CONTROL_FILE,
     388                 :             :                                     controlFile, PG_CONTROL_FILE_SIZE,
     389                 :             :                                     &manifest);
     390                 :         194 :                 pfree(controlFile);
     391                 :             :             }
     392                 :             :             else
     393                 :             :             {
     394                 :          38 :                 char       *archive_name = psprintf("%u.tar", ti->oid);
     395                 :             : 
     396                 :          38 :                 bbsink_begin_archive(sink, archive_name);
     397                 :             : 
     398                 :          38 :                 sendTablespace(sink, ti->path, ti->oid, false, &manifest, ib);
     399                 :             :             }
     400                 :             : 
     401                 :             :             /*
     402                 :             :              * If we're including WAL, and this is the main data directory we
     403                 :             :              * don't treat this as the end of the tablespace. Instead, we will
     404                 :             :              * include the xlog files below and stop afterwards. This is safe
     405                 :             :              * since the main data directory is always sent *last*.
     406                 :             :              */
     407   [ +  +  +  + ]:         232 :             if (opt->includewal && ti->path == NULL)
     408                 :             :             {
     409                 :             :                 Assert(lnext(state.tablespaces, lc) == NULL);
     410                 :             :             }
     411                 :             :             else
     412                 :             :             {
     413                 :             :                 /* Properly terminate the tarfile. */
     414                 :         217 :                 memset(sink->bbs_buffer, 0, TAR_NUM_TERMINATION_BLOCKS * TAR_BLOCK_SIZE);
     415                 :         217 :                 bbsink_archive_contents(sink, TAR_NUM_TERMINATION_BLOCKS * TAR_BLOCK_SIZE);
     416                 :             : 
     417                 :             :                 /* OK, that's the end of the archive. */
     418                 :         217 :                 bbsink_end_archive(sink);
     419                 :             :             }
     420                 :             :         }
     421                 :             : 
     422                 :         194 :         basebackup_progress_wait_wal_archive(&state);
     423                 :         194 :         do_pg_backup_stop(backup_state, !opt->nowait);
     424                 :             : 
     425                 :         194 :         endptr = backup_state->stoppoint;
     426                 :         194 :         endtli = backup_state->stoptli;
     427                 :             : 
     428                 :             :         /* Deallocate backup-related variables. */
     429                 :         194 :         pfree(tablespace_map.data);
     430                 :         194 :         pfree(backup_state);
     431                 :             :     }
     432         [ -  + ]:         198 :     PG_END_ENSURE_ERROR_CLEANUP(do_pg_abort_backup, BoolGetDatum(false));
     433                 :             : 
     434                 :             : 
     435         [ +  + ]:         194 :     if (opt->includewal)
     436                 :             :     {
     437                 :             :         /*
     438                 :             :          * We've left the last tar file "open", so we can now append the
     439                 :             :          * required WAL files to it.
     440                 :             :          */
     441                 :             :         char        pathbuf[MAXPGPATH];
     442                 :             :         XLogSegNo   segno;
     443                 :             :         XLogSegNo   startsegno;
     444                 :             :         XLogSegNo   endsegno;
     445                 :             :         struct stat statbuf;
     446                 :          15 :         List       *historyFileList = NIL;
     447                 :          15 :         List       *walFileList = NIL;
     448                 :             :         char        firstoff[MAXFNAMELEN];
     449                 :             :         char        lastoff[MAXFNAMELEN];
     450                 :             :         DIR        *dir;
     451                 :             :         struct dirent *de;
     452                 :             :         ListCell   *lc;
     453                 :             :         TimeLineID  tli;
     454                 :             : 
     455                 :          15 :         basebackup_progress_transfer_wal();
     456                 :             : 
     457                 :             :         /*
     458                 :             :          * I'd rather not worry about timelines here, so scan pg_wal and
     459                 :             :          * include all WAL files in the range between 'startptr' and 'endptr',
     460                 :             :          * regardless of the timeline the file is stamped with. If there are
     461                 :             :          * some spurious WAL files belonging to timelines that don't belong in
     462                 :             :          * this server's history, they will be included too. Normally there
     463                 :             :          * shouldn't be such files, but if there are, there's little harm in
     464                 :             :          * including them.
     465                 :             :          */
     466                 :          15 :         XLByteToSeg(state.startptr, startsegno, wal_segment_size);
     467                 :          15 :         XLogFileName(firstoff, state.starttli, startsegno, wal_segment_size);
     468                 :          15 :         XLByteToPrevSeg(endptr, endsegno, wal_segment_size);
     469                 :          15 :         XLogFileName(lastoff, endtli, endsegno, wal_segment_size);
     470                 :             : 
     471                 :          15 :         dir = AllocateDir("pg_wal");
     472         [ +  + ]:         108 :         while ((de = ReadDir(dir, "pg_wal")) != NULL)
     473                 :             :         {
     474                 :             :             /* Does it look like a WAL segment, and is it in the range? */
     475         [ +  + ]:          93 :             if (IsXLogFileName(de->d_name) &&
     476         [ +  - ]:          33 :                 strcmp(de->d_name + 8, firstoff + 8) >= 0 &&
     477         [ +  + ]:          33 :                 strcmp(de->d_name + 8, lastoff + 8) <= 0)
     478                 :             :             {
     479                 :          15 :                 walFileList = lappend(walFileList, pstrdup(de->d_name));
     480                 :             :             }
     481                 :             :             /* Does it look like a timeline history file? */
     482         [ -  + ]:          78 :             else if (IsTLHistoryFileName(de->d_name))
     483                 :             :             {
     484                 :           0 :                 historyFileList = lappend(historyFileList, pstrdup(de->d_name));
     485                 :             :             }
     486                 :             :         }
     487                 :          15 :         FreeDir(dir);
     488                 :             : 
     489                 :             :         /*
     490                 :             :          * Before we go any further, check that none of the WAL segments we
     491                 :             :          * need were removed.
     492                 :             :          */
     493                 :          15 :         CheckXLogRemoved(startsegno, state.starttli);
     494                 :             : 
     495                 :             :         /*
     496                 :             :          * Sort the WAL filenames.  We want to send the files in order from
     497                 :             :          * oldest to newest, to reduce the chance that a file is recycled
     498                 :             :          * before we get a chance to send it over.
     499                 :             :          */
     500                 :          15 :         list_sort(walFileList, compareWalFileNames);
     501                 :             : 
     502                 :             :         /*
     503                 :             :          * There must be at least one xlog file in the pg_wal directory, since
     504                 :             :          * we are doing backup-including-xlog.
     505                 :             :          */
     506         [ -  + ]:          15 :         if (walFileList == NIL)
     507         [ #  # ]:           0 :             ereport(ERROR,
     508                 :             :                     (errmsg("could not find any WAL files")));
     509                 :             : 
     510                 :             :         /*
     511                 :             :          * Sanity check: the first and last segment should cover startptr and
     512                 :             :          * endptr, with no gaps in between.
     513                 :             :          */
     514                 :          15 :         XLogFromFileName((char *) linitial(walFileList),
     515                 :             :                          &tli, &segno, wal_segment_size);
     516         [ -  + ]:          15 :         if (segno != startsegno)
     517                 :             :         {
     518                 :             :             char        startfname[MAXFNAMELEN];
     519                 :             : 
     520                 :           0 :             XLogFileName(startfname, state.starttli, startsegno,
     521                 :             :                          wal_segment_size);
     522         [ #  # ]:           0 :             ereport(ERROR,
     523                 :             :                     (errmsg("could not find WAL file \"%s\"", startfname)));
     524                 :             :         }
     525   [ +  -  +  +  :          30 :         foreach(lc, walFileList)
                   +  + ]
     526                 :             :         {
     527                 :          15 :             char       *walFileName = (char *) lfirst(lc);
     528                 :          15 :             XLogSegNo   currsegno = segno;
     529                 :          15 :             XLogSegNo   nextsegno = segno + 1;
     530                 :             : 
     531                 :          15 :             XLogFromFileName(walFileName, &tli, &segno, wal_segment_size);
     532   [ +  -  -  + ]:          15 :             if (!(nextsegno == segno || currsegno == segno))
     533                 :             :             {
     534                 :             :                 char        nextfname[MAXFNAMELEN];
     535                 :             : 
     536                 :           0 :                 XLogFileName(nextfname, tli, nextsegno, wal_segment_size);
     537         [ #  # ]:           0 :                 ereport(ERROR,
     538                 :             :                         (errmsg("could not find WAL file \"%s\"", nextfname)));
     539                 :             :             }
     540                 :             :         }
     541         [ -  + ]:          15 :         if (segno != endsegno)
     542                 :             :         {
     543                 :             :             char        endfname[MAXFNAMELEN];
     544                 :             : 
     545                 :           0 :             XLogFileName(endfname, endtli, endsegno, wal_segment_size);
     546         [ #  # ]:           0 :             ereport(ERROR,
     547                 :             :                     (errmsg("could not find WAL file \"%s\"", endfname)));
     548                 :             :         }
     549                 :             : 
     550                 :             :         /* Ok, we have everything we need. Send the WAL files. */
     551   [ +  -  +  +  :          30 :         foreach(lc, walFileList)
                   +  + ]
     552                 :             :         {
     553                 :          15 :             char       *walFileName = (char *) lfirst(lc);
     554                 :             :             int         fd;
     555                 :             :             ssize_t     cnt;
     556                 :          15 :             pgoff_t     len = 0;
     557                 :             : 
     558                 :          15 :             snprintf(pathbuf, MAXPGPATH, XLOGDIR "/%s", walFileName);
     559                 :          15 :             XLogFromFileName(walFileName, &tli, &segno, wal_segment_size);
     560                 :             : 
     561                 :          15 :             fd = OpenTransientFile(pathbuf, O_RDONLY | PG_BINARY);
     562         [ -  + ]:          15 :             if (fd < 0)
     563                 :             :             {
     564                 :           0 :                 int         save_errno = errno;
     565                 :             : 
     566                 :             :                 /*
     567                 :             :                  * Most likely reason for this is that the file was already
     568                 :             :                  * removed by a checkpoint, so check for that to get a better
     569                 :             :                  * error message.
     570                 :             :                  */
     571                 :           0 :                 CheckXLogRemoved(segno, tli);
     572                 :             : 
     573                 :           0 :                 errno = save_errno;
     574         [ #  # ]:           0 :                 ereport(ERROR,
     575                 :             :                         (errcode_for_file_access(),
     576                 :             :                          errmsg("could not open file \"%s\": %m", pathbuf)));
     577                 :             :             }
     578                 :             : 
     579         [ -  + ]:          15 :             if (fstat(fd, &statbuf) != 0)
     580         [ #  # ]:           0 :                 ereport(ERROR,
     581                 :             :                         (errcode_for_file_access(),
     582                 :             :                          errmsg("could not stat file \"%s\": %m",
     583                 :             :                                 pathbuf)));
     584         [ -  + ]:          15 :             if (statbuf.st_size != wal_segment_size)
     585                 :             :             {
     586                 :           0 :                 CheckXLogRemoved(segno, tli);
     587         [ #  # ]:           0 :                 ereport(ERROR,
     588                 :             :                         (errcode_for_file_access(),
     589                 :             :                          errmsg("unexpected WAL file size \"%s\"", walFileName)));
     590                 :             :             }
     591                 :             : 
     592                 :             :             /* send the WAL file itself */
     593                 :          15 :             _tarWriteHeader(sink, pathbuf, NULL, &statbuf, false);
     594                 :             : 
     595                 :          15 :             while ((cnt = basebackup_read_file(fd, sink->bbs_buffer,
     596                 :        7680 :                                                Min(sink->bbs_buffer_length,
     597                 :             :                                                    wal_segment_size - len),
     598         [ +  - ]:        7680 :                                                len, pathbuf, true)) > 0)
     599                 :             :             {
     600                 :        7680 :                 CheckXLogRemoved(segno, tli);
     601                 :        7680 :                 bbsink_archive_contents(sink, cnt);
     602                 :             : 
     603                 :        7680 :                 len += cnt;
     604                 :             : 
     605         [ +  + ]:        7680 :                 if (len == wal_segment_size)
     606                 :          15 :                     break;
     607                 :             :             }
     608                 :             : 
     609         [ -  + ]:          15 :             if (len != wal_segment_size)
     610                 :             :             {
     611                 :           0 :                 CheckXLogRemoved(segno, tli);
     612         [ #  # ]:           0 :                 ereport(ERROR,
     613                 :             :                         (errcode_for_file_access(),
     614                 :             :                          errmsg("unexpected WAL file size \"%s\"", walFileName)));
     615                 :             :             }
     616                 :             : 
     617                 :             :             /*
     618                 :             :              * wal_segment_size is a multiple of TAR_BLOCK_SIZE, so no need
     619                 :             :              * for padding.
     620                 :             :              */
     621                 :             :             Assert(wal_segment_size % TAR_BLOCK_SIZE == 0);
     622                 :             : 
     623                 :          15 :             CloseTransientFile(fd);
     624                 :             : 
     625                 :             :             /*
     626                 :             :              * Mark file as archived, otherwise files can get archived again
     627                 :             :              * after promotion of a new node. This is in line with
     628                 :             :              * walreceiver.c always doing an XLogArchiveForceDone() after a
     629                 :             :              * complete segment.
     630                 :             :              */
     631                 :          15 :             StatusFilePath(pathbuf, walFileName, ".done");
     632                 :          15 :             sendFileWithContent(sink, pathbuf, "", -1, &manifest);
     633                 :             :         }
     634                 :             : 
     635                 :             :         /*
     636                 :             :          * Send timeline history files too. Only the latest timeline history
     637                 :             :          * file is required for recovery, and even that only if there happens
     638                 :             :          * to be a timeline switch in the first WAL segment that contains the
     639                 :             :          * checkpoint record, or if we're taking a base backup from a standby
     640                 :             :          * server and the target timeline changes while the backup is taken.
     641                 :             :          * But they are small and highly useful for debugging purposes, so
     642                 :             :          * better include them all, always.
     643                 :             :          */
     644   [ -  +  -  -  :          15 :         foreach(lc, historyFileList)
                   -  + ]
     645                 :             :         {
     646                 :           0 :             char       *fname = lfirst(lc);
     647                 :             : 
     648                 :           0 :             snprintf(pathbuf, MAXPGPATH, XLOGDIR "/%s", fname);
     649                 :             : 
     650         [ #  # ]:           0 :             if (lstat(pathbuf, &statbuf) != 0)
     651         [ #  # ]:           0 :                 ereport(ERROR,
     652                 :             :                         (errcode_for_file_access(),
     653                 :             :                          errmsg("could not stat file \"%s\": %m", pathbuf)));
     654                 :             : 
     655                 :           0 :             sendFile(sink, pathbuf, pathbuf, &statbuf, false,
     656                 :             :                      InvalidOid, InvalidOid, InvalidRelFileNumber, 0,
     657                 :             :                      &manifest, 0, NULL, 0);
     658                 :             : 
     659                 :             :             /* unconditionally mark file as archived */
     660                 :           0 :             StatusFilePath(pathbuf, fname, ".done");
     661                 :           0 :             sendFileWithContent(sink, pathbuf, "", -1, &manifest);
     662                 :             :         }
     663                 :             : 
     664                 :             :         /* Properly terminate the tar file. */
     665                 :          15 :         memset(sink->bbs_buffer, 0, TAR_NUM_TERMINATION_BLOCKS * TAR_BLOCK_SIZE);
     666                 :          15 :         bbsink_archive_contents(sink, TAR_NUM_TERMINATION_BLOCKS * TAR_BLOCK_SIZE);
     667                 :             : 
     668                 :             :         /* OK, that's the end of the archive. */
     669                 :          15 :         bbsink_end_archive(sink);
     670                 :             :     }
     671                 :             : 
     672                 :         194 :     AddWALInfoToBackupManifest(&manifest, state.startptr, state.starttli,
     673                 :             :                                endptr, endtli);
     674                 :             : 
     675                 :         194 :     SendBackupManifest(&manifest, sink);
     676                 :             : 
     677                 :         194 :     bbsink_end_backup(sink, endptr, endtli);
     678                 :             : 
     679         [ +  + ]:         194 :     if (total_checksum_failures)
     680                 :             :     {
     681         [ +  - ]:           3 :         ereport(WARNING,
     682                 :             :                 (errmsg_plural("%lld total checksum verification failure",
     683                 :             :                                "%lld total checksum verification failures",
     684                 :             :                                total_checksum_failures,
     685                 :             :                                total_checksum_failures)));
     686                 :             : 
     687         [ +  - ]:           3 :         ereport(ERROR,
     688                 :             :                 (errcode(ERRCODE_DATA_CORRUPTED),
     689                 :             :                  errmsg("checksum verification failure during base backup")));
     690                 :             :     }
     691                 :             : 
     692                 :             :     /*
     693                 :             :      * Make sure to free the manifest before the resource owners as manifests
     694                 :             :      * use cryptohash contexts that may depend on resource owners (like
     695                 :             :      * OpenSSL).
     696                 :             :      */
     697                 :         191 :     FreeBackupManifest(&manifest);
     698                 :             : 
     699                 :             :     /* clean up the resource owner we created */
     700                 :         191 :     ReleaseAuxProcessResources(true);
     701                 :         191 : }
     702                 :             : 
     703                 :             : /*
     704                 :             :  * list_sort comparison function, to compare log/seg portion of WAL segment
     705                 :             :  * filenames, ignoring the timeline portion.
     706                 :             :  */
     707                 :             : static int
     708                 :           0 : compareWalFileNames(const ListCell *a, const ListCell *b)
     709                 :             : {
     710                 :           0 :     char       *fna = (char *) lfirst(a);
     711                 :           0 :     char       *fnb = (char *) lfirst(b);
     712                 :             : 
     713                 :           0 :     return strcmp(fna + 8, fnb + 8);
     714                 :             : }
     715                 :             : 
     716                 :             : /*
     717                 :             :  * Parse the base backup options passed down by the parser
     718                 :             :  */
     719                 :             : static void
     720                 :         219 : parse_basebackup_options(List *options, basebackup_options *opt)
     721                 :             : {
     722                 :             :     ListCell   *lopt;
     723                 :         219 :     bool        o_label = false;
     724                 :         219 :     bool        o_progress = false;
     725                 :         219 :     bool        o_checkpoint = false;
     726                 :         219 :     bool        o_nowait = false;
     727                 :         219 :     bool        o_wal = false;
     728                 :         219 :     bool        o_incremental = false;
     729                 :         219 :     bool        o_maxrate = false;
     730                 :         219 :     bool        o_tablespace_map = false;
     731                 :         219 :     bool        o_noverify_checksums = false;
     732                 :         219 :     bool        o_manifest = false;
     733                 :         219 :     bool        o_manifest_checksums = false;
     734                 :         219 :     bool        o_target = false;
     735                 :         219 :     bool        o_target_detail = false;
     736                 :         219 :     char       *target_str = NULL;
     737                 :         219 :     char       *target_detail_str = NULL;
     738                 :         219 :     bool        o_compression = false;
     739                 :         219 :     bool        o_compression_detail = false;
     740                 :         219 :     char       *compression_detail_str = NULL;
     741                 :             : 
     742   [ +  -  +  -  :        2409 :     MemSet(opt, 0, sizeof(*opt));
          +  -  +  -  +  
                      + ]
     743                 :         219 :     opt->manifest = MANIFEST_OPTION_NO;
     744                 :         219 :     opt->manifest_checksum_type = CHECKSUM_TYPE_CRC32C;
     745                 :         219 :     opt->compression = PG_COMPRESSION_NONE;
     746                 :         219 :     opt->compression_specification.algorithm = PG_COMPRESSION_NONE;
     747                 :             : 
     748   [ +  -  +  +  :        1636 :     foreach(lopt, options)
                   +  + ]
     749                 :             :     {
     750                 :        1420 :         DefElem    *defel = (DefElem *) lfirst(lopt);
     751                 :             : 
     752         [ +  + ]:        1420 :         if (strcmp(defel->defname, "label") == 0)
     753                 :             :         {
     754         [ -  + ]:         218 :             if (o_label)
     755         [ #  # ]:           0 :                 ereport(ERROR,
     756                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     757                 :             :                          errmsg("duplicate option \"%s\"", defel->defname)));
     758                 :         218 :             opt->label = defGetString(defel);
     759                 :         218 :             o_label = true;
     760                 :             :         }
     761         [ +  + ]:        1202 :         else if (strcmp(defel->defname, "progress") == 0)
     762                 :             :         {
     763         [ -  + ]:         218 :             if (o_progress)
     764         [ #  # ]:           0 :                 ereport(ERROR,
     765                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     766                 :             :                          errmsg("duplicate option \"%s\"", defel->defname)));
     767                 :         218 :             opt->progress = defGetBoolean(defel);
     768                 :         218 :             o_progress = true;
     769                 :             :         }
     770         [ +  + ]:         984 :         else if (strcmp(defel->defname, "checkpoint") == 0)
     771                 :             :         {
     772                 :         209 :             char       *optval = defGetString(defel);
     773                 :             : 
     774         [ -  + ]:         209 :             if (o_checkpoint)
     775         [ #  # ]:           0 :                 ereport(ERROR,
     776                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     777                 :             :                          errmsg("duplicate option \"%s\"", defel->defname)));
     778         [ +  - ]:         209 :             if (pg_strcasecmp(optval, "fast") == 0)
     779                 :         209 :                 opt->fastcheckpoint = true;
     780         [ #  # ]:           0 :             else if (pg_strcasecmp(optval, "spread") == 0)
     781                 :           0 :                 opt->fastcheckpoint = false;
     782                 :             :             else
     783         [ #  # ]:           0 :                 ereport(ERROR,
     784                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     785                 :             :                          errmsg("unrecognized checkpoint type: \"%s\"",
     786                 :             :                                 optval)));
     787                 :         209 :             o_checkpoint = true;
     788                 :             :         }
     789         [ +  + ]:         775 :         else if (strcmp(defel->defname, "wait") == 0)
     790                 :             :         {
     791         [ -  + ]:         208 :             if (o_nowait)
     792         [ #  # ]:           0 :                 ereport(ERROR,
     793                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     794                 :             :                          errmsg("duplicate option \"%s\"", defel->defname)));
     795                 :         208 :             opt->nowait = !defGetBoolean(defel);
     796                 :         208 :             o_nowait = true;
     797                 :             :         }
     798         [ +  + ]:         567 :         else if (strcmp(defel->defname, "wal") == 0)
     799                 :             :         {
     800         [ -  + ]:          19 :             if (o_wal)
     801         [ #  # ]:           0 :                 ereport(ERROR,
     802                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     803                 :             :                          errmsg("duplicate option \"%s\"", defel->defname)));
     804                 :          19 :             opt->includewal = defGetBoolean(defel);
     805                 :          19 :             o_wal = true;
     806                 :             :         }
     807         [ +  + ]:         548 :         else if (strcmp(defel->defname, "incremental") == 0)
     808                 :             :         {
     809         [ -  + ]:          16 :             if (o_incremental)
     810         [ #  # ]:           0 :                 ereport(ERROR,
     811                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     812                 :             :                          errmsg("duplicate option \"%s\"", defel->defname)));
     813                 :          16 :             opt->incremental = defGetBoolean(defel);
     814   [ +  -  -  + ]:          16 :             if (opt->incremental && !summarize_wal)
     815         [ #  # ]:           0 :                 ereport(ERROR,
     816                 :             :                         (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     817                 :             :                          errmsg("incremental backups cannot be taken unless WAL summarization is enabled")));
     818                 :          16 :             o_incremental = true;
     819                 :             :         }
     820         [ +  + ]:         532 :         else if (strcmp(defel->defname, "max_rate") == 0)
     821                 :             :         {
     822                 :             :             int64       maxrate;
     823                 :             : 
     824         [ -  + ]:           2 :             if (o_maxrate)
     825         [ #  # ]:           0 :                 ereport(ERROR,
     826                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     827                 :             :                          errmsg("duplicate option \"%s\"", defel->defname)));
     828                 :             : 
     829                 :           2 :             maxrate = defGetInt64(defel);
     830   [ +  -  -  + ]:           2 :             if (maxrate < MAX_RATE_LOWER || maxrate > MAX_RATE_UPPER)
     831         [ #  # ]:           0 :                 ereport(ERROR,
     832                 :             :                         (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
     833                 :             :                          errmsg("%" PRId64 " is outside the valid range for parameter \"%s\" (%d .. %d)",
     834                 :             :                                 maxrate, "MAX_RATE", MAX_RATE_LOWER, MAX_RATE_UPPER)));
     835                 :             : 
     836                 :           2 :             opt->maxrate = (uint32) maxrate;
     837                 :           2 :             o_maxrate = true;
     838                 :             :         }
     839         [ +  + ]:         530 :         else if (strcmp(defel->defname, "tablespace_map") == 0)
     840                 :             :         {
     841         [ -  + ]:          36 :             if (o_tablespace_map)
     842         [ #  # ]:           0 :                 ereport(ERROR,
     843                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     844                 :             :                          errmsg("duplicate option \"%s\"", defel->defname)));
     845                 :          36 :             opt->sendtblspcmapfile = defGetBoolean(defel);
     846                 :          36 :             o_tablespace_map = true;
     847                 :             :         }
     848         [ +  + ]:         494 :         else if (strcmp(defel->defname, "verify_checksums") == 0)
     849                 :             :         {
     850         [ -  + ]:           1 :             if (o_noverify_checksums)
     851         [ #  # ]:           0 :                 ereport(ERROR,
     852                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     853                 :             :                          errmsg("duplicate option \"%s\"", defel->defname)));
     854                 :           1 :             noverify_checksums = !defGetBoolean(defel);
     855                 :           1 :             o_noverify_checksums = true;
     856                 :             :         }
     857         [ +  + ]:         493 :         else if (strcmp(defel->defname, "manifest") == 0)
     858                 :             :         {
     859                 :         217 :             char       *optval = defGetString(defel);
     860                 :             :             bool        manifest_bool;
     861                 :             : 
     862         [ -  + ]:         217 :             if (o_manifest)
     863         [ #  # ]:           0 :                 ereport(ERROR,
     864                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     865                 :             :                          errmsg("duplicate option \"%s\"", defel->defname)));
     866         [ +  + ]:         217 :             if (parse_bool(optval, &manifest_bool))
     867                 :             :             {
     868         [ +  - ]:         216 :                 if (manifest_bool)
     869                 :         216 :                     opt->manifest = MANIFEST_OPTION_YES;
     870                 :             :                 else
     871                 :           0 :                     opt->manifest = MANIFEST_OPTION_NO;
     872                 :             :             }
     873         [ +  - ]:           1 :             else if (pg_strcasecmp(optval, "force-encode") == 0)
     874                 :           1 :                 opt->manifest = MANIFEST_OPTION_FORCE_ENCODE;
     875                 :             :             else
     876         [ #  # ]:           0 :                 ereport(ERROR,
     877                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     878                 :             :                          errmsg("unrecognized manifest option: \"%s\"",
     879                 :             :                                 optval)));
     880                 :         217 :             o_manifest = true;
     881                 :             :         }
     882         [ +  + ]:         276 :         else if (strcmp(defel->defname, "manifest_checksums") == 0)
     883                 :             :         {
     884                 :          14 :             char       *optval = defGetString(defel);
     885                 :             : 
     886         [ -  + ]:          14 :             if (o_manifest_checksums)
     887         [ #  # ]:           0 :                 ereport(ERROR,
     888                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     889                 :             :                          errmsg("duplicate option \"%s\"", defel->defname)));
     890         [ +  + ]:          14 :             if (!pg_checksum_parse_type(optval,
     891                 :             :                                         &opt->manifest_checksum_type))
     892         [ +  - ]:           2 :                 ereport(ERROR,
     893                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     894                 :             :                          errmsg("unrecognized checksum algorithm: \"%s\"",
     895                 :             :                                 optval)));
     896                 :          12 :             o_manifest_checksums = true;
     897                 :             :         }
     898         [ +  + ]:         262 :         else if (strcmp(defel->defname, "target") == 0)
     899                 :             :         {
     900         [ -  + ]:         216 :             if (o_target)
     901         [ #  # ]:           0 :                 ereport(ERROR,
     902                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     903                 :             :                          errmsg("duplicate option \"%s\"", defel->defname)));
     904                 :         216 :             target_str = defGetString(defel);
     905                 :         216 :             o_target = true;
     906                 :             :         }
     907         [ +  + ]:          46 :         else if (strcmp(defel->defname, "target_detail") == 0)
     908                 :             :         {
     909                 :           8 :             char       *optval = defGetString(defel);
     910                 :             : 
     911         [ -  + ]:           8 :             if (o_target_detail)
     912         [ #  # ]:           0 :                 ereport(ERROR,
     913                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     914                 :             :                          errmsg("duplicate option \"%s\"", defel->defname)));
     915                 :           8 :             target_detail_str = optval;
     916                 :           8 :             o_target_detail = true;
     917                 :             :         }
     918         [ +  + ]:          38 :         else if (strcmp(defel->defname, "compression") == 0)
     919                 :             :         {
     920                 :          26 :             char       *optval = defGetString(defel);
     921                 :             : 
     922         [ -  + ]:          26 :             if (o_compression)
     923         [ #  # ]:           0 :                 ereport(ERROR,
     924                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     925                 :             :                          errmsg("duplicate option \"%s\"", defel->defname)));
     926         [ +  + ]:          26 :             if (!parse_compress_algorithm(optval, &opt->compression))
     927         [ +  - ]:           1 :                 ereport(ERROR,
     928                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     929                 :             :                          errmsg("unrecognized compression algorithm: \"%s\"",
     930                 :             :                                 optval)));
     931                 :          25 :             o_compression = true;
     932                 :             :         }
     933         [ +  - ]:          12 :         else if (strcmp(defel->defname, "compression_detail") == 0)
     934                 :             :         {
     935         [ -  + ]:          12 :             if (o_compression_detail)
     936         [ #  # ]:           0 :                 ereport(ERROR,
     937                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     938                 :             :                          errmsg("duplicate option \"%s\"", defel->defname)));
     939                 :          12 :             compression_detail_str = defGetString(defel);
     940                 :          12 :             o_compression_detail = true;
     941                 :             :         }
     942                 :             :         else
     943         [ #  # ]:           0 :             ereport(ERROR,
     944                 :             :                     (errcode(ERRCODE_SYNTAX_ERROR),
     945                 :             :                      errmsg("unrecognized base backup option: \"%s\"",
     946                 :             :                             defel->defname)));
     947                 :             :     }
     948                 :             : 
     949         [ +  + ]:         216 :     if (opt->label == NULL)
     950                 :           1 :         opt->label = "base backup";
     951         [ +  + ]:         216 :     if (opt->manifest == MANIFEST_OPTION_NO)
     952                 :             :     {
     953         [ -  + ]:           2 :         if (o_manifest_checksums)
     954         [ #  # ]:           0 :             ereport(ERROR,
     955                 :             :                     (errcode(ERRCODE_SYNTAX_ERROR),
     956                 :             :                      errmsg("manifest checksums require a backup manifest")));
     957                 :           2 :         opt->manifest_checksum_type = CHECKSUM_TYPE_NONE;
     958                 :             :     }
     959                 :             : 
     960         [ +  + ]:         216 :     if (target_str == NULL)
     961                 :             :     {
     962         [ -  + ]:           1 :         if (target_detail_str != NULL)
     963         [ #  # ]:           0 :             ereport(ERROR,
     964                 :             :                     (errcode(ERRCODE_SYNTAX_ERROR),
     965                 :             :                      errmsg("target detail cannot be used without target")));
     966                 :           1 :         opt->use_copytblspc = true;
     967                 :           1 :         opt->send_to_client = true;
     968                 :             :     }
     969         [ +  + ]:         215 :     else if (strcmp(target_str, "client") == 0)
     970                 :             :     {
     971         [ -  + ]:         201 :         if (target_detail_str != NULL)
     972         [ #  # ]:           0 :             ereport(ERROR,
     973                 :             :                     (errcode(ERRCODE_SYNTAX_ERROR),
     974                 :             :                      errmsg("target \"%s\" does not accept a target detail",
     975                 :             :                             target_str)));
     976                 :         201 :         opt->send_to_client = true;
     977                 :             :     }
     978                 :             :     else
     979                 :          12 :         opt->target_handle =
     980                 :          14 :             BaseBackupGetTargetHandle(target_str, target_detail_str);
     981                 :             : 
     982   [ +  +  -  + ]:         214 :     if (o_compression_detail && !o_compression)
     983         [ #  # ]:           0 :         ereport(ERROR,
     984                 :             :                 (errcode(ERRCODE_SYNTAX_ERROR),
     985                 :             :                  errmsg("compression detail cannot be specified unless compression is enabled")));
     986                 :             : 
     987         [ +  + ]:         214 :     if (o_compression)
     988                 :             :     {
     989                 :             :         char       *error_detail;
     990                 :             : 
     991                 :          23 :         parse_compress_specification(opt->compression, compression_detail_str,
     992                 :             :                                      &opt->compression_specification);
     993                 :             :         error_detail =
     994                 :          23 :             validate_compress_specification(&opt->compression_specification);
     995         [ +  + ]:          23 :         if (error_detail != NULL)
     996         [ +  - ]:           9 :             ereport(ERROR,
     997                 :             :                     errcode(ERRCODE_SYNTAX_ERROR),
     998                 :             :                     errmsg("invalid compression specification: %s",
     999                 :             :                            error_detail));
    1000                 :             :     }
    1001                 :         205 : }
    1002                 :             : 
    1003                 :             : 
    1004                 :             : /*
    1005                 :             :  * SendBaseBackup() - send a complete base backup.
    1006                 :             :  *
    1007                 :             :  * The function will put the system into backup mode like pg_backup_start()
    1008                 :             :  * does, so that the backup is consistent even though we read directly from
    1009                 :             :  * the filesystem, bypassing the buffer cache.
    1010                 :             :  */
    1011                 :             : void
    1012                 :         220 : SendBaseBackup(BaseBackupCmd *cmd, IncrementalBackupInfo *ib)
    1013                 :             : {
    1014                 :             :     basebackup_options opt;
    1015                 :             :     bbsink     *sink;
    1016                 :         220 :     SessionBackupState status = get_backup_status();
    1017                 :             : 
    1018         [ +  + ]:         220 :     if (status == SESSION_BACKUP_RUNNING)
    1019         [ +  - ]:           1 :         ereport(ERROR,
    1020                 :             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1021                 :             :                  errmsg("a backup is already in progress in this session")));
    1022                 :             : 
    1023                 :         219 :     parse_basebackup_options(cmd->options, &opt);
    1024                 :             : 
    1025                 :         205 :     WalSndSetState(WALSNDSTATE_BACKUP);
    1026                 :             : 
    1027         [ +  - ]:         205 :     if (update_process_title)
    1028                 :             :     {
    1029                 :             :         char        activitymsg[50];
    1030                 :             : 
    1031                 :         205 :         snprintf(activitymsg, sizeof(activitymsg), "sending backup \"%s\"",
    1032                 :             :                  opt.label);
    1033                 :         205 :         set_ps_display(activitymsg);
    1034                 :             :     }
    1035                 :             : 
    1036                 :             :     /*
    1037                 :             :      * If we're asked to perform an incremental backup and the user has not
    1038                 :             :      * supplied a manifest, that's an ERROR.
    1039                 :             :      *
    1040                 :             :      * If we're asked to perform a full backup and the user did supply a
    1041                 :             :      * manifest, just ignore it.
    1042                 :             :      */
    1043         [ +  + ]:         205 :     if (!opt.incremental)
    1044                 :         189 :         ib = NULL;
    1045         [ -  + ]:          16 :     else if (ib == NULL)
    1046         [ #  # ]:           0 :         ereport(ERROR,
    1047                 :             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1048                 :             :                  errmsg("must UPLOAD_MANIFEST before performing an incremental BASE_BACKUP")));
    1049                 :             : 
    1050                 :             :     /*
    1051                 :             :      * If the target is specifically 'client' then set up to stream the backup
    1052                 :             :      * to the client; otherwise, it's being sent someplace else and should not
    1053                 :             :      * be sent to the client. BaseBackupGetSink has the job of setting up a
    1054                 :             :      * sink to send the backup data wherever it needs to go.
    1055                 :             :      */
    1056                 :         205 :     sink = bbsink_copystream_new(opt.send_to_client);
    1057         [ +  + ]:         205 :     if (opt.target_handle != NULL)
    1058                 :          12 :         sink = BaseBackupGetSink(opt.target_handle, sink);
    1059                 :             : 
    1060                 :             :     /* Set up network throttling, if client requested it */
    1061         [ +  + ]:         202 :     if (opt.maxrate > 0)
    1062                 :           2 :         sink = bbsink_throttle_new(sink, opt.maxrate);
    1063                 :             : 
    1064                 :             :     /* Set up server-side compression, if client requested it */
    1065         [ +  + ]:         202 :     if (opt.compression == PG_COMPRESSION_GZIP)
    1066                 :           2 :         sink = bbsink_gzip_new(sink, &opt.compression_specification);
    1067         [ +  + ]:         200 :     else if (opt.compression == PG_COMPRESSION_LZ4)
    1068                 :           3 :         sink = bbsink_lz4_new(sink, &opt.compression_specification);
    1069         [ -  + ]:         197 :     else if (opt.compression == PG_COMPRESSION_ZSTD)
    1070                 :           0 :         sink = bbsink_zstd_new(sink, &opt.compression_specification);
    1071                 :             : 
    1072                 :             :     /* Set up progress reporting. */
    1073                 :         202 :     sink = bbsink_progress_new(sink, opt.progress, opt.incremental);
    1074                 :             : 
    1075                 :             :     /*
    1076                 :             :      * Perform the base backup, but make sure we clean up the bbsink even if
    1077                 :             :      * an error occurs.
    1078                 :             :      */
    1079         [ +  + ]:         202 :     PG_TRY();
    1080                 :             :     {
    1081                 :         202 :         perform_base_backup(&opt, sink, ib);
    1082                 :             :     }
    1083                 :           7 :     PG_FINALLY();
    1084                 :             :     {
    1085                 :         198 :         bbsink_cleanup(sink);
    1086                 :             :     }
    1087         [ +  + ]:         198 :     PG_END_TRY();
    1088                 :         191 : }
    1089                 :             : 
    1090                 :             : /*
    1091                 :             :  * Inject a file with given name and content in the output tar stream.
    1092                 :             :  *
    1093                 :             :  * "len" can optionally be set to an arbitrary length of data sent.  If set
    1094                 :             :  * to -1, the content sent is treated as a string with strlen() as length.
    1095                 :             :  */
    1096                 :             : static void
    1097                 :         439 : sendFileWithContent(bbsink *sink, const char *filename, const char *content,
    1098                 :             :                     int len, backup_manifest_info *manifest)
    1099                 :             : {
    1100                 :             :     struct stat statbuf;
    1101                 :         439 :     int         bytes_done = 0;
    1102                 :             :     pg_checksum_context checksum_ctx;
    1103                 :             : 
    1104         [ -  + ]:         439 :     if (pg_checksum_init(&checksum_ctx, manifest->checksum_type) < 0)
    1105         [ #  # ]:           0 :         elog(ERROR, "could not initialize checksum of file \"%s\"",
    1106                 :             :              filename);
    1107                 :             : 
    1108         [ +  + ]:         439 :     if (len < 0)
    1109                 :         245 :         len = strlen(content);
    1110                 :             : 
    1111                 :             :     /*
    1112                 :             :      * Construct a stat struct for the file we're injecting in the tar.
    1113                 :             :      */
    1114                 :             : 
    1115                 :             :     /* Windows doesn't have the concept of uid and gid */
    1116                 :             : #ifdef WIN32
    1117                 :             :     statbuf.st_uid = 0;
    1118                 :             :     statbuf.st_gid = 0;
    1119                 :             : #else
    1120                 :         439 :     statbuf.st_uid = geteuid();
    1121                 :         439 :     statbuf.st_gid = getegid();
    1122                 :             : #endif
    1123                 :         439 :     statbuf.st_mtime = time(NULL);
    1124                 :         439 :     statbuf.st_mode = pg_file_create_mode;
    1125                 :         439 :     statbuf.st_size = len;
    1126                 :             : 
    1127                 :         439 :     _tarWriteHeader(sink, filename, NULL, &statbuf, false);
    1128                 :             : 
    1129         [ -  + ]:         439 :     if (pg_checksum_update(&checksum_ctx, (const uint8 *) content, len) < 0)
    1130         [ #  # ]:           0 :         elog(ERROR, "could not update checksum of file \"%s\"",
    1131                 :             :              filename);
    1132                 :             : 
    1133         [ +  + ]:         839 :     while (bytes_done < len)
    1134                 :             :     {
    1135                 :         400 :         size_t      remaining = len - bytes_done;
    1136                 :         400 :         size_t      nbytes = Min(sink->bbs_buffer_length, remaining);
    1137                 :             : 
    1138                 :         400 :         memcpy(sink->bbs_buffer, content, nbytes);
    1139                 :         400 :         bbsink_archive_contents(sink, nbytes);
    1140                 :         400 :         bytes_done += nbytes;
    1141                 :         400 :         content += nbytes;
    1142                 :             :     }
    1143                 :             : 
    1144                 :         439 :     _tarWritePadding(sink, len);
    1145                 :             : 
    1146                 :         439 :     AddFileToBackupManifest(manifest, InvalidOid, filename, len,
    1147                 :         439 :                             (pg_time_t) statbuf.st_mtime, &checksum_ctx);
    1148                 :         439 : }
    1149                 :             : 
    1150                 :             : /*
    1151                 :             :  * Include the tablespace directory pointed to by 'path' in the output tar
    1152                 :             :  * stream.  If 'sizeonly' is true, we just calculate a total length and return
    1153                 :             :  * it, without actually sending anything.
    1154                 :             :  *
    1155                 :             :  * Only used to send auxiliary tablespaces, not PGDATA.
    1156                 :             :  */
    1157                 :             : static int64
    1158                 :          76 : sendTablespace(bbsink *sink, char *path, Oid spcoid, bool sizeonly,
    1159                 :             :                backup_manifest_info *manifest, IncrementalBackupInfo *ib)
    1160                 :             : {
    1161                 :             :     int64       size;
    1162                 :             :     char        pathbuf[MAXPGPATH];
    1163                 :             :     struct stat statbuf;
    1164                 :             : 
    1165                 :             :     /*
    1166                 :             :      * 'path' points to the tablespace location, but we only want to include
    1167                 :             :      * the version directory in it that belongs to us.
    1168                 :             :      */
    1169                 :          76 :     snprintf(pathbuf, sizeof(pathbuf), "%s/%s", path,
    1170                 :             :              TABLESPACE_VERSION_DIRECTORY);
    1171                 :             : 
    1172                 :             :     /*
    1173                 :             :      * Store a directory entry in the tar file so we get the permissions
    1174                 :             :      * right.
    1175                 :             :      */
    1176         [ -  + ]:          76 :     if (lstat(pathbuf, &statbuf) != 0)
    1177                 :             :     {
    1178         [ #  # ]:           0 :         if (errno != ENOENT)
    1179         [ #  # ]:           0 :             ereport(ERROR,
    1180                 :             :                     (errcode_for_file_access(),
    1181                 :             :                      errmsg("could not stat file or directory \"%s\": %m",
    1182                 :             :                             pathbuf)));
    1183                 :             : 
    1184                 :             :         /* If the tablespace went away while scanning, it's no error. */
    1185                 :           0 :         return 0;
    1186                 :             :     }
    1187                 :             : 
    1188                 :          76 :     size = _tarWriteHeader(sink, TABLESPACE_VERSION_DIRECTORY, NULL, &statbuf,
    1189                 :             :                            sizeonly);
    1190                 :             : 
    1191                 :             :     /* Send all the files in the tablespace version directory */
    1192                 :          76 :     size += sendDir(sink, pathbuf, strlen(path), sizeonly, NIL, true, manifest,
    1193                 :             :                     spcoid, ib);
    1194                 :             : 
    1195                 :          76 :     return size;
    1196                 :             : }
    1197                 :             : 
    1198                 :             : /*
    1199                 :             :  * Include all files from the given directory in the output tar stream. If
    1200                 :             :  * 'sizeonly' is true, we just calculate a total length and return it, without
    1201                 :             :  * actually sending anything. A file that will be sent incrementally is
    1202                 :             :  * counted at the size of the incremental file.
    1203                 :             :  *
    1204                 :             :  * Omit any directory in the tablespaces list, to avoid backing up
    1205                 :             :  * tablespaces twice when they were created inside PGDATA.
    1206                 :             :  *
    1207                 :             :  * If sendtblspclinks is true, we need to include symlink
    1208                 :             :  * information in the tar file. If not, we can skip that
    1209                 :             :  * as it will be sent separately in the tablespace_map file.
    1210                 :             :  */
    1211                 :             : static int64
    1212                 :        6875 : sendDir(bbsink *sink, const char *path, int basepathlen, bool sizeonly,
    1213                 :             :         List *tablespaces, bool sendtblspclinks, backup_manifest_info *manifest,
    1214                 :             :         Oid spcoid, IncrementalBackupInfo *ib)
    1215                 :             : {
    1216                 :             :     DIR        *dir;
    1217                 :             :     struct dirent *de;
    1218                 :             :     char        pathbuf[MAXPGPATH * 2];
    1219                 :             :     struct stat statbuf;
    1220                 :        6875 :     int64       size = 0;
    1221                 :             :     const char *lastDir;        /* Split last dir from parent path. */
    1222                 :        6875 :     bool        isRelationDir = false;  /* Does directory contain relations? */
    1223                 :        6875 :     bool        isGlobalDir = false;
    1224                 :        6875 :     Oid         dboid = InvalidOid;
    1225                 :        6875 :     BlockNumber *relative_block_numbers = NULL;
    1226                 :             : 
    1227                 :             :     /*
    1228                 :             :      * Since this array is relatively large, avoid putting it on the stack.
    1229                 :             :      * But we don't need it at all if this is not an incremental backup.
    1230                 :             :      */
    1231         [ +  + ]:        6875 :     if (ib != NULL)
    1232                 :         484 :         relative_block_numbers = palloc_array(BlockNumber, RELSEG_SIZE);
    1233                 :             : 
    1234                 :             :     /*
    1235                 :             :      * Determine if the current path is a database directory that can contain
    1236                 :             :      * relations.
    1237                 :             :      *
    1238                 :             :      * Start by finding the location of the delimiter between the parent path
    1239                 :             :      * and the current path.
    1240                 :             :      */
    1241                 :        6875 :     lastDir = last_dir_separator(path);
    1242                 :             : 
    1243                 :             :     /* Does this path look like a database path (i.e. all digits)? */
    1244         [ +  + ]:        6875 :     if (lastDir != NULL &&
    1245         [ +  + ]:        6476 :         strspn(lastDir + 1, "0123456789") == strlen(lastDir + 1))
    1246                 :        1268 :     {
    1247                 :             :         /* Part of path that contains the parent directory. */
    1248                 :        1268 :         int         parentPathLen = lastDir - path;
    1249                 :             : 
    1250                 :             :         /*
    1251                 :             :          * Mark path as a database directory if the parent path is either
    1252                 :             :          * $PGDATA/base or a tablespace version path.
    1253                 :             :          */
    1254         [ +  + ]:        1268 :         if (strncmp(path, "./base", parentPathLen) == 0 ||
    1255         [ +  - ]:          54 :             (parentPathLen >= (sizeof(TABLESPACE_VERSION_DIRECTORY) - 1) &&
    1256         [ +  - ]:          54 :              strncmp(lastDir - (sizeof(TABLESPACE_VERSION_DIRECTORY) - 1),
    1257                 :             :                      TABLESPACE_VERSION_DIRECTORY,
    1258                 :             :                      sizeof(TABLESPACE_VERSION_DIRECTORY) - 1) == 0))
    1259                 :             :         {
    1260                 :        1268 :             isRelationDir = true;
    1261                 :        1268 :             dboid = atooid(lastDir + 1);
    1262                 :             :         }
    1263                 :             :     }
    1264         [ +  + ]:        5607 :     else if (strcmp(path, "./global") == 0)
    1265                 :             :     {
    1266                 :         395 :         isRelationDir = true;
    1267                 :         395 :         isGlobalDir = true;
    1268                 :             :     }
    1269                 :             : 
    1270                 :        6875 :     dir = AllocateDir(path);
    1271         [ +  + ]:      425840 :     while ((de = ReadDir(dir, path)) != NULL)
    1272                 :             :     {
    1273                 :             :         int         excludeIdx;
    1274                 :             :         bool        excludeFound;
    1275                 :      418975 :         RelFileNumber relfilenumber = InvalidRelFileNumber;
    1276                 :      418975 :         ForkNumber  relForkNum = InvalidForkNumber;
    1277                 :      418975 :         unsigned    segno = 0;
    1278                 :      418975 :         bool        isRelationFile = false;
    1279                 :             : 
    1280                 :             :         /* Skip special stuff */
    1281   [ +  +  +  + ]:      418975 :         if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
    1282                 :       19419 :             continue;
    1283                 :             : 
    1284                 :             :         /* Skip temporary files */
    1285         [ +  + ]:      405241 :         if (strncmp(de->d_name,
    1286                 :             :                     PG_TEMP_FILE_PREFIX,
    1287                 :             :                     strlen(PG_TEMP_FILE_PREFIX)) == 0)
    1288                 :         393 :             continue;
    1289                 :             : 
    1290                 :             :         /* Skip macOS system files */
    1291         [ +  + ]:      404848 :         if (strcmp(de->d_name, ".DS_Store") == 0)
    1292                 :          68 :             continue;
    1293                 :             : 
    1294                 :             :         /*
    1295                 :             :          * Check if the postmaster has signaled us to exit, and abort with an
    1296                 :             :          * error in that case. The error handler further up will call
    1297                 :             :          * do_pg_abort_backup() for us. Also check that if the backup was
    1298                 :             :          * started while still in recovery, the server wasn't promoted.
    1299                 :             :          * do_pg_backup_stop() will check that too, but it's better to stop
    1300                 :             :          * the backup early than continue to the end and fail there.
    1301                 :             :          */
    1302         [ +  + ]:      404780 :         CHECK_FOR_INTERRUPTS();
    1303         [ -  + ]:      404776 :         if (RecoveryInProgress() != backup_started_in_recovery)
    1304         [ #  # ]:           0 :             ereport(ERROR,
    1305                 :             :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1306                 :             :                      errmsg("the standby was promoted during online backup"),
    1307                 :             :                      errhint("This means that the backup being taken is corrupt "
    1308                 :             :                              "and should not be used. "
    1309                 :             :                              "Try taking another online backup.")));
    1310                 :             : 
    1311                 :             :         /* Scan for files that should be excluded */
    1312                 :      404776 :         excludeFound = false;
    1313         [ +  + ]:     3637114 :         for (excludeIdx = 0; excludeFiles[excludeIdx].name != NULL; excludeIdx++)
    1314                 :             :         {
    1315                 :     3233892 :             int         cmplen = strlen(excludeFiles[excludeIdx].name);
    1316                 :             : 
    1317         [ +  + ]:     3233892 :             if (!excludeFiles[excludeIdx].match_prefix)
    1318                 :     2829248 :                 cmplen++;
    1319         [ +  + ]:     3233892 :             if (strncmp(de->d_name, excludeFiles[excludeIdx].name, cmplen) == 0)
    1320                 :             :             {
    1321         [ +  + ]:        1554 :                 elog(DEBUG1, "file \"%s\" excluded from backup", de->d_name);
    1322                 :        1554 :                 excludeFound = true;
    1323                 :        1554 :                 break;
    1324                 :             :             }
    1325                 :             :         }
    1326                 :             : 
    1327         [ +  + ]:      404776 :         if (excludeFound)
    1328                 :        1554 :             continue;
    1329                 :             : 
    1330                 :             :         /*
    1331                 :             :          * If there could be non-temporary relation files in this directory,
    1332                 :             :          * try to parse the filename.
    1333                 :             :          */
    1334         [ +  + ]:      403222 :         if (isRelationDir)
    1335                 :             :             isRelationFile =
    1336                 :      389432 :                 parse_filename_for_nontemp_relation(de->d_name,
    1337                 :             :                                                     &relfilenumber,
    1338                 :             :                                                     &relForkNum, &segno);
    1339                 :             : 
    1340                 :             :         /* Exclude all forks for unlogged tables except the init fork */
    1341   [ +  +  +  + ]:      403222 :         if (isRelationFile && relForkNum != INIT_FORKNUM)
    1342                 :             :         {
    1343                 :             :             char        initForkFile[MAXPGPATH];
    1344                 :             : 
    1345                 :             :             /*
    1346                 :             :              * If any other type of fork, check if there is an init fork with
    1347                 :             :              * the same RelFileNumber. If so, the file can be excluded.
    1348                 :             :              */
    1349                 :      386099 :             snprintf(initForkFile, sizeof(initForkFile), "%s/%u_init",
    1350                 :             :                      path, relfilenumber);
    1351                 :             : 
    1352         [ +  + ]:      386099 :             if (lstat(initForkFile, &statbuf) == 0)
    1353                 :             :             {
    1354         [ -  + ]:          81 :                 elog(DEBUG2,
    1355                 :             :                      "unlogged relation file \"%s\" excluded from backup",
    1356                 :             :                      de->d_name);
    1357                 :             : 
    1358                 :          81 :                 continue;
    1359                 :             :             }
    1360                 :             :         }
    1361                 :             : 
    1362                 :             :         /* Exclude temporary relations */
    1363   [ +  +  +  + ]:      403141 :         if (OidIsValid(dboid) && looks_like_temp_rel_name(de->d_name))
    1364                 :             :         {
    1365         [ -  + ]:          36 :             elog(DEBUG2,
    1366                 :             :                  "temporary relation file \"%s\" excluded from backup",
    1367                 :             :                  de->d_name);
    1368                 :             : 
    1369                 :          36 :             continue;
    1370                 :             :         }
    1371                 :             : 
    1372                 :      403105 :         snprintf(pathbuf, sizeof(pathbuf), "%s/%s", path, de->d_name);
    1373                 :             : 
    1374                 :             :         /* Skip pg_control here to back up it last */
    1375         [ +  + ]:      403105 :         if (strcmp(pathbuf, "./" XLOG_CONTROL_FILE) == 0)
    1376                 :         394 :             continue;
    1377                 :             : 
    1378         [ -  + ]:      402711 :         if (lstat(pathbuf, &statbuf) != 0)
    1379                 :             :         {
    1380         [ #  # ]:           0 :             if (errno != ENOENT)
    1381         [ #  # ]:           0 :                 ereport(ERROR,
    1382                 :             :                         (errcode_for_file_access(),
    1383                 :             :                          errmsg("could not stat file or directory \"%s\": %m",
    1384                 :             :                                 pathbuf)));
    1385                 :             : 
    1386                 :             :             /* If the file went away while scanning, it's not an error. */
    1387                 :           0 :             continue;
    1388                 :             :         }
    1389                 :             : 
    1390                 :             :         /* Scan for directories whose contents should be excluded */
    1391                 :      402711 :         excludeFound = false;
    1392         [ +  + ]:     3210611 :         for (excludeIdx = 0; excludeDirContents[excludeIdx] != NULL; excludeIdx++)
    1393                 :             :         {
    1394         [ +  + ]:     2810666 :             if (strcmp(de->d_name, excludeDirContents[excludeIdx]) == 0)
    1395                 :             :             {
    1396         [ +  + ]:        2766 :                 elog(DEBUG1, "contents of directory \"%s\" excluded from backup", de->d_name);
    1397                 :        2766 :                 convert_link_to_directory(pathbuf, &statbuf);
    1398                 :        2766 :                 size += _tarWriteHeader(sink, pathbuf + basepathlen + 1, NULL,
    1399                 :             :                                         &statbuf, sizeonly);
    1400                 :        2765 :                 excludeFound = true;
    1401                 :        2765 :                 break;
    1402                 :             :             }
    1403                 :             :         }
    1404                 :             : 
    1405         [ +  + ]:      402710 :         if (excludeFound)
    1406                 :        2765 :             continue;
    1407                 :             : 
    1408                 :             :         /*
    1409                 :             :          * We can skip pg_wal, the WAL segments need to be fetched from the
    1410                 :             :          * WAL archive anyway. But include it as an empty directory anyway, so
    1411                 :             :          * we get permissions right.
    1412                 :             :          */
    1413         [ +  + ]:      399945 :         if (strcmp(pathbuf, "./pg_wal") == 0)
    1414                 :             :         {
    1415                 :             :             /* If pg_wal is a symlink, write it as a directory anyway */
    1416                 :         394 :             convert_link_to_directory(pathbuf, &statbuf);
    1417                 :         394 :             size += _tarWriteHeader(sink, pathbuf + basepathlen + 1, NULL,
    1418                 :             :                                     &statbuf, sizeonly);
    1419                 :             : 
    1420                 :             :             /*
    1421                 :             :              * Also send archive_status and summaries directories (by
    1422                 :             :              * hackishly reusing statbuf from above ...).
    1423                 :             :              */
    1424                 :         394 :             size += _tarWriteHeader(sink, "./pg_wal/archive_status", NULL,
    1425                 :             :                                     &statbuf, sizeonly);
    1426                 :         394 :             size += _tarWriteHeader(sink, "./pg_wal/summaries", NULL,
    1427                 :             :                                     &statbuf, sizeonly);
    1428                 :             : 
    1429                 :         394 :             continue;           /* don't recurse into pg_wal */
    1430                 :             :         }
    1431                 :             : 
    1432                 :             :         /* Allow symbolic links in pg_tblspc only */
    1433   [ +  +  +  + ]:      399551 :         if (strcmp(path, "./pg_tblspc") == 0 && S_ISLNK(statbuf.st_mode))
    1434                 :          39 :         {
    1435                 :             :             char        linkpath[MAXPGPATH];
    1436                 :             :             ssize_t     rllen;
    1437                 :             : 
    1438                 :          39 :             rllen = readlink(pathbuf, linkpath, sizeof(linkpath));
    1439         [ -  + ]:          39 :             if (rllen < 0)
    1440         [ #  # ]:           0 :                 ereport(ERROR,
    1441                 :             :                         (errcode_for_file_access(),
    1442                 :             :                          errmsg("could not read symbolic link \"%s\": %m",
    1443                 :             :                                 pathbuf)));
    1444         [ -  + ]:          39 :             if (rllen >= sizeof(linkpath))
    1445         [ #  # ]:           0 :                 ereport(ERROR,
    1446                 :             :                         (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    1447                 :             :                          errmsg("symbolic link \"%s\" target is too long",
    1448                 :             :                                 pathbuf)));
    1449                 :          39 :             linkpath[rllen] = '\0';
    1450                 :             : 
    1451                 :          39 :             size += _tarWriteHeader(sink, pathbuf + basepathlen + 1, linkpath,
    1452                 :             :                                     &statbuf, sizeonly);
    1453                 :             :         }
    1454         [ +  + ]:      399512 :         else if (S_ISDIR(statbuf.st_mode))
    1455                 :             :         {
    1456                 :        6458 :             bool        skip_this_dir = false;
    1457                 :             :             ListCell   *lc;
    1458                 :             : 
    1459                 :             :             /*
    1460                 :             :              * Store a directory entry in the tar file so we can get the
    1461                 :             :              * permissions right.
    1462                 :             :              */
    1463                 :        6458 :             size += _tarWriteHeader(sink, pathbuf + basepathlen + 1, NULL, &statbuf,
    1464                 :             :                                     sizeonly);
    1465                 :             : 
    1466                 :             :             /*
    1467                 :             :              * Call ourselves recursively for a directory, unless it happens
    1468                 :             :              * to be a separate tablespace located within PGDATA.
    1469                 :             :              */
    1470   [ +  +  +  +  :       14082 :             foreach(lc, tablespaces)
                   +  + ]
    1471                 :             :             {
    1472                 :        7653 :                 tablespaceinfo *ti = (tablespaceinfo *) lfirst(lc);
    1473                 :             : 
    1474                 :             :                 /*
    1475                 :             :                  * ti->rpath is the tablespace relative path within PGDATA, or
    1476                 :             :                  * NULL if the tablespace has been properly located somewhere
    1477                 :             :                  * else.
    1478                 :             :                  *
    1479                 :             :                  * Skip past the leading "./" in pathbuf when comparing.
    1480                 :             :                  */
    1481   [ +  +  +  + ]:        7653 :                 if (ti->rpath && strcmp(ti->rpath, pathbuf + 2) == 0)
    1482                 :             :                 {
    1483                 :          29 :                     skip_this_dir = true;
    1484                 :          29 :                     break;
    1485                 :             :                 }
    1486                 :             :             }
    1487                 :             : 
    1488                 :             :             /*
    1489                 :             :              * skip sending directories inside pg_tblspc, if not required.
    1490                 :             :              */
    1491   [ +  +  +  + ]:        6458 :             if (strcmp(pathbuf, "./pg_tblspc") == 0 && !sendtblspclinks)
    1492                 :          29 :                 skip_this_dir = true;
    1493                 :             : 
    1494         [ +  + ]:        6458 :             if (!skip_this_dir)
    1495                 :        6400 :                 size += sendDir(sink, pathbuf, basepathlen, sizeonly, tablespaces,
    1496                 :             :                                 sendtblspclinks, manifest, spcoid, ib);
    1497                 :             :         }
    1498         [ +  - ]:      393054 :         else if (S_ISREG(statbuf.st_mode))
    1499                 :             :         {
    1500                 :      393054 :             bool        sent = false;
    1501                 :      393054 :             unsigned    num_blocks_required = 0;
    1502                 :      393054 :             unsigned    truncation_block_length = 0;
    1503                 :             :             char        tarfilenamebuf[MAXPGPATH * 2];
    1504                 :      393054 :             char       *tarfilename = pathbuf + basepathlen + 1;
    1505                 :      393054 :             FileBackupMethod method = BACK_UP_FILE_FULLY;
    1506                 :             : 
    1507   [ +  +  +  + ]:      393054 :             if (ib != NULL && isRelationFile)
    1508                 :             :             {
    1509                 :             :                 Oid         relspcoid;
    1510                 :             :                 char       *lookup_path;
    1511                 :             : 
    1512         [ +  + ]:       28024 :                 if (OidIsValid(spcoid))
    1513                 :             :                 {
    1514                 :          18 :                     relspcoid = spcoid;
    1515                 :          18 :                     lookup_path = psprintf("%s/%u/%s", PG_TBLSPC_DIR, spcoid,
    1516                 :             :                                            tarfilename);
    1517                 :             :                 }
    1518                 :             :                 else
    1519                 :             :                 {
    1520         [ +  + ]:       28006 :                     if (isGlobalDir)
    1521                 :        1568 :                         relspcoid = GLOBALTABLESPACE_OID;
    1522                 :             :                     else
    1523                 :       26438 :                         relspcoid = DEFAULTTABLESPACE_OID;
    1524                 :       28006 :                     lookup_path = pstrdup(tarfilename);
    1525                 :             :                 }
    1526                 :             : 
    1527                 :       28024 :                 method = GetFileBackupMethod(ib, lookup_path, dboid, relspcoid,
    1528                 :             :                                              relfilenumber, relForkNum,
    1529                 :       28024 :                                              segno, statbuf.st_size,
    1530                 :             :                                              &num_blocks_required,
    1531                 :             :                                              relative_block_numbers,
    1532                 :             :                                              &truncation_block_length);
    1533         [ +  + ]:       28024 :                 if (method == BACK_UP_FILE_INCREMENTALLY)
    1534                 :             :                 {
    1535                 :       18734 :                     statbuf.st_size =
    1536                 :       18734 :                         GetIncrementalFileSize(num_blocks_required);
    1537                 :       18734 :                     snprintf(tarfilenamebuf, sizeof(tarfilenamebuf),
    1538                 :             :                              "%s/INCREMENTAL.%s",
    1539                 :       18734 :                              path + basepathlen + 1,
    1540                 :       18734 :                              de->d_name);
    1541                 :       18734 :                     tarfilename = tarfilenamebuf;
    1542                 :             :                 }
    1543                 :             : 
    1544                 :       28024 :                 pfree(lookup_path);
    1545                 :             :             }
    1546                 :             : 
    1547         [ +  + ]:      393054 :             if (!sizeonly)
    1548         [ +  + ]:      194158 :                 sent = sendFile(sink, pathbuf, tarfilename, &statbuf,
    1549                 :             :                                 true, dboid, spcoid,
    1550                 :             :                                 relfilenumber, segno, manifest,
    1551                 :             :                                 num_blocks_required,
    1552                 :             :                                 method == BACK_UP_FILE_INCREMENTALLY ? relative_block_numbers : NULL,
    1553                 :             :                                 truncation_block_length);
    1554                 :             : 
    1555   [ +  +  +  - ]:      393053 :             if (sent || sizeonly)
    1556                 :             :             {
    1557                 :             :                 /* Add size. */
    1558                 :      393053 :                 size += statbuf.st_size;
    1559                 :             : 
    1560                 :             :                 /* Pad to a multiple of the tar block size. */
    1561                 :      393053 :                 size += tarPaddingBytesRequired(statbuf.st_size);
    1562                 :             : 
    1563                 :             :                 /* Size of the header for the file. */
    1564                 :      393053 :                 size += TAR_BLOCK_SIZE;
    1565                 :             :             }
    1566                 :             :         }
    1567                 :             :         else
    1568         [ #  # ]:           0 :             ereport(WARNING,
    1569                 :             :                     (errmsg("skipping special file \"%s\"", pathbuf)));
    1570                 :             :     }
    1571                 :             : 
    1572         [ +  + ]:        6865 :     if (relative_block_numbers != NULL)
    1573                 :         484 :         pfree(relative_block_numbers);
    1574                 :             : 
    1575                 :        6865 :     FreeDir(dir);
    1576                 :        6865 :     return size;
    1577                 :             : }
    1578                 :             : 
    1579                 :             : /*
    1580                 :             :  * Given the member, write the TAR header & send the file.
    1581                 :             :  *
    1582                 :             :  * If 'missing_ok' is true, will not throw an error if the file is not found.
    1583                 :             :  *
    1584                 :             :  * If dboid is anything other than InvalidOid then any checksum failures
    1585                 :             :  * detected will get reported to the cumulative stats system.
    1586                 :             :  *
    1587                 :             :  * If the file is to be sent incrementally, then num_incremental_blocks
    1588                 :             :  * should be the number of blocks to be sent, and incremental_blocks
    1589                 :             :  * an array of block numbers relative to the start of the current segment.
    1590                 :             :  * If the whole file is to be sent, then incremental_blocks should be NULL,
    1591                 :             :  * and num_incremental_blocks can have any value, as it will be ignored.
    1592                 :             :  *
    1593                 :             :  * For non-relation files, the stat data of the opened file is used, not
    1594                 :             :  * 'statbuf'.
    1595                 :             :  *
    1596                 :             :  * Returns true if the file was successfully sent, false if 'missing_ok',
    1597                 :             :  * and the file did not exist.
    1598                 :             :  */
    1599                 :             : static bool
    1600                 :      194158 : sendFile(bbsink *sink, const char *readfilename, const char *tarfilename,
    1601                 :             :          const struct stat *statbuf, bool missing_ok, Oid dboid, Oid spcoid,
    1602                 :             :          RelFileNumber relfilenumber, unsigned segno,
    1603                 :             :          backup_manifest_info *manifest, unsigned num_incremental_blocks,
    1604                 :             :          BlockNumber *incremental_blocks, unsigned truncation_block_length)
    1605                 :             : {
    1606                 :             :     int         fd;
    1607                 :      194158 :     BlockNumber blkno = 0;
    1608                 :      194158 :     int         checksum_failures = 0;
    1609                 :             :     off_t       cnt;
    1610                 :      194158 :     pgoff_t     bytes_done = 0;
    1611                 :      194158 :     bool        verify_checksum = false;
    1612                 :             :     pg_checksum_context checksum_ctx;
    1613                 :      194158 :     int         ibindex = 0;
    1614                 :             :     struct stat filestat;
    1615                 :             : 
    1616         [ -  + ]:      194158 :     if (pg_checksum_init(&checksum_ctx, manifest->checksum_type) < 0)
    1617         [ #  # ]:           0 :         elog(ERROR, "could not initialize checksum of file \"%s\"",
    1618                 :             :              readfilename);
    1619                 :             : 
    1620                 :      194158 :     fd = OpenTransientFile(readfilename, O_RDONLY | PG_BINARY);
    1621         [ -  + ]:      194158 :     if (fd < 0)
    1622                 :             :     {
    1623   [ #  #  #  # ]:           0 :         if (errno == ENOENT && missing_ok)
    1624                 :           0 :             return false;
    1625         [ #  # ]:           0 :         ereport(ERROR,
    1626                 :             :                 (errcode_for_file_access(),
    1627                 :             :                  errmsg("could not open file \"%s\": %m", readfilename)));
    1628                 :             :     }
    1629                 :             : 
    1630                 :             :     /*
    1631                 :             :      * Non-relation files may be replaced by a rename(), making irrelevant the
    1632                 :             :      * caller's stat data.  Reuse fstat() on the opened file.
    1633                 :             :      */
    1634                 :      194158 :     filestat = *statbuf;
    1635                 :             : 
    1636   [ +  +  -  + ]:      194158 :     if (!RelFileNumberIsValid(relfilenumber) && fstat(fd, &filestat) != 0)
    1637         [ #  # ]:           0 :         ereport(ERROR,
    1638                 :             :                 (errcode_for_file_access(),
    1639                 :             :                  errmsg("could not stat file \"%s\": %m", readfilename)));
    1640                 :             : 
    1641                 :      194158 :     _tarWriteHeader(sink, tarfilename, NULL, &filestat, false);
    1642                 :             : 
    1643                 :             :     /*
    1644                 :             :      * Checksums are verified in multiples of BLCKSZ, so the buffer length
    1645                 :             :      * should be a multiple of the block size as well.
    1646                 :             :      */
    1647                 :             :     Assert((sink->bbs_buffer_length % BLCKSZ) == 0);
    1648                 :             : 
    1649                 :             :     /*
    1650                 :             :      * Verify checksums unless the client requested otherwise, but only for
    1651                 :             :      * relation files, and only while checksums have been continuously enabled
    1652                 :             :      * since the checkpoint this backup started from.  Checksums can still be
    1653                 :             :      * disabled while the backup runs, thus we check at each point where we
    1654                 :             :      * could be validating a checksum.
    1655                 :             :      */
    1656   [ +  +  +  +  :      383908 :     if (!noverify_checksums && RelFileNumberIsValid(relfilenumber) &&
                   +  + ]
    1657                 :      189751 :         backup_checksums_verifiable(sink->bbs_state->startptr))
    1658                 :      184011 :         verify_checksum = true;
    1659                 :             : 
    1660                 :             :     /*
    1661                 :             :      * If we're sending an incremental file, write the file header.
    1662                 :             :      */
    1663         [ +  + ]:      194157 :     if (incremental_blocks != NULL)
    1664                 :             :     {
    1665                 :        9367 :         unsigned    magic = INCREMENTAL_MAGIC;
    1666                 :        9367 :         size_t      header_bytes_done = 0;
    1667                 :             :         char        padding[BLCKSZ];
    1668                 :             :         size_t      paddinglen;
    1669                 :             : 
    1670                 :             :         /* Emit header data. */
    1671                 :        9367 :         push_to_sink(sink, &checksum_ctx, &header_bytes_done,
    1672                 :             :                      &magic, sizeof(magic));
    1673                 :        9367 :         push_to_sink(sink, &checksum_ctx, &header_bytes_done,
    1674                 :             :                      &num_incremental_blocks, sizeof(num_incremental_blocks));
    1675                 :        9367 :         push_to_sink(sink, &checksum_ctx, &header_bytes_done,
    1676                 :             :                      &truncation_block_length, sizeof(truncation_block_length));
    1677                 :        9367 :         push_to_sink(sink, &checksum_ctx, &header_bytes_done,
    1678                 :             :                      incremental_blocks,
    1679                 :             :                      sizeof(BlockNumber) * num_incremental_blocks);
    1680                 :             : 
    1681                 :             :         /*
    1682                 :             :          * Add padding to align header to a multiple of BLCKSZ, but only if
    1683                 :             :          * the incremental file has some blocks, and the alignment is actually
    1684                 :             :          * needed (i.e. header is not already a multiple of BLCKSZ). If there
    1685                 :             :          * are no blocks we don't want to make the file unnecessarily large,
    1686                 :             :          * as that might make some filesystem optimizations impossible.
    1687                 :             :          */
    1688   [ +  +  +  - ]:        9367 :         if ((num_incremental_blocks > 0) && (header_bytes_done % BLCKSZ != 0))
    1689                 :             :         {
    1690                 :          29 :             paddinglen = (BLCKSZ - (header_bytes_done % BLCKSZ));
    1691                 :             : 
    1692                 :          29 :             memset(padding, 0, paddinglen);
    1693                 :          29 :             bytes_done += paddinglen;
    1694                 :             : 
    1695                 :          29 :             push_to_sink(sink, &checksum_ctx, &header_bytes_done,
    1696                 :             :                          padding, paddinglen);
    1697                 :             :         }
    1698                 :             : 
    1699                 :             :         /* Flush out any data still in the buffer so it's again empty. */
    1700         [ +  - ]:        9367 :         if (header_bytes_done > 0)
    1701                 :             :         {
    1702                 :        9367 :             bbsink_archive_contents(sink, header_bytes_done);
    1703         [ -  + ]:        9367 :             if (pg_checksum_update(&checksum_ctx,
    1704                 :        9367 :                                    (uint8 *) sink->bbs_buffer,
    1705                 :             :                                    header_bytes_done) < 0)
    1706         [ #  # ]:           0 :                 elog(ERROR, "could not update checksum of base backup");
    1707                 :             :         }
    1708                 :             : 
    1709                 :             :         /* Update our notion of file position. */
    1710                 :        9367 :         bytes_done += sizeof(magic);
    1711                 :        9367 :         bytes_done += sizeof(num_incremental_blocks);
    1712                 :        9367 :         bytes_done += sizeof(truncation_block_length);
    1713                 :        9367 :         bytes_done += sizeof(BlockNumber) * num_incremental_blocks;
    1714                 :             :     }
    1715                 :             : 
    1716                 :             :     /*
    1717                 :             :      * Loop until we read the amount of data the caller told us to expect. The
    1718                 :             :      * file could be longer, if it was extended while we were sending it, but
    1719                 :             :      * for a base backup we can ignore such extended data. It will be restored
    1720                 :             :      * from WAL.
    1721                 :             :      */
    1722                 :             :     while (1)
    1723                 :             :     {
    1724                 :             :         /*
    1725                 :             :          * Determine whether we've read all the data that we need, and if not,
    1726                 :             :          * read some more.
    1727                 :             :          */
    1728         [ +  + ]:      417479 :         if (incremental_blocks == NULL)
    1729                 :             :         {
    1730                 :      408071 :             size_t      remaining = filestat.st_size - bytes_done;
    1731                 :             : 
    1732                 :             :             /*
    1733                 :             :              * If we've read the required number of bytes, then it's time to
    1734                 :             :              * stop.
    1735                 :             :              */
    1736         [ +  + ]:      408071 :             if (bytes_done >= filestat.st_size)
    1737                 :      184790 :                 break;
    1738                 :             : 
    1739                 :             :             /*
    1740                 :             :              * Read as many bytes as will fit in the buffer, or however many
    1741                 :             :              * are left to read, whichever is less.
    1742                 :             :              */
    1743                 :      223281 :             cnt = read_file_data_into_buffer(sink, readfilename, fd,
    1744                 :             :                                              bytes_done, remaining,
    1745                 :      223281 :                                              blkno + segno * RELSEG_SIZE,
    1746                 :             :                                              verify_checksum,
    1747                 :             :                                              &checksum_failures);
    1748                 :             :         }
    1749                 :             :         else
    1750                 :             :         {
    1751                 :             :             BlockNumber relative_blkno;
    1752                 :             : 
    1753                 :             :             /*
    1754                 :             :              * If we've read all the blocks, then it's time to stop.
    1755                 :             :              */
    1756         [ +  + ]:        9408 :             if (ibindex >= num_incremental_blocks)
    1757                 :        9367 :                 break;
    1758                 :             : 
    1759                 :             :             /*
    1760                 :             :              * Read just one block, whichever one is the next that we're
    1761                 :             :              * supposed to include.
    1762                 :             :              */
    1763                 :          41 :             relative_blkno = incremental_blocks[ibindex++];
    1764                 :          41 :             cnt = read_file_data_into_buffer(sink, readfilename, fd,
    1765                 :          41 :                                              relative_blkno * BLCKSZ,
    1766                 :             :                                              BLCKSZ,
    1767                 :          41 :                                              relative_blkno + segno * RELSEG_SIZE,
    1768                 :             :                                              verify_checksum,
    1769                 :             :                                              &checksum_failures);
    1770                 :             : 
    1771                 :             :             /*
    1772                 :             :              * If we get a partial read, that must mean that the relation is
    1773                 :             :              * being truncated. Ultimately, it should be truncated to a
    1774                 :             :              * multiple of BLCKSZ, since this path should only be reached for
    1775                 :             :              * relation files, but we might transiently observe an
    1776                 :             :              * intermediate value.
    1777                 :             :              *
    1778                 :             :              * It should be fine to treat this just as if the entire block had
    1779                 :             :              * been truncated away - i.e. fill this and all later blocks with
    1780                 :             :              * zeroes. WAL replay will fix things up.
    1781                 :             :              */
    1782         [ -  + ]:          41 :             if (cnt < BLCKSZ)
    1783                 :           0 :                 break;
    1784                 :             :         }
    1785                 :             : 
    1786                 :             :         /*
    1787                 :             :          * If the amount of data we were able to read was not a multiple of
    1788                 :             :          * BLCKSZ, we cannot verify checksums, which are block-level.
    1789                 :             :          */
    1790   [ +  +  +  - ]:      435642 :         if (verify_checksum &&
    1791                 :      212320 :             backup_checksums_verifiable(sink->bbs_state->startptr) &&
    1792         [ -  + ]:      212320 :             (cnt % BLCKSZ != 0))
    1793                 :             :         {
    1794         [ #  # ]:           0 :             ereport(WARNING,
    1795                 :             :                     (errmsg("could not verify checksum in file \"%s\", block "
    1796                 :             :                             "%u: read buffer size %d and page size %d "
    1797                 :             :                             "differ",
    1798                 :             :                             readfilename, blkno, (int) cnt, BLCKSZ)));
    1799                 :           0 :             verify_checksum = false;
    1800                 :             :         }
    1801                 :             : 
    1802                 :             :         /*
    1803                 :             :          * If we hit end-of-file, a concurrent truncation must have occurred.
    1804                 :             :          * That's not an error condition, because WAL replay will fix things
    1805                 :             :          * up.
    1806                 :             :          */
    1807         [ -  + ]:      223322 :         if (cnt == 0)
    1808                 :           0 :             break;
    1809                 :             : 
    1810                 :             :         /* Update block number and # of bytes done for next loop iteration. */
    1811                 :      223322 :         blkno += cnt / BLCKSZ;
    1812                 :      223322 :         bytes_done += cnt;
    1813                 :             : 
    1814                 :             :         /*
    1815                 :             :          * Make sure incremental files with block data are properly aligned
    1816                 :             :          * (header is a multiple of BLCKSZ, blocks are BLCKSZ too).
    1817                 :             :          */
    1818                 :             :         Assert(!((incremental_blocks != NULL && num_incremental_blocks > 0) &&
    1819                 :             :                  (bytes_done % BLCKSZ != 0)));
    1820                 :             : 
    1821                 :             :         /* Archive the data we just read. */
    1822                 :      223322 :         bbsink_archive_contents(sink, cnt);
    1823                 :             : 
    1824                 :             :         /* Also feed it to the checksum machinery. */
    1825         [ -  + ]:      223322 :         if (pg_checksum_update(&checksum_ctx,
    1826                 :      223322 :                                (uint8 *) sink->bbs_buffer, cnt) < 0)
    1827         [ #  # ]:           0 :             elog(ERROR, "could not update checksum of base backup");
    1828                 :             :     }
    1829                 :             : 
    1830                 :             :     /* If the file was truncated while we were sending it, pad it with zeros */
    1831         [ -  + ]:      194157 :     while (bytes_done < filestat.st_size)
    1832                 :             :     {
    1833                 :           0 :         size_t      remaining = filestat.st_size - bytes_done;
    1834                 :           0 :         size_t      nbytes = Min(sink->bbs_buffer_length, remaining);
    1835                 :             : 
    1836   [ #  #  #  #  :           0 :         MemSet(sink->bbs_buffer, 0, nbytes);
          #  #  #  #  #  
                      # ]
    1837         [ #  # ]:           0 :         if (pg_checksum_update(&checksum_ctx,
    1838                 :           0 :                                (uint8 *) sink->bbs_buffer,
    1839                 :             :                                nbytes) < 0)
    1840         [ #  # ]:           0 :             elog(ERROR, "could not update checksum of base backup");
    1841                 :           0 :         bbsink_archive_contents(sink, nbytes);
    1842                 :           0 :         bytes_done += nbytes;
    1843                 :             :     }
    1844                 :             : 
    1845                 :             :     /*
    1846                 :             :      * Pad to a block boundary, per tar format requirements. (This small piece
    1847                 :             :      * of data is probably not worth throttling, and is not checksummed
    1848                 :             :      * because it's not actually part of the file.)
    1849                 :             :      */
    1850                 :      194157 :     _tarWritePadding(sink, bytes_done);
    1851                 :             : 
    1852                 :      194157 :     CloseTransientFile(fd);
    1853                 :             : 
    1854         [ +  + ]:      194157 :     if (checksum_failures > 0)
    1855                 :             :     {
    1856         [ +  - ]:           4 :         ereport(WARNING,
    1857                 :             :                 (errmsg_plural("file \"%s\" has a total of %d checksum verification failure",
    1858                 :             :                                "file \"%s\" has a total of %d checksum verification failures",
    1859                 :             :                                checksum_failures,
    1860                 :             :                                readfilename, checksum_failures)));
    1861                 :             : 
    1862                 :           4 :         pgstat_prepare_report_checksum_failure(dboid);
    1863                 :           4 :         pgstat_report_checksum_failures_in_db(dboid, checksum_failures);
    1864                 :             :     }
    1865                 :             : 
    1866                 :      194157 :     total_checksum_failures += checksum_failures;
    1867                 :             : 
    1868                 :      194157 :     AddFileToBackupManifest(manifest, spcoid, tarfilename, filestat.st_size,
    1869                 :      194157 :                             (pg_time_t) filestat.st_mtime, &checksum_ctx);
    1870                 :             : 
    1871                 :      194157 :     return true;
    1872                 :             : }
    1873                 :             : 
    1874                 :             : /*
    1875                 :             :  * Read some more data from the file into the bbsink's buffer, verifying
    1876                 :             :  * checksums as required.
    1877                 :             :  *
    1878                 :             :  * 'offset' is the file offset from which we should begin to read, and
    1879                 :             :  * 'length' is the amount of data that should be read. The actual amount
    1880                 :             :  * of data read will be less than the requested amount if the bbsink's
    1881                 :             :  * buffer isn't big enough to hold it all, or if the underlying file has
    1882                 :             :  * been truncated. The return value is the number of bytes actually read.
    1883                 :             :  *
    1884                 :             :  * 'blkno' is the block number of the first page in the bbsink's buffer
    1885                 :             :  * relative to the start of the relation.
    1886                 :             :  *
    1887                 :             :  * 'verify_checksum' determines if the user has asked to verify checksums, but
    1888                 :             :  * since data checksums can be disabled, or become disabled, we need to check
    1889                 :             :  * state before verifying individual pages.  If we do this, we'll update
    1890                 :             :  * *checksum_failures and issue warnings as appropriate.
    1891                 :             :  */
    1892                 :             : static off_t
    1893                 :      223322 : read_file_data_into_buffer(bbsink *sink, const char *readfilename, int fd,
    1894                 :             :                            off_t offset, size_t length, BlockNumber blkno,
    1895                 :             :                            bool verify_checksum, int *checksum_failures)
    1896                 :             : {
    1897                 :             :     off_t       cnt;
    1898                 :             :     int         i;
    1899                 :             :     char       *page;
    1900                 :             : 
    1901                 :             :     /* Try to read some more data. */
    1902                 :      223322 :     cnt = basebackup_read_file(fd, sink->bbs_buffer,
    1903                 :      223322 :                                Min(sink->bbs_buffer_length, length),
    1904                 :             :                                offset, readfilename, true);
    1905                 :             : 
    1906                 :             :     /* Can't verify checksums if read length is not a multiple of BLCKSZ. */
    1907   [ +  +  -  + ]:      223322 :     if (!verify_checksum || (cnt % BLCKSZ) != 0)
    1908                 :       11002 :         return cnt;
    1909                 :             : 
    1910                 :             :     /* Verify checksum for each block. */
    1911         [ +  + ]:      741346 :     for (i = 0; i < cnt / BLCKSZ; i++)
    1912                 :             :     {
    1913                 :             :         int         reread_cnt;
    1914                 :             :         uint16      expected_checksum;
    1915                 :             : 
    1916                 :             :         /*
    1917                 :             :          * The data checksum state can change at any point, so we need to
    1918                 :             :          * re-check before each page.
    1919                 :             :          */
    1920         [ -  + ]:      529026 :         if (!backup_checksums_verifiable(sink->bbs_state->startptr))
    1921                 :           0 :             return cnt;
    1922                 :             : 
    1923                 :      529026 :         page = sink->bbs_buffer + BLCKSZ * i;
    1924                 :             : 
    1925                 :             :         /* If the page is OK, go on to the next one. */
    1926         [ +  + ]:      529026 :         if (verify_page_checksum(page, sink->bbs_state->startptr, blkno + i,
    1927                 :             :                                  &expected_checksum))
    1928                 :      529012 :             continue;
    1929                 :             : 
    1930                 :             :         /*
    1931                 :             :          * Retry the block on the first failure.  It's possible that we read
    1932                 :             :          * the first 4K page of the block just before postgres updated the
    1933                 :             :          * entire block so it ends up looking torn to us. If, before we retry
    1934                 :             :          * the read, the concurrent write of the block finishes, the page LSN
    1935                 :             :          * will be updated and we'll realize that we should ignore this block.
    1936                 :             :          *
    1937                 :             :          * There's no guarantee that this will actually happen, though: the
    1938                 :             :          * torn write could take an arbitrarily long time to complete.
    1939                 :             :          * Retrying multiple times wouldn't fix this problem, either, though
    1940                 :             :          * it would reduce the chances of it happening in practice. The only
    1941                 :             :          * real fix here seems to be to have some kind of interlock that
    1942                 :             :          * allows us to wait until we can be certain that no write to the
    1943                 :             :          * block is in progress. Since we don't have any such thing right now,
    1944                 :             :          * we just do this and hope for the best.
    1945                 :             :          *
    1946                 :             :          * The data checksum state may also have changed concurrently so check
    1947                 :             :          * again.
    1948                 :             :          */
    1949         [ -  + ]:          14 :         if (!backup_checksums_verifiable(sink->bbs_state->startptr))
    1950                 :           0 :             return cnt;
    1951                 :          14 :         reread_cnt =
    1952                 :          14 :             basebackup_read_file(fd, sink->bbs_buffer + BLCKSZ * i,
    1953                 :          14 :                                  BLCKSZ, offset + BLCKSZ * i,
    1954                 :             :                                  readfilename, false);
    1955         [ -  + ]:          14 :         if (reread_cnt == 0)
    1956                 :             :         {
    1957                 :             :             /*
    1958                 :             :              * If we hit end-of-file, a concurrent truncation must have
    1959                 :             :              * occurred, so reduce cnt to reflect only the blocks already
    1960                 :             :              * processed and break out of this loop.
    1961                 :             :              */
    1962                 :           0 :             cnt = BLCKSZ * i;
    1963                 :           0 :             break;
    1964                 :             :         }
    1965                 :             : 
    1966                 :             :         /* If the page now looks OK, go on to the next one. */
    1967         [ -  + ]:          14 :         if (verify_page_checksum(page, sink->bbs_state->startptr, blkno + i,
    1968                 :             :                                  &expected_checksum))
    1969                 :           0 :             continue;
    1970                 :             : 
    1971                 :             :         /* Handle checksum failure. */
    1972                 :          14 :         (*checksum_failures)++;
    1973         [ +  + ]:          14 :         if (*checksum_failures <= 5)
    1974         [ +  - ]:          12 :             ereport(WARNING,
    1975                 :             :                     (errmsg("checksum verification failed in "
    1976                 :             :                             "file \"%s\", block %u: calculated "
    1977                 :             :                             "%X but expected %X",
    1978                 :             :                             readfilename, blkno + i, expected_checksum,
    1979                 :             :                             ((PageHeader) page)->pd_checksum)));
    1980         [ +  + ]:          14 :         if (*checksum_failures == 5)
    1981         [ +  - ]:           2 :             ereport(WARNING,
    1982                 :             :                     (errmsg("further checksum verification "
    1983                 :             :                             "failures in file \"%s\" will not "
    1984                 :             :                             "be reported", readfilename)));
    1985                 :             :     }
    1986                 :             : 
    1987                 :      212320 :     return cnt;
    1988                 :             : }
    1989                 :             : 
    1990                 :             : /*
    1991                 :             :  * Push data into a bbsink.
    1992                 :             :  *
    1993                 :             :  * It's better, when possible, to read data directly into the bbsink's buffer,
    1994                 :             :  * rather than using this function to copy it into the buffer; this function is
    1995                 :             :  * for cases where that approach is not practical.
    1996                 :             :  *
    1997                 :             :  * bytes_done should point to a count of the number of bytes that are
    1998                 :             :  * currently used in the bbsink's buffer. Upon return, the bytes identified by
    1999                 :             :  * data and length will have been copied into the bbsink's buffer, flushing
    2000                 :             :  * as required, and *bytes_done will have been updated accordingly. If the
    2001                 :             :  * buffer was flushed, the previous contents will also have been fed to
    2002                 :             :  * checksum_ctx.
    2003                 :             :  *
    2004                 :             :  * Note that after one or more calls to this function it is the caller's
    2005                 :             :  * responsibility to perform any required final flush.
    2006                 :             :  */
    2007                 :             : static void
    2008                 :       37497 : push_to_sink(bbsink *sink, pg_checksum_context *checksum_ctx,
    2009                 :             :              size_t *bytes_done, void *data, size_t length)
    2010                 :             : {
    2011         [ +  + ]:       37497 :     while (length > 0)
    2012                 :             :     {
    2013                 :             :         size_t      bytes_to_copy;
    2014                 :             : 
    2015                 :             :         /*
    2016                 :             :          * We use < here rather than <= so that if the data exactly fills the
    2017                 :             :          * remaining buffer space, we trigger a flush now.
    2018                 :             :          */
    2019         [ +  - ]:       28159 :         if (length < sink->bbs_buffer_length - *bytes_done)
    2020                 :             :         {
    2021                 :             :             /* Append remaining data to buffer. */
    2022                 :       28159 :             memcpy(sink->bbs_buffer + *bytes_done, data, length);
    2023                 :       28159 :             *bytes_done += length;
    2024                 :       28159 :             return;
    2025                 :             :         }
    2026                 :             : 
    2027                 :             :         /* Copy until buffer is full and flush it. */
    2028                 :           0 :         bytes_to_copy = sink->bbs_buffer_length - *bytes_done;
    2029                 :           0 :         memcpy(sink->bbs_buffer + *bytes_done, data, bytes_to_copy);
    2030                 :           0 :         data = ((char *) data) + bytes_to_copy;
    2031                 :           0 :         length -= bytes_to_copy;
    2032                 :           0 :         bbsink_archive_contents(sink, sink->bbs_buffer_length);
    2033         [ #  # ]:           0 :         if (pg_checksum_update(checksum_ctx, (uint8 *) sink->bbs_buffer,
    2034                 :             :                                sink->bbs_buffer_length) < 0)
    2035         [ #  # ]:           0 :             elog(ERROR, "could not update checksum");
    2036                 :           0 :         *bytes_done = 0;
    2037                 :             :     }
    2038                 :             : }
    2039                 :             : 
    2040                 :             : /*
    2041                 :             :  * Check whether data checksums can be verified for a backup started at
    2042                 :             :  * start_lsn.
    2043                 :             :  *
    2044                 :             :  * Checksums are verified only while they have been continuously enabled
    2045                 :             :  * since the checkpoint the backup started from: the state must be "on" and
    2046                 :             :  * the last state change must predate the backup start.  Such a checkpoint
    2047                 :             :  * guarantees that every page flushed before it has a checksum written.  Any
    2048                 :             :  * later state change ends verification for the rest of the backup: pages
    2049                 :             :  * written while checksums were off can lack checksums yet keep LSNs older
    2050                 :             :  * than the backup start, and re-enabling completes before the rewritten
    2051                 :             :  * pages are flushed, so observing the "on" state again is not enough to
    2052                 :             :  * resume.
    2053                 :             :  */
    2054                 :             : static bool
    2055                 :     1459114 : backup_checksums_verifiable(XLogRecPtr start_lsn)
    2056                 :             : {
    2057   [ +  +  +  - ]:     2912488 :     return DataChecksumsNeedVerify() &&
    2058                 :     1453374 :         GetLastChecksumChangeRecPtr() <= start_lsn;
    2059                 :             : }
    2060                 :             : 
    2061                 :             : /*
    2062                 :             :  * Try to verify the checksum for the provided page, if it seems appropriate
    2063                 :             :  * to do so.
    2064                 :             :  *
    2065                 :             :  * Returns true if verification succeeds or if we decide not to check it,
    2066                 :             :  * and false if verification fails. When return false, it also sets
    2067                 :             :  * *expected_checksum to the computed value.
    2068                 :             :  */
    2069                 :             : static bool
    2070                 :      529040 : verify_page_checksum(Page page, XLogRecPtr start_lsn, BlockNumber blkno,
    2071                 :             :                      uint16 *expected_checksum)
    2072                 :             : {
    2073                 :             :     PageHeader  phdr;
    2074                 :             :     uint16      checksum;
    2075                 :             : 
    2076                 :             :     /*
    2077                 :             :      * Only check pages which have not been modified since the start of the
    2078                 :             :      * base backup. Otherwise, they might have been written only halfway and
    2079                 :             :      * the checksum would not be valid.  However, replaying WAL would
    2080                 :             :      * reinstate the correct page in this case. We also skip completely new
    2081                 :             :      * pages, since they don't have a checksum yet.
    2082                 :             :      */
    2083   [ +  +  +  + ]:      529040 :     if (PageIsNew(page) || PageGetLSN(page) >= start_lsn)
    2084                 :        1037 :         return true;
    2085                 :             : 
    2086         [ -  + ]:      528003 :     if (!backup_checksums_verifiable(start_lsn))
    2087                 :           0 :         return true;
    2088                 :             : 
    2089                 :             :     /* Perform the actual checksum calculation. */
    2090                 :      528003 :     checksum = pg_checksum_page(page, blkno);
    2091                 :             : 
    2092                 :             : #ifdef USE_INJECTION_POINTS
    2093                 :             :     {
    2094                 :             :         /*
    2095                 :             :          * Make it possible to test checksum verification failure without
    2096                 :             :          * having to destroy data on disk.  There is cap on how many times we
    2097                 :             :          * want to cause verification failure to make tests more interesting
    2098                 :             :          * and less log intensive.  This makes it easy to test pg_basebackup
    2099                 :             :          * with the command_checks_all test function.
    2100                 :             :          */
    2101                 :             :         static int  hit = 0;
    2102                 :             : 
    2103         [ -  + ]:      528003 :         if (IS_INJECTION_POINT_ATTACHED("basebackup-fail-checksum-verification"))
    2104                 :             :         {
    2105         [ #  # ]:           0 :             if (hit++ < 5)
    2106                 :             :             {
    2107                 :           0 :                 checksum = 0;
    2108                 :           0 :                 INJECTION_POINT_CACHED("basebackup-fail-checksum-verification",
    2109                 :             :                                        NULL);
    2110                 :             :             }
    2111                 :             :         }
    2112                 :             :     }
    2113                 :             : #endif
    2114                 :             : 
    2115                 :             :     /* See whether it matches the value from the page. */
    2116                 :      528003 :     phdr = (PageHeader) page;
    2117         [ +  + ]:      528003 :     if (phdr->pd_checksum == checksum)
    2118                 :      527975 :         return true;
    2119                 :          28 :     *expected_checksum = checksum;
    2120                 :          28 :     return false;
    2121                 :             : }
    2122                 :             : 
    2123                 :             : static int64
    2124                 :      205133 : _tarWriteHeader(bbsink *sink, const char *filename, const char *linktarget,
    2125                 :             :                 struct stat *statbuf, bool sizeonly)
    2126                 :             : {
    2127                 :             :     enum tarError rc;
    2128                 :             : 
    2129         [ +  + ]:      205133 :     if (!sizeonly)
    2130                 :             :     {
    2131                 :             :         /*
    2132                 :             :          * As of this writing, the smallest supported block size is 1kB, which
    2133                 :             :          * is twice TAR_BLOCK_SIZE. Since the buffer size is required to be a
    2134                 :             :          * multiple of BLCKSZ, it should be safe to assume that the buffer is
    2135                 :             :          * large enough to fit an entire tar block. We double-check by means
    2136                 :             :          * of these assertions.
    2137                 :             :          */
    2138                 :             :         StaticAssertDecl(TAR_BLOCK_SIZE <= BLCKSZ,
    2139                 :             :                          "BLCKSZ too small for tar block");
    2140                 :             :         Assert(sink->bbs_buffer_length >= TAR_BLOCK_SIZE);
    2141                 :             : 
    2142                 :      199835 :         rc = tarCreateHeader(sink->bbs_buffer, filename, linktarget,
    2143                 :             :                              statbuf->st_size, statbuf->st_mode,
    2144                 :             :                              statbuf->st_uid, statbuf->st_gid,
    2145                 :             :                              statbuf->st_mtime);
    2146                 :             : 
    2147   [ +  +  -  - ]:      199835 :         switch (rc)
    2148                 :             :         {
    2149                 :      199834 :             case TAR_OK:
    2150                 :      199834 :                 break;
    2151                 :           1 :             case TAR_NAME_TOO_LONG:
    2152         [ +  - ]:           1 :                 ereport(ERROR,
    2153                 :             :                         (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    2154                 :             :                          errmsg("file name too long for tar format: \"%s\"",
    2155                 :             :                                 filename)));
    2156                 :             :                 break;
    2157                 :           0 :             case TAR_SYMLINK_TOO_LONG:
    2158         [ #  # ]:           0 :                 ereport(ERROR,
    2159                 :             :                         (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    2160                 :             :                          errmsg("symbolic link target too long for tar format: "
    2161                 :             :                                 "file name \"%s\", target \"%s\"",
    2162                 :             :                                 filename, linktarget)));
    2163                 :             :                 break;
    2164                 :           0 :             default:
    2165         [ #  # ]:           0 :                 elog(ERROR, "unrecognized tar error: %d", rc);
    2166                 :             :         }
    2167                 :             : 
    2168                 :      199834 :         bbsink_archive_contents(sink, TAR_BLOCK_SIZE);
    2169                 :             :     }
    2170                 :             : 
    2171                 :      205131 :     return TAR_BLOCK_SIZE;
    2172                 :             : }
    2173                 :             : 
    2174                 :             : /*
    2175                 :             :  * Pad with zero bytes out to a multiple of TAR_BLOCK_SIZE.
    2176                 :             :  */
    2177                 :             : static void
    2178                 :      194596 : _tarWritePadding(bbsink *sink, int len)
    2179                 :             : {
    2180                 :      194596 :     int         pad = tarPaddingBytesRequired(len);
    2181                 :             : 
    2182                 :             :     /*
    2183                 :             :      * As in _tarWriteHeader, it should be safe to assume that the buffer is
    2184                 :             :      * large enough that we don't need to do this in multiple chunks.
    2185                 :             :      */
    2186                 :             :     Assert(sink->bbs_buffer_length >= TAR_BLOCK_SIZE);
    2187                 :             :     Assert(pad <= TAR_BLOCK_SIZE);
    2188                 :             : 
    2189         [ +  + ]:      194596 :     if (pad > 0)
    2190                 :             :     {
    2191   [ +  -  +  +  :       37589 :         MemSet(sink->bbs_buffer, 0, pad);
          +  -  +  -  +  
                      + ]
    2192                 :       12387 :         bbsink_archive_contents(sink, pad);
    2193                 :             :     }
    2194                 :      194596 : }
    2195                 :             : 
    2196                 :             : /*
    2197                 :             :  * If the entry in statbuf is a link, then adjust statbuf to make it look like a
    2198                 :             :  * directory, so that it will be written that way.
    2199                 :             :  */
    2200                 :             : static void
    2201                 :        3160 : convert_link_to_directory(const char *pathbuf, struct stat *statbuf)
    2202                 :             : {
    2203                 :             :     /* If symlink, write it as a directory anyway */
    2204         [ +  + ]:        3160 :     if (S_ISLNK(statbuf->st_mode))
    2205                 :          66 :         statbuf->st_mode = S_IFDIR | pg_dir_create_mode;
    2206                 :        3160 : }
    2207                 :             : 
    2208                 :             : /*
    2209                 :             :  * Read some data from a file, setting a wait event and reporting any error
    2210                 :             :  * encountered.
    2211                 :             :  *
    2212                 :             :  * If partial_read_ok is false, also report an error if the number of bytes
    2213                 :             :  * read is not equal to the number of bytes requested.
    2214                 :             :  *
    2215                 :             :  * Returns the number of bytes read.
    2216                 :             :  */
    2217                 :             : static ssize_t
    2218                 :      231016 : basebackup_read_file(int fd, char *buf, size_t nbytes, off_t offset,
    2219                 :             :                      const char *filename, bool partial_read_ok)
    2220                 :             : {
    2221                 :             :     ssize_t     rc;
    2222                 :             : 
    2223                 :      231016 :     pgstat_report_wait_start(WAIT_EVENT_BASEBACKUP_READ);
    2224                 :      231016 :     rc = pg_pread(fd, buf, nbytes, offset);
    2225                 :      231016 :     pgstat_report_wait_end();
    2226                 :             : 
    2227         [ -  + ]:      231016 :     if (rc < 0)
    2228         [ #  # ]:           0 :         ereport(ERROR,
    2229                 :             :                 (errcode_for_file_access(),
    2230                 :             :                  errmsg("could not read file \"%s\": %m", filename)));
    2231   [ +  +  +  -  :      231016 :     if (!partial_read_ok && rc > 0 && rc != nbytes)
                   -  + ]
    2232         [ #  # ]:           0 :         ereport(ERROR,
    2233                 :             :                 (errcode_for_file_access(),
    2234                 :             :                  errmsg("could not read file \"%s\": read %zd of %zu",
    2235                 :             :                         filename, rc, nbytes)));
    2236                 :             : 
    2237                 :      231016 :     return rc;
    2238                 :             : }
        

Generated by: LCOV version 2.0-1