LCOV - code coverage report
Current view: top level - src/bin/pg_waldump - xlogreader.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 70.8 % 737 522
Test Date: 2026-08-05 22:15:48 Functions: 89.3 % 28 25
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 62.3 % 414 258

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  *
       3                 :             :  * xlogreader.c
       4                 :             :  *      Generic XLog reading facility
       5                 :             :  *
       6                 :             :  * Portions Copyright (c) 2013-2026, PostgreSQL Global Development Group
       7                 :             :  *
       8                 :             :  * IDENTIFICATION
       9                 :             :  *      src/backend/access/transam/xlogreader.c
      10                 :             :  *
      11                 :             :  * NOTES
      12                 :             :  *      See xlogreader.h for more notes on this facility.
      13                 :             :  *
      14                 :             :  *      This file is compiled as both front-end and backend code, so it
      15                 :             :  *      may not use ereport, server-defined static variables, etc.
      16                 :             :  *-------------------------------------------------------------------------
      17                 :             :  */
      18                 :             : #include "postgres.h"
      19                 :             : 
      20                 :             : #include <unistd.h>
      21                 :             : #ifdef USE_LZ4
      22                 :             : #include <lz4.h>
      23                 :             : #endif
      24                 :             : #ifdef USE_ZSTD
      25                 :             : #include <zstd.h>
      26                 :             : #endif
      27                 :             : 
      28                 :             : #include "access/transam.h"
      29                 :             : #include "access/xlog_internal.h"
      30                 :             : #include "access/xlogreader.h"
      31                 :             : #include "access/xlogrecord.h"
      32                 :             : #include "catalog/pg_control.h"
      33                 :             : #include "common/pg_lzcompress.h"
      34                 :             : #include "replication/origin.h"
      35                 :             : 
      36                 :             : #ifndef FRONTEND
      37                 :             : #include "pgstat.h"
      38                 :             : #include "storage/bufmgr.h"
      39                 :             : #include "utils/wait_event.h"
      40                 :             : #else
      41                 :             : #include "common/logging.h"
      42                 :             : #endif
      43                 :             : 
      44                 :             : static void report_invalid_record(XLogReaderState *state, const char *fmt, ...)
      45                 :             :             pg_attribute_printf(2, 3);
      46                 :             : static void allocate_recordbuf(XLogReaderState *state, uint32 reclength);
      47                 :             : static int  ReadPageInternal(XLogReaderState *state, XLogRecPtr pageptr,
      48                 :             :                              int reqLen);
      49                 :             : static void XLogReaderInvalReadState(XLogReaderState *state);
      50                 :             : static XLogPageReadResult XLogDecodeNextRecord(XLogReaderState *state, bool nonblocking);
      51                 :             : static bool ValidXLogRecordHeader(XLogReaderState *state, XLogRecPtr RecPtr,
      52                 :             :                                   XLogRecPtr PrevRecPtr, XLogRecord *record, bool randAccess);
      53                 :             : static bool ValidXLogRecord(XLogReaderState *state, XLogRecord *record,
      54                 :             :                             XLogRecPtr recptr);
      55                 :             : static void ResetDecoder(XLogReaderState *state);
      56                 :             : static void WALOpenSegmentInit(WALOpenSegment *seg, WALSegmentContext *segcxt,
      57                 :             :                                int segsize, const char *waldir);
      58                 :             : 
      59                 :             : /* size of the buffer allocated for error message. */
      60                 :             : #define MAX_ERRORMSG_LEN 1000
      61                 :             : 
      62                 :             : /*
      63                 :             :  * Default size; large enough that typical users of XLogReader won't often need
      64                 :             :  * to use the 'oversized' memory allocation code path.
      65                 :             :  */
      66                 :             : #define DEFAULT_DECODE_BUFFER_SIZE (64 * 1024)
      67                 :             : 
      68                 :             : /*
      69                 :             :  * Construct a string in state->errormsg_buf explaining what's wrong with
      70                 :             :  * the current record being read.
      71                 :             :  */
      72                 :             : static void
      73                 :           7 : report_invalid_record(XLogReaderState *state, const char *fmt, ...)
      74                 :             : {
      75                 :             :     va_list     args;
      76                 :             : 
      77                 :           7 :     fmt = _(fmt);
      78                 :             : 
      79                 :           7 :     va_start(args, fmt);
      80                 :           7 :     vsnprintf(state->errormsg_buf, MAX_ERRORMSG_LEN, fmt, args);
      81                 :           7 :     va_end(args);
      82                 :             : 
      83                 :           7 :     state->errormsg_deferred = true;
      84                 :           7 : }
      85                 :             : 
      86                 :             : /*
      87                 :             :  * Set the size of the decoding buffer.  A pointer to a caller supplied memory
      88                 :             :  * region may also be passed in, in which case non-oversized records will be
      89                 :             :  * decoded there.
      90                 :             :  */
      91                 :             : void
      92                 :           0 : XLogReaderSetDecodeBuffer(XLogReaderState *state, void *buffer, size_t size)
      93                 :             : {
      94                 :             :     Assert(state->decode_buffer == NULL);
      95                 :             : 
      96                 :           0 :     state->decode_buffer = buffer;
      97                 :           0 :     state->decode_buffer_size = size;
      98                 :           0 :     state->decode_buffer_tail = buffer;
      99                 :           0 :     state->decode_buffer_head = buffer;
     100                 :           0 : }
     101                 :             : 
     102                 :             : /*
     103                 :             :  * Allocate and initialize a new XLogReader.
     104                 :             :  *
     105                 :             :  * Returns NULL if the xlogreader couldn't be allocated.
     106                 :             :  */
     107                 :             : XLogReaderState *
     108                 :         120 : XLogReaderAllocate(int wal_segment_size, const char *waldir,
     109                 :             :                    XLogReaderRoutine *routine, void *private_data)
     110                 :             : {
     111                 :             :     XLogReaderState *state;
     112                 :             : 
     113                 :             :     state = (XLogReaderState *)
     114                 :         120 :         palloc_extended(sizeof(XLogReaderState),
     115                 :             :                         MCXT_ALLOC_NO_OOM | MCXT_ALLOC_ZERO);
     116         [ -  + ]:         120 :     if (!state)
     117                 :           0 :         return NULL;
     118                 :             : 
     119                 :             :     /* initialize caller-provided support functions */
     120                 :         120 :     state->routine = *routine;
     121                 :             : 
     122                 :             :     /*
     123                 :             :      * Permanently allocate readBuf.  We do it this way, rather than just
     124                 :             :      * making a static array, for two reasons: (1) no need to waste the
     125                 :             :      * storage in most instantiations of the backend; (2) a static char array
     126                 :             :      * isn't guaranteed to have any particular alignment, whereas
     127                 :             :      * palloc_extended() will provide MAXALIGN'd storage.
     128                 :             :      */
     129                 :         120 :     state->readBuf = (char *) palloc_extended(XLOG_BLCKSZ,
     130                 :             :                                               MCXT_ALLOC_NO_OOM);
     131         [ -  + ]:         120 :     if (!state->readBuf)
     132                 :             :     {
     133                 :           0 :         pfree(state);
     134                 :           0 :         return NULL;
     135                 :             :     }
     136                 :             : 
     137                 :             :     /* Initialize segment info. */
     138                 :         120 :     WALOpenSegmentInit(&state->seg, &state->segcxt, wal_segment_size,
     139                 :             :                        waldir);
     140                 :             : 
     141                 :             :     /* system_identifier initialized to zeroes above */
     142                 :         120 :     state->private_data = private_data;
     143                 :             :     /* ReadRecPtr, EndRecPtr and readLen initialized to zeroes above */
     144                 :         120 :     state->errormsg_buf = palloc_extended(MAX_ERRORMSG_LEN + 1,
     145                 :             :                                           MCXT_ALLOC_NO_OOM);
     146         [ -  + ]:         120 :     if (!state->errormsg_buf)
     147                 :             :     {
     148                 :           0 :         pfree(state->readBuf);
     149                 :           0 :         pfree(state);
     150                 :           0 :         return NULL;
     151                 :             :     }
     152                 :         120 :     state->errormsg_buf[0] = '\0';
     153                 :             : 
     154                 :             :     /*
     155                 :             :      * Allocate an initial readRecordBuf of minimal size, which can later be
     156                 :             :      * enlarged if necessary.
     157                 :             :      */
     158                 :         120 :     allocate_recordbuf(state, 0);
     159                 :         120 :     return state;
     160                 :             : }
     161                 :             : 
     162                 :             : void
     163                 :         113 : XLogReaderFree(XLogReaderState *state)
     164                 :             : {
     165         [ +  + ]:         113 :     if (state->seg.ws_file != -1)
     166                 :          65 :         state->routine.segment_close(state);
     167                 :             : 
     168   [ +  -  +  - ]:         113 :     if (state->decode_buffer && state->free_decode_buffer)
     169                 :         113 :         pfree(state->decode_buffer);
     170                 :             : 
     171                 :         113 :     pfree(state->errormsg_buf);
     172         [ +  - ]:         113 :     if (state->readRecordBuf)
     173                 :         113 :         pfree(state->readRecordBuf);
     174                 :         113 :     pfree(state->readBuf);
     175                 :         113 :     pfree(state);
     176                 :         113 : }
     177                 :             : 
     178                 :             : /*
     179                 :             :  * Allocate readRecordBuf to fit a record of at least the given length.
     180                 :             :  *
     181                 :             :  * readRecordBufSize is set to the new buffer size.
     182                 :             :  *
     183                 :             :  * To avoid useless small increases, round its size to a multiple of
     184                 :             :  * XLOG_BLCKSZ, and make sure it's at least 5*Max(BLCKSZ, XLOG_BLCKSZ) to start
     185                 :             :  * with.  (That is enough for all "normal" records, but very large commit or
     186                 :             :  * abort records might need more space.)
     187                 :             :  *
     188                 :             :  * The caller must make sure that "reclength" is valid and within the
     189                 :             :  * XLogRecordMaxSize limit.
     190                 :             :  *
     191                 :             :  * Note: This routine should *never* be called for xl_tot_len until the header
     192                 :             :  * of the record has been fully validated.
     193                 :             :  */
     194                 :             : static void
     195                 :         173 : allocate_recordbuf(XLogReaderState *state, uint32 reclength)
     196                 :             : {
     197                 :             :     uint32      newSize;
     198                 :             : 
     199                 :             :     Assert(reclength <= XLogRecordMaxSize);
     200                 :             : 
     201                 :         173 :     newSize = TYPEALIGN(XLOG_BLCKSZ, reclength);
     202                 :         173 :     newSize = Max(newSize, 5 * Max(BLCKSZ, XLOG_BLCKSZ));
     203                 :             : 
     204         [ +  + ]:         173 :     if (state->readRecordBuf)
     205                 :          53 :         pfree(state->readRecordBuf);
     206                 :         173 :     state->readRecordBuf = (char *) palloc(newSize);
     207                 :         173 :     state->readRecordBufSize = newSize;
     208                 :         173 : }
     209                 :             : 
     210                 :             : /*
     211                 :             :  * Initialize the passed segment structs.
     212                 :             :  */
     213                 :             : static void
     214                 :         120 : WALOpenSegmentInit(WALOpenSegment *seg, WALSegmentContext *segcxt,
     215                 :             :                    int segsize, const char *waldir)
     216                 :             : {
     217                 :         120 :     seg->ws_file = -1;
     218                 :         120 :     seg->ws_segno = 0;
     219                 :         120 :     seg->ws_tli = 0;
     220                 :             : 
     221                 :         120 :     segcxt->ws_segsize = segsize;
     222         [ +  - ]:         120 :     if (waldir)
     223                 :         120 :         snprintf(segcxt->ws_dir, MAXPGPATH, "%s", waldir);
     224                 :         120 : }
     225                 :             : 
     226                 :             : /*
     227                 :             :  * Begin reading WAL at 'RecPtr'.
     228                 :             :  *
     229                 :             :  * 'RecPtr' should point to the beginning of a valid WAL record.  Pointing at
     230                 :             :  * the beginning of a page is also OK, if there is a new record right after
     231                 :             :  * the page header, i.e. not a continuation.
     232                 :             :  *
     233                 :             :  * This does not make any attempt to read the WAL yet, and hence cannot fail.
     234                 :             :  * If the starting address is not correct, the first call to XLogReadRecord()
     235                 :             :  * will error out.
     236                 :             :  */
     237                 :             : void
     238                 :         238 : XLogBeginRead(XLogReaderState *state, XLogRecPtr RecPtr)
     239                 :             : {
     240                 :             :     Assert(XLogRecPtrIsValid(RecPtr));
     241                 :             : 
     242                 :         238 :     ResetDecoder(state);
     243                 :             : 
     244                 :             :     /* Begin at the passed-in record pointer. */
     245                 :         238 :     state->EndRecPtr = RecPtr;
     246                 :         238 :     state->NextRecPtr = RecPtr;
     247                 :         238 :     state->ReadRecPtr = InvalidXLogRecPtr;
     248                 :         238 :     state->DecodeRecPtr = InvalidXLogRecPtr;
     249                 :         238 : }
     250                 :             : 
     251                 :             : /*
     252                 :             :  * Release the last record that was returned by XLogNextRecord(), if any, to
     253                 :             :  * free up space.  Returns the LSN past the end of the record.
     254                 :             :  */
     255                 :             : XLogRecPtr
     256                 :     3144618 : XLogReleasePreviousRecord(XLogReaderState *state)
     257                 :             : {
     258                 :             :     DecodedXLogRecord *record;
     259                 :             :     XLogRecPtr  next_lsn;
     260                 :             : 
     261         [ +  + ]:     3144618 :     if (!state->record)
     262                 :     1572547 :         return InvalidXLogRecPtr;
     263                 :             : 
     264                 :             :     /*
     265                 :             :      * Remove it from the decoded record queue.  It must be the oldest item
     266                 :             :      * decoded, decode_queue_head.
     267                 :             :      */
     268                 :     1572071 :     record = state->record;
     269                 :     1572071 :     next_lsn = record->next_lsn;
     270                 :             :     Assert(record == state->decode_queue_head);
     271                 :     1572071 :     state->record = NULL;
     272                 :     1572071 :     state->decode_queue_head = record->next;
     273                 :             : 
     274                 :             :     /* It might also be the newest item decoded, decode_queue_tail. */
     275         [ +  - ]:     1572071 :     if (state->decode_queue_tail == record)
     276                 :     1572071 :         state->decode_queue_tail = NULL;
     277                 :             : 
     278                 :             :     /* Release the space. */
     279         [ +  + ]:     1572071 :     if (unlikely(record->oversized))
     280                 :             :     {
     281                 :             :         /* It's not in the decode buffer, so free it to release space. */
     282                 :          55 :         pfree(record);
     283                 :             :     }
     284                 :             :     else
     285                 :             :     {
     286                 :             :         /* It must be the head (oldest) record in the decode buffer. */
     287                 :             :         Assert(state->decode_buffer_head == (char *) record);
     288                 :             : 
     289                 :             :         /*
     290                 :             :          * We need to update head to point to the next record that is in the
     291                 :             :          * decode buffer, if any, being careful to skip oversized ones
     292                 :             :          * (they're not in the decode buffer).
     293                 :             :          */
     294                 :     1572016 :         record = record->next;
     295   [ -  +  -  -  :     1572016 :         while (unlikely(record && record->oversized))
                   -  + ]
     296                 :           0 :             record = record->next;
     297                 :             : 
     298         [ -  + ]:     1572016 :         if (record)
     299                 :             :         {
     300                 :             :             /* Adjust head to release space up to the next record. */
     301                 :           0 :             state->decode_buffer_head = (char *) record;
     302                 :             :         }
     303                 :             :         else
     304                 :             :         {
     305                 :             :             /*
     306                 :             :              * Otherwise we might as well just reset head and tail to the
     307                 :             :              * start of the buffer space, because we're empty.  This means
     308                 :             :              * we'll keep overwriting the same piece of memory if we're not
     309                 :             :              * doing any prefetching.
     310                 :             :              */
     311                 :     1572016 :             state->decode_buffer_head = state->decode_buffer;
     312                 :     1572016 :             state->decode_buffer_tail = state->decode_buffer;
     313                 :             :         }
     314                 :             :     }
     315                 :             : 
     316                 :     1572071 :     return next_lsn;
     317                 :             : }
     318                 :             : 
     319                 :             : /*
     320                 :             :  * Attempt to read an XLOG record.
     321                 :             :  *
     322                 :             :  * XLogBeginRead() or XLogFindNextRecord() and then XLogReadAhead() must be
     323                 :             :  * called before the first call to XLogNextRecord().  This functions returns
     324                 :             :  * records and errors that were put into an internal queue by XLogReadAhead().
     325                 :             :  *
     326                 :             :  * On success, a record is returned.
     327                 :             :  *
     328                 :             :  * The returned record (or *errormsg) points to an internal buffer that's
     329                 :             :  * valid until the next call to XLogNextRecord.
     330                 :             :  */
     331                 :             : DecodedXLogRecord *
     332                 :     1572309 : XLogNextRecord(XLogReaderState *state, char **errormsg)
     333                 :             : {
     334                 :             :     /* Release the last record returned by XLogNextRecord(). */
     335                 :     1572309 :     XLogReleasePreviousRecord(state);
     336                 :             : 
     337         [ +  + ]:     1572309 :     if (state->decode_queue_head == NULL)
     338                 :             :     {
     339                 :         116 :         *errormsg = NULL;
     340         [ +  + ]:         116 :         if (state->errormsg_deferred)
     341                 :             :         {
     342         [ +  + ]:           8 :             if (state->errormsg_buf[0] != '\0')
     343                 :           6 :                 *errormsg = state->errormsg_buf;
     344                 :           8 :             state->errormsg_deferred = false;
     345                 :             :         }
     346                 :             : 
     347                 :             :         /*
     348                 :             :          * state->EndRecPtr is expected to have been set by the last call to
     349                 :             :          * XLogBeginRead() or XLogNextRecord(), and is the location of the
     350                 :             :          * error.
     351                 :             :          */
     352                 :             :         Assert(XLogRecPtrIsValid(state->EndRecPtr));
     353                 :             : 
     354                 :         116 :         return NULL;
     355                 :             :     }
     356                 :             : 
     357                 :             :     /*
     358                 :             :      * Record this as the most recent record returned, so that we'll release
     359                 :             :      * it next time.  This also exposes it to the traditional
     360                 :             :      * XLogRecXXX(xlogreader) macros, which work with the decoder rather than
     361                 :             :      * the record for historical reasons.
     362                 :             :      */
     363                 :     1572193 :     state->record = state->decode_queue_head;
     364                 :             : 
     365                 :             :     /*
     366                 :             :      * Update the pointers to the beginning and one-past-the-end of this
     367                 :             :      * record, again for the benefit of historical code that expected the
     368                 :             :      * decoder to track this rather than accessing these fields of the record
     369                 :             :      * itself.
     370                 :             :      */
     371                 :     1572193 :     state->ReadRecPtr = state->record->lsn;
     372                 :     1572193 :     state->EndRecPtr = state->record->next_lsn;
     373                 :             : 
     374                 :     1572193 :     *errormsg = NULL;
     375                 :             : 
     376                 :     1572193 :     return state->record;
     377                 :             : }
     378                 :             : 
     379                 :             : /*
     380                 :             :  * Attempt to read an XLOG record.
     381                 :             :  *
     382                 :             :  * XLogBeginRead() or XLogFindNextRecord() must be called before the first call
     383                 :             :  * to XLogReadRecord().
     384                 :             :  *
     385                 :             :  * If the page_read callback fails to read the requested data, NULL is
     386                 :             :  * returned.  The callback is expected to have reported the error; errormsg
     387                 :             :  * is set to NULL.
     388                 :             :  *
     389                 :             :  * If the reading fails for some other reason, NULL is also returned, and
     390                 :             :  * *errormsg is set to a string with details of the failure.
     391                 :             :  *
     392                 :             :  * The returned pointer (or *errormsg) points to an internal buffer that's
     393                 :             :  * valid until the next call to XLogReadRecord.
     394                 :             :  */
     395                 :             : XLogRecord *
     396                 :     1572309 : XLogReadRecord(XLogReaderState *state, char **errormsg)
     397                 :             : {
     398                 :             :     DecodedXLogRecord *decoded;
     399                 :             : 
     400                 :             :     /*
     401                 :             :      * Release last returned record, if there is one.  We need to do this so
     402                 :             :      * that we can check for empty decode queue accurately.
     403                 :             :      */
     404                 :     1572309 :     XLogReleasePreviousRecord(state);
     405                 :             : 
     406                 :             :     /*
     407                 :             :      * Call XLogReadAhead() in blocking mode to make sure there is something
     408                 :             :      * in the queue, though we don't use the result.
     409                 :             :      */
     410         [ +  - ]:     1572309 :     if (!XLogReaderHasQueuedRecordOrError(state))
     411                 :     1572309 :         XLogReadAhead(state, false /* nonblocking */ );
     412                 :             : 
     413                 :             :     /* Consume the head record or error. */
     414                 :     1572309 :     decoded = XLogNextRecord(state, errormsg);
     415         [ +  + ]:     1572309 :     if (decoded)
     416                 :             :     {
     417                 :             :         /*
     418                 :             :          * This function returns a pointer to the record's header, not the
     419                 :             :          * actual decoded record.  The caller will access the decoded record
     420                 :             :          * through the XLogRecGetXXX() macros, which reach the decoded
     421                 :             :          * recorded as xlogreader->record.
     422                 :             :          */
     423                 :             :         Assert(state->record == decoded);
     424                 :     1572193 :         return &decoded->header;
     425                 :             :     }
     426                 :             : 
     427                 :         116 :     return NULL;
     428                 :             : }
     429                 :             : 
     430                 :             : /*
     431                 :             :  * Allocate space for a decoded record.  The only member of the returned
     432                 :             :  * object that is initialized is the 'oversized' flag, indicating that the
     433                 :             :  * decoded record wouldn't fit in the decode buffer and must eventually be
     434                 :             :  * freed explicitly.
     435                 :             :  *
     436                 :             :  * The caller is responsible for adjusting decode_buffer_tail with the real
     437                 :             :  * size after successfully decoding a record into this space.  This way, if
     438                 :             :  * decoding fails, then there is nothing to undo unless the 'oversized' flag
     439                 :             :  * was set and pfree() must be called.
     440                 :             :  *
     441                 :             :  * Return NULL if there is no space in the decode buffer and allow_oversized
     442                 :             :  * is false, or if memory allocation fails for an oversized buffer.
     443                 :             :  */
     444                 :             : static DecodedXLogRecord *
     445                 :     1572253 : XLogReadRecordAlloc(XLogReaderState *state, size_t xl_tot_len, bool allow_oversized)
     446                 :             : {
     447                 :     1572253 :     size_t      required_space = DecodeXLogRecordRequiredSpace(xl_tot_len);
     448                 :     1572253 :     DecodedXLogRecord *decoded = NULL;
     449                 :             : 
     450                 :             :     /* Allocate a circular decode buffer if we don't have one already. */
     451         [ +  + ]:     1572253 :     if (unlikely(state->decode_buffer == NULL))
     452                 :             :     {
     453         [ +  - ]:         119 :         if (state->decode_buffer_size == 0)
     454                 :         119 :             state->decode_buffer_size = DEFAULT_DECODE_BUFFER_SIZE;
     455                 :         119 :         state->decode_buffer = palloc(state->decode_buffer_size);
     456                 :         119 :         state->decode_buffer_head = state->decode_buffer;
     457                 :         119 :         state->decode_buffer_tail = state->decode_buffer;
     458                 :         119 :         state->free_decode_buffer = true;
     459                 :             :     }
     460                 :             : 
     461                 :             :     /* Try to allocate space in the circular decode buffer. */
     462         [ +  - ]:     1572253 :     if (state->decode_buffer_tail >= state->decode_buffer_head)
     463                 :             :     {
     464                 :             :         /* Empty, or tail is to the right of head. */
     465                 :     1572253 :         if (required_space <=
     466                 :     1572253 :             state->decode_buffer_size -
     467         [ +  + ]:     1572253 :             (state->decode_buffer_tail - state->decode_buffer))
     468                 :             :         {
     469                 :             :             /*-
     470                 :             :              * There is space between tail and end.
     471                 :             :              *
     472                 :             :              * +-----+--------------------+-----+
     473                 :             :              * |     |////////////////////|here!|
     474                 :             :              * +-----+--------------------+-----+
     475                 :             :              *       ^                    ^
     476                 :             :              *       |                    |
     477                 :             :              *       h                    t
     478                 :             :              */
     479                 :     1572135 :             decoded = (DecodedXLogRecord *) state->decode_buffer_tail;
     480                 :     1572135 :             decoded->oversized = false;
     481                 :     1572135 :             return decoded;
     482                 :             :         }
     483                 :         118 :         else if (required_space <
     484         [ -  + ]:         118 :                  state->decode_buffer_head - state->decode_buffer)
     485                 :             :         {
     486                 :             :             /*-
     487                 :             :              * There is space between start and head.
     488                 :             :              *
     489                 :             :              * +-----+--------------------+-----+
     490                 :             :              * |here!|////////////////////|     |
     491                 :             :              * +-----+--------------------+-----+
     492                 :             :              *       ^                    ^
     493                 :             :              *       |                    |
     494                 :             :              *       h                    t
     495                 :             :              */
     496                 :           0 :             decoded = (DecodedXLogRecord *) state->decode_buffer;
     497                 :           0 :             decoded->oversized = false;
     498                 :           0 :             return decoded;
     499                 :             :         }
     500                 :             :     }
     501                 :             :     else
     502                 :             :     {
     503                 :             :         /* Tail is to the left of head. */
     504                 :           0 :         if (required_space <
     505         [ #  # ]:           0 :             state->decode_buffer_head - state->decode_buffer_tail)
     506                 :             :         {
     507                 :             :             /*-
     508                 :             :              * There is space between tail and head.
     509                 :             :              *
     510                 :             :              * +-----+--------------------+-----+
     511                 :             :              * |/////|here!               |/////|
     512                 :             :              * +-----+--------------------+-----+
     513                 :             :              *       ^                    ^
     514                 :             :              *       |                    |
     515                 :             :              *       t                    h
     516                 :             :              */
     517                 :           0 :             decoded = (DecodedXLogRecord *) state->decode_buffer_tail;
     518                 :           0 :             decoded->oversized = false;
     519                 :           0 :             return decoded;
     520                 :             :         }
     521                 :             :     }
     522                 :             : 
     523                 :             :     /* Not enough space in the decode buffer.  Are we allowed to allocate? */
     524         [ +  + ]:         118 :     if (allow_oversized)
     525                 :             :     {
     526                 :          58 :         decoded = palloc(required_space);
     527                 :          58 :         decoded->oversized = true;
     528                 :          58 :         return decoded;
     529                 :             :     }
     530                 :             : 
     531                 :          60 :     return NULL;
     532                 :             : }
     533                 :             : 
     534                 :             : static XLogPageReadResult
     535                 :     1572309 : XLogDecodeNextRecord(XLogReaderState *state, bool nonblocking)
     536                 :             : {
     537                 :             :     XLogRecPtr  RecPtr;
     538                 :             :     XLogRecord *record;
     539                 :             :     XLogRecPtr  targetPagePtr;
     540                 :             :     bool        randAccess;
     541                 :             :     uint32      len,
     542                 :             :                 total_len;
     543                 :             :     uint32      targetRecOff;
     544                 :             :     uint32      pageHeaderSize;
     545                 :             :     bool        assembled;
     546                 :             :     bool        gotheader;
     547                 :             :     int         readOff;
     548                 :             :     DecodedXLogRecord *decoded;
     549                 :             :     char       *errormsg;       /* not used */
     550                 :             : 
     551                 :             :     /*
     552                 :             :      * randAccess indicates whether to verify the previous-record pointer of
     553                 :             :      * the record we're reading.  We only do this if we're reading
     554                 :             :      * sequentially, which is what we initially assume.
     555                 :             :      */
     556                 :     1572309 :     randAccess = false;
     557                 :             : 
     558                 :             :     /* reset error state */
     559                 :     1572309 :     state->errormsg_buf[0] = '\0';
     560                 :     1572309 :     decoded = NULL;
     561                 :             : 
     562                 :     1572309 :     state->abortedRecPtr = InvalidXLogRecPtr;
     563                 :     1572309 :     state->missingContrecPtr = InvalidXLogRecPtr;
     564                 :             : 
     565                 :     1572309 :     RecPtr = state->NextRecPtr;
     566                 :             : 
     567         [ +  + ]:     1572309 :     if (XLogRecPtrIsValid(state->DecodeRecPtr))
     568                 :             :     {
     569                 :             :         /* read the record after the one we just read */
     570                 :             : 
     571                 :             :         /*
     572                 :             :          * NextRecPtr is pointing to end+1 of the previous WAL record.  If
     573                 :             :          * we're at a page boundary, no more records can fit on the current
     574                 :             :          * page. We must skip over the page header, but we can't do that until
     575                 :             :          * we've read in the page, since the header size is variable.
     576                 :             :          */
     577                 :             :     }
     578                 :             :     else
     579                 :             :     {
     580                 :             :         /*
     581                 :             :          * Caller supplied a position to start at.
     582                 :             :          *
     583                 :             :          * In this case, NextRecPtr should already be pointing either to a
     584                 :             :          * valid record starting position or alternatively to the beginning of
     585                 :             :          * a page. See the header comments for XLogBeginRead.
     586                 :             :          */
     587                 :             :         Assert(RecPtr % XLOG_BLCKSZ == 0 || XRecOffIsValid(RecPtr));
     588                 :         238 :         randAccess = true;
     589                 :             :     }
     590                 :             : 
     591                 :     1572309 : restart:
     592                 :     1572309 :     state->nonblocking = nonblocking;
     593                 :     1572309 :     state->currRecPtr = RecPtr;
     594                 :     1572309 :     assembled = false;
     595                 :             : 
     596                 :     1572309 :     targetPagePtr = RecPtr - (RecPtr % XLOG_BLCKSZ);
     597                 :     1572309 :     targetRecOff = RecPtr % XLOG_BLCKSZ;
     598                 :             : 
     599                 :             :     /*
     600                 :             :      * Read the page containing the record into state->readBuf. Request enough
     601                 :             :      * byte to cover the whole record header, or at least the part of it that
     602                 :             :      * fits on the same page.
     603                 :             :      */
     604                 :     1572309 :     readOff = ReadPageInternal(state, targetPagePtr,
     605                 :     1572309 :                                Min(targetRecOff + SizeOfXLogRecord, XLOG_BLCKSZ));
     606         [ -  + ]:     1572309 :     if (readOff == XLREAD_WOULDBLOCK)
     607                 :           0 :         return XLREAD_WOULDBLOCK;
     608         [ +  + ]:     1572309 :     else if (readOff < 0)
     609                 :         108 :         goto err;
     610                 :             : 
     611                 :             :     /*
     612                 :             :      * ReadPageInternal always returns at least the page header, so we can
     613                 :             :      * examine it now.
     614                 :             :      */
     615         [ +  + ]:     1572201 :     pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) state->readBuf);
     616         [ +  + ]:     1572201 :     if (targetRecOff == 0)
     617                 :             :     {
     618                 :             :         /*
     619                 :             :          * At page start, so skip over page header.
     620                 :             :          */
     621                 :        1538 :         RecPtr += pageHeaderSize;
     622                 :        1538 :         targetRecOff = pageHeaderSize;
     623                 :             :     }
     624         [ -  + ]:     1570663 :     else if (targetRecOff < pageHeaderSize)
     625                 :             :     {
     626                 :           0 :         report_invalid_record(state, "invalid record offset at %X/%08X: expected at least %u, got %u",
     627                 :           0 :                               LSN_FORMAT_ARGS(RecPtr),
     628                 :             :                               pageHeaderSize, targetRecOff);
     629                 :           0 :         goto err;
     630                 :             :     }
     631                 :             : 
     632   [ +  +  -  + ]:     1572201 :     if ((((XLogPageHeader) state->readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD) &&
     633                 :             :         targetRecOff == pageHeaderSize)
     634                 :             :     {
     635                 :           0 :         report_invalid_record(state, "contrecord is requested by %X/%08X",
     636                 :           0 :                               LSN_FORMAT_ARGS(RecPtr));
     637                 :           0 :         goto err;
     638                 :             :     }
     639                 :             : 
     640                 :             :     /* ReadPageInternal has verified the page header */
     641                 :             :     Assert(pageHeaderSize <= readOff);
     642                 :             : 
     643                 :             :     /*
     644                 :             :      * Read the record length.
     645                 :             :      *
     646                 :             :      * NB: Even though we use an XLogRecord pointer here, the whole record
     647                 :             :      * header might not fit on this page. xl_tot_len is the first field of the
     648                 :             :      * struct, so it must be on this page (the records are MAXALIGNed), but we
     649                 :             :      * cannot access any other fields until we've verified that we got the
     650                 :             :      * whole header.
     651                 :             :      */
     652                 :     1572201 :     record = (XLogRecord *) (state->readBuf + RecPtr % XLOG_BLCKSZ);
     653                 :     1572201 :     total_len = record->xl_tot_len;
     654                 :             : 
     655                 :             :     /*
     656                 :             :      * If the whole record header is on this page, validate it immediately.
     657                 :             :      * Otherwise do just a basic sanity check on xl_tot_len, and validate the
     658                 :             :      * rest of the header after reading it from the next page.  The xl_tot_len
     659                 :             :      * check is necessary here to ensure that we enter the "Need to reassemble
     660                 :             :      * record" code path below; otherwise we might fail to apply
     661                 :             :      * ValidXLogRecordHeader at all.
     662                 :             :      */
     663         [ +  + ]:     1572201 :     if (targetRecOff <= XLOG_BLCKSZ - SizeOfXLogRecord)
     664                 :             :     {
     665         [ +  + ]:     1568833 :         if (!ValidXLogRecordHeader(state, RecPtr, state->DecodeRecPtr, record,
     666                 :             :                                    randAccess))
     667                 :           6 :             goto err;
     668                 :     1568827 :         gotheader = true;
     669                 :             :     }
     670                 :             :     else
     671                 :             :     {
     672                 :             :         /* There may be no next page if it's too small. */
     673         [ -  + ]:        3368 :         if (total_len < SizeOfXLogRecord)
     674                 :             :         {
     675                 :           0 :             report_invalid_record(state,
     676                 :             :                                   "invalid record length at %X/%08X: expected at least %u, got %u",
     677                 :           0 :                                   LSN_FORMAT_ARGS(RecPtr),
     678                 :             :                                   (uint32) SizeOfXLogRecord, total_len);
     679                 :           0 :             goto err;
     680                 :             :         }
     681                 :             : 
     682                 :             :         /*
     683                 :             :          * If the record length exceeds the maximum allowed size, don't try to
     684                 :             :          * reconstruct it.  The backend enforces the same limit in
     685                 :             :          * XLogRecordAssemble().
     686                 :             :          */
     687         [ -  + ]:        3368 :         if (total_len > XLogRecordMaxSize)
     688                 :             :         {
     689                 :           0 :             report_invalid_record(state,
     690                 :             :                                   "invalid record length at %X/%08X: expected at most %u, got %u",
     691                 :           0 :                                   LSN_FORMAT_ARGS(RecPtr),
     692                 :             :                                   XLogRecordMaxSize, total_len);
     693                 :           0 :             goto err;
     694                 :             :         }
     695                 :             : 
     696                 :             :         /* We'll validate the header once we have the next page. */
     697                 :        3368 :         gotheader = false;
     698                 :             :     }
     699                 :             : 
     700                 :             :     /*
     701                 :             :      * Try to find space to decode this record, if we can do so without
     702                 :             :      * calling palloc.  If we can't, we'll try again below after we've
     703                 :             :      * validated that total_len isn't garbage bytes from a recycled WAL page.
     704                 :             :      */
     705                 :     1572195 :     decoded = XLogReadRecordAlloc(state,
     706                 :             :                                   total_len,
     707                 :             :                                   false /* allow_oversized */ );
     708   [ +  +  -  + ]:     1572195 :     if (decoded == NULL && nonblocking)
     709                 :             :     {
     710                 :             :         /*
     711                 :             :          * There is no space in the circular decode buffer, and the caller is
     712                 :             :          * only reading ahead.  The caller should consume existing records to
     713                 :             :          * make space.
     714                 :             :          */
     715                 :           0 :         return XLREAD_WOULDBLOCK;
     716                 :             :     }
     717                 :             : 
     718                 :     1572195 :     len = XLOG_BLCKSZ - RecPtr % XLOG_BLCKSZ;
     719         [ +  + ]:     1572195 :     if (total_len > len)
     720                 :             :     {
     721                 :             :         /* Need to reassemble record */
     722                 :             :         char       *contdata;
     723                 :             :         XLogPageHeader pageHeader;
     724                 :             :         char       *buffer;
     725                 :             :         uint32      gotlen;
     726                 :             : 
     727                 :       44051 :         assembled = true;
     728                 :             : 
     729                 :             :         /*
     730                 :             :          * We always have space for a couple of pages, enough to validate a
     731                 :             :          * boundary-spanning record header.
     732                 :             :          */
     733                 :             :         Assert(state->readRecordBufSize >= XLOG_BLCKSZ * 2);
     734                 :             :         Assert(state->readRecordBufSize >= len);
     735                 :             : 
     736                 :             :         /* Copy the first fragment of the record from the first page. */
     737                 :       44051 :         memcpy(state->readRecordBuf,
     738                 :       44051 :                state->readBuf + RecPtr % XLOG_BLCKSZ, len);
     739                 :       44051 :         buffer = state->readRecordBuf + len;
     740                 :       44051 :         gotlen = len;
     741                 :             : 
     742                 :             :         do
     743                 :             :         {
     744                 :             :             /* Calculate pointer to beginning of next page */
     745                 :       48148 :             targetPagePtr += XLOG_BLCKSZ;
     746                 :             : 
     747                 :             :             /*
     748                 :             :              * Read the page header before processing the record data, so we
     749                 :             :              * can handle the case where the previous record ended as being a
     750                 :             :              * partial one.
     751                 :             :              */
     752                 :       48148 :             readOff = ReadPageInternal(state, targetPagePtr, SizeOfXLogShortPHD);
     753         [ -  + ]:       48148 :             if (readOff == XLREAD_WOULDBLOCK)
     754                 :           0 :                 return XLREAD_WOULDBLOCK;
     755         [ +  + ]:       48148 :             else if (readOff < 0)
     756                 :           2 :                 goto err;
     757                 :             : 
     758                 :             :             Assert(SizeOfXLogShortPHD <= readOff);
     759                 :             : 
     760                 :       48146 :             pageHeader = (XLogPageHeader) state->readBuf;
     761                 :             : 
     762                 :             :             /*
     763                 :             :              * If we were expecting a continuation record and got an
     764                 :             :              * "overwrite contrecord" flag, that means the continuation record
     765                 :             :              * was overwritten with a different record.  Restart the read by
     766                 :             :              * assuming the address to read is the location where we found
     767                 :             :              * this flag; but keep track of the LSN of the record we were
     768                 :             :              * reading, for later verification.
     769                 :             :              */
     770         [ -  + ]:       48146 :             if (pageHeader->xlp_info & XLP_FIRST_IS_OVERWRITE_CONTRECORD)
     771                 :             :             {
     772                 :           0 :                 state->overwrittenRecPtr = RecPtr;
     773                 :           0 :                 RecPtr = targetPagePtr;
     774                 :           0 :                 goto restart;
     775                 :             :             }
     776                 :             : 
     777                 :             :             /* Check that the continuation on next page looks valid */
     778         [ -  + ]:       48146 :             if (!(pageHeader->xlp_info & XLP_FIRST_IS_CONTRECORD))
     779                 :             :             {
     780                 :           0 :                 report_invalid_record(state,
     781                 :             :                                       "there is no contrecord flag at %X/%08X",
     782                 :           0 :                                       LSN_FORMAT_ARGS(RecPtr));
     783                 :           0 :                 goto err;
     784                 :             :             }
     785                 :             : 
     786                 :             :             /*
     787                 :             :              * Cross-check that xlp_rem_len agrees with how much of the record
     788                 :             :              * we expect there to be left.
     789                 :             :              */
     790         [ +  - ]:       48146 :             if (pageHeader->xlp_rem_len == 0 ||
     791         [ -  + ]:       48146 :                 total_len != (pageHeader->xlp_rem_len + gotlen))
     792                 :             :             {
     793                 :           0 :                 report_invalid_record(state,
     794                 :             :                                       "invalid contrecord length %u (expected %lld) at %X/%08X",
     795                 :             :                                       pageHeader->xlp_rem_len,
     796                 :           0 :                                       ((long long) total_len) - gotlen,
     797                 :           0 :                                       LSN_FORMAT_ARGS(RecPtr));
     798                 :           0 :                 goto err;
     799                 :             :             }
     800                 :             : 
     801                 :             :             /* Wait for the next page to become available */
     802                 :       48146 :             readOff = ReadPageInternal(state, targetPagePtr,
     803                 :       48146 :                                        Min(total_len - gotlen + SizeOfXLogShortPHD,
     804                 :             :                                            XLOG_BLCKSZ));
     805         [ -  + ]:       48146 :             if (readOff == XLREAD_WOULDBLOCK)
     806                 :           0 :                 return XLREAD_WOULDBLOCK;
     807         [ -  + ]:       48146 :             else if (readOff < 0)
     808                 :           0 :                 goto err;
     809                 :             : 
     810                 :             :             /* Append the continuation from this page to the buffer */
     811         [ +  + ]:       48146 :             pageHeaderSize = XLogPageHeaderSize(pageHeader);
     812                 :             : 
     813         [ -  + ]:       48146 :             if (readOff < pageHeaderSize)
     814                 :           0 :                 readOff = ReadPageInternal(state, targetPagePtr,
     815                 :             :                                            pageHeaderSize);
     816                 :             : 
     817                 :             :             Assert(pageHeaderSize <= readOff);
     818                 :             : 
     819                 :       48146 :             contdata = (char *) state->readBuf + pageHeaderSize;
     820                 :       48146 :             len = XLOG_BLCKSZ - pageHeaderSize;
     821         [ +  + ]:       48146 :             if (pageHeader->xlp_rem_len < len)
     822                 :       44049 :                 len = pageHeader->xlp_rem_len;
     823                 :             : 
     824         [ -  + ]:       48146 :             if (readOff < pageHeaderSize + len)
     825                 :           0 :                 readOff = ReadPageInternal(state, targetPagePtr,
     826                 :           0 :                                            pageHeaderSize + len);
     827                 :             : 
     828                 :       48146 :             memcpy(buffer, contdata, len);
     829                 :       48146 :             buffer += len;
     830                 :       48146 :             gotlen += len;
     831                 :             : 
     832                 :             :             /* If we just reassembled the record header, validate it. */
     833         [ +  + ]:       48146 :             if (!gotheader)
     834                 :             :             {
     835                 :        3368 :                 record = (XLogRecord *) state->readRecordBuf;
     836         [ -  + ]:        3368 :                 if (!ValidXLogRecordHeader(state, RecPtr, state->DecodeRecPtr,
     837                 :             :                                            record, randAccess))
     838                 :           0 :                     goto err;
     839                 :        3368 :                 gotheader = true;
     840                 :             :             }
     841                 :             : 
     842                 :             :             /*
     843                 :             :              * We might need a bigger buffer.  We have validated the record
     844                 :             :              * header, in the case that it split over a page boundary.  We've
     845                 :             :              * also cross-checked total_len against xlp_rem_len on the second
     846                 :             :              * page, and verified xlp_pageaddr on both.
     847                 :             :              */
     848         [ +  + ]:       48146 :             if (total_len > state->readRecordBufSize)
     849                 :             :             {
     850                 :             :                 char        save_copy[XLOG_BLCKSZ * 2];
     851                 :             : 
     852                 :             :                 /*
     853                 :             :                  * Save and restore the data we already had.  It can't be more
     854                 :             :                  * than two pages.
     855                 :             :                  */
     856                 :             :                 Assert(gotlen <= lengthof(save_copy));
     857                 :             :                 Assert(gotlen <= state->readRecordBufSize);
     858                 :          53 :                 memcpy(save_copy, state->readRecordBuf, gotlen);
     859                 :          53 :                 allocate_recordbuf(state, total_len);
     860                 :          53 :                 memcpy(state->readRecordBuf, save_copy, gotlen);
     861                 :          53 :                 buffer = state->readRecordBuf + gotlen;
     862                 :             :             }
     863         [ +  + ]:       48146 :         } while (gotlen < total_len);
     864                 :             :         Assert(gotheader);
     865                 :             : 
     866                 :       44049 :         record = (XLogRecord *) state->readRecordBuf;
     867         [ -  + ]:       44049 :         if (!ValidXLogRecord(state, record, RecPtr))
     868                 :           0 :             goto err;
     869                 :             : 
     870         [ -  + ]:       44049 :         pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) state->readBuf);
     871                 :       44049 :         state->DecodeRecPtr = RecPtr;
     872                 :       44049 :         state->NextRecPtr = targetPagePtr + pageHeaderSize
     873                 :       44049 :             + MAXALIGN(pageHeader->xlp_rem_len);
     874                 :             :     }
     875                 :             :     else
     876                 :             :     {
     877                 :             :         /* Wait for the record data to become available */
     878                 :     1528144 :         readOff = ReadPageInternal(state, targetPagePtr,
     879                 :     1528144 :                                    Min(targetRecOff + total_len, XLOG_BLCKSZ));
     880         [ -  + ]:     1528144 :         if (readOff == XLREAD_WOULDBLOCK)
     881                 :           0 :             return XLREAD_WOULDBLOCK;
     882         [ -  + ]:     1528144 :         else if (readOff < 0)
     883                 :           0 :             goto err;
     884                 :             : 
     885                 :             :         /* Record does not cross a page boundary */
     886         [ -  + ]:     1528144 :         if (!ValidXLogRecord(state, record, RecPtr))
     887                 :           0 :             goto err;
     888                 :             : 
     889                 :     1528144 :         state->NextRecPtr = RecPtr + MAXALIGN(total_len);
     890                 :             : 
     891                 :     1528144 :         state->DecodeRecPtr = RecPtr;
     892                 :             :     }
     893                 :             : 
     894                 :             :     /*
     895                 :             :      * Special processing if it's an XLOG SWITCH record
     896                 :             :      */
     897         [ +  + ]:     1572193 :     if (record->xl_rmid == RM_XLOG_ID &&
     898         [ +  + ]:       42398 :         (record->xl_info & ~XLR_INFO_MASK) == XLOG_SWITCH)
     899                 :             :     {
     900                 :             :         /* Pretend it extends to end of segment */
     901                 :           8 :         state->NextRecPtr += state->segcxt.ws_segsize - 1;
     902                 :           8 :         state->NextRecPtr -= XLogSegmentOffset(state->NextRecPtr, state->segcxt.ws_segsize);
     903                 :             :     }
     904                 :             : 
     905                 :             :     /*
     906                 :             :      * If we got here without a DecodedXLogRecord, it means we needed to
     907                 :             :      * validate total_len before trusting it, but by now we've done that.
     908                 :             :      */
     909         [ +  + ]:     1572193 :     if (decoded == NULL)
     910                 :             :     {
     911                 :             :         Assert(!nonblocking);
     912                 :          58 :         decoded = XLogReadRecordAlloc(state,
     913                 :             :                                       total_len,
     914                 :             :                                       true /* allow_oversized */ );
     915                 :             :         /* allocation should always happen under allow_oversized */
     916                 :             :         Assert(decoded != NULL);
     917                 :             :     }
     918                 :             : 
     919         [ +  - ]:     1572193 :     if (DecodeXLogRecord(state, decoded, record, RecPtr, &errormsg))
     920                 :             :     {
     921                 :             :         /* Record the location of the next record. */
     922                 :     1572193 :         decoded->next_lsn = state->NextRecPtr;
     923                 :             : 
     924                 :             :         /*
     925                 :             :          * If it's in the decode buffer, mark the decode buffer space as
     926                 :             :          * occupied.
     927                 :             :          */
     928         [ +  + ]:     1572193 :         if (!decoded->oversized)
     929                 :             :         {
     930                 :             :             /* The new decode buffer head must be MAXALIGNed. */
     931                 :             :             Assert(decoded->size == MAXALIGN(decoded->size));
     932         [ +  - ]:     1572135 :             if ((char *) decoded == state->decode_buffer)
     933                 :     1572135 :                 state->decode_buffer_tail = state->decode_buffer + decoded->size;
     934                 :             :             else
     935                 :           0 :                 state->decode_buffer_tail += decoded->size;
     936                 :             :         }
     937                 :             : 
     938                 :             :         /* Insert it into the queue of decoded records. */
     939                 :             :         Assert(state->decode_queue_tail != decoded);
     940         [ -  + ]:     1572193 :         if (state->decode_queue_tail)
     941                 :           0 :             state->decode_queue_tail->next = decoded;
     942                 :     1572193 :         state->decode_queue_tail = decoded;
     943         [ +  - ]:     1572193 :         if (!state->decode_queue_head)
     944                 :     1572193 :             state->decode_queue_head = decoded;
     945                 :     1572193 :         return XLREAD_SUCCESS;
     946                 :             :     }
     947                 :             : 
     948                 :           0 : err:
     949         [ +  + ]:         116 :     if (assembled)
     950                 :             :     {
     951                 :             :         /*
     952                 :             :          * We get here when a record that spans multiple pages needs to be
     953                 :             :          * assembled, but something went wrong -- perhaps a contrecord piece
     954                 :             :          * was lost.  If caller is WAL replay, it will know where the aborted
     955                 :             :          * record was and where to direct followup WAL to be written, marking
     956                 :             :          * the next piece with XLP_FIRST_IS_OVERWRITE_CONTRECORD, which will
     957                 :             :          * in turn signal downstream WAL consumers that the broken WAL record
     958                 :             :          * is to be ignored.
     959                 :             :          */
     960                 :           2 :         state->abortedRecPtr = RecPtr;
     961                 :           2 :         state->missingContrecPtr = targetPagePtr;
     962                 :             : 
     963                 :             :         /*
     964                 :             :          * If we got here without reporting an error, make sure an error is
     965                 :             :          * queued so that XLogPrefetcherReadRecord() doesn't bring us back a
     966                 :             :          * second time and clobber the above state.
     967                 :             :          */
     968                 :           2 :         state->errormsg_deferred = true;
     969                 :             :     }
     970                 :             : 
     971   [ -  +  -  - ]:         116 :     if (decoded && decoded->oversized)
     972                 :           0 :         pfree(decoded);
     973                 :             : 
     974                 :             :     /*
     975                 :             :      * Invalidate the read state. We might read from a different source after
     976                 :             :      * failure.
     977                 :             :      */
     978                 :         116 :     XLogReaderInvalReadState(state);
     979                 :             : 
     980                 :             :     /*
     981                 :             :      * If an error was written to errormsg_buf, it'll be returned to the
     982                 :             :      * caller of XLogReadRecord() after all successfully decoded records from
     983                 :             :      * the read queue.
     984                 :             :      */
     985                 :             : 
     986                 :         116 :     return XLREAD_FAIL;
     987                 :             : }
     988                 :             : 
     989                 :             : /*
     990                 :             :  * Try to decode the next available record, and return it.  The record will
     991                 :             :  * also be returned to XLogNextRecord(), which must be called to 'consume'
     992                 :             :  * each record.
     993                 :             :  *
     994                 :             :  * If nonblocking is true, may return NULL due to lack of data or WAL decoding
     995                 :             :  * space.
     996                 :             :  */
     997                 :             : DecodedXLogRecord *
     998                 :     1572309 : XLogReadAhead(XLogReaderState *state, bool nonblocking)
     999                 :             : {
    1000                 :             :     XLogPageReadResult result;
    1001                 :             : 
    1002         [ -  + ]:     1572309 :     if (state->errormsg_deferred)
    1003                 :           0 :         return NULL;
    1004                 :             : 
    1005                 :     1572309 :     result = XLogDecodeNextRecord(state, nonblocking);
    1006         [ +  + ]:     1572309 :     if (result == XLREAD_SUCCESS)
    1007                 :             :     {
    1008                 :             :         Assert(state->decode_queue_tail != NULL);
    1009                 :     1572193 :         return state->decode_queue_tail;
    1010                 :             :     }
    1011                 :             : 
    1012                 :         116 :     return NULL;
    1013                 :             : }
    1014                 :             : 
    1015                 :             : /*
    1016                 :             :  * Read a single xlog page including at least [pageptr, reqLen] of valid data
    1017                 :             :  * via the page_read() callback.
    1018                 :             :  *
    1019                 :             :  * Returns XLREAD_FAIL if the required page cannot be read for some
    1020                 :             :  * reason; errormsg_buf is set in that case (unless the error occurs in the
    1021                 :             :  * page_read callback).
    1022                 :             :  *
    1023                 :             :  * Returns XLREAD_WOULDBLOCK if the requested data can't be read without
    1024                 :             :  * waiting.  This can be returned only if the installed page_read callback
    1025                 :             :  * respects the state->nonblocking flag, and cannot read the requested data
    1026                 :             :  * immediately.
    1027                 :             :  *
    1028                 :             :  * We fetch the page from a reader-local cache if we know we have the required
    1029                 :             :  * data and if there hasn't been any error since caching the data.
    1030                 :             :  */
    1031                 :             : static int
    1032                 :     3196986 : ReadPageInternal(XLogReaderState *state, XLogRecPtr pageptr, int reqLen)
    1033                 :             : {
    1034                 :             :     int         readLen;
    1035                 :             :     uint32      targetPageOff;
    1036                 :             :     XLogSegNo   targetSegNo;
    1037                 :             :     XLogPageHeader hdr;
    1038                 :             : 
    1039                 :             :     Assert((pageptr % XLOG_BLCKSZ) == 0);
    1040                 :             : 
    1041                 :     3196986 :     XLByteToSeg(pageptr, targetSegNo, state->segcxt.ws_segsize);
    1042                 :     3196986 :     targetPageOff = XLogSegmentOffset(pageptr, state->segcxt.ws_segsize);
    1043                 :             : 
    1044                 :             :     /* check whether we have all the requested data already */
    1045         [ +  + ]:     3196986 :     if (targetSegNo == state->seg.ws_segno &&
    1046   [ +  +  +  + ]:     3196807 :         targetPageOff == state->segoff && reqLen <= state->readLen)
    1047                 :     3147069 :         return state->readLen;
    1048                 :             : 
    1049                 :             :     /*
    1050                 :             :      * Invalidate contents of internal buffer before read attempt.  Just set
    1051                 :             :      * the length to 0, rather than a full XLogReaderInvalReadState(), so we
    1052                 :             :      * don't forget the segment we last successfully read.
    1053                 :             :      */
    1054                 :       49917 :     state->readLen = 0;
    1055                 :             : 
    1056                 :             :     /*
    1057                 :             :      * Data is not in our buffer.
    1058                 :             :      *
    1059                 :             :      * Every time we actually read the segment, even if we looked at parts of
    1060                 :             :      * it before, we need to do verification as the page_read callback might
    1061                 :             :      * now be rereading data from a different source.
    1062                 :             :      *
    1063                 :             :      * Whenever switching to a new WAL segment, we read the first page of the
    1064                 :             :      * file and validate its header, even if that's not where the target
    1065                 :             :      * record is.  This is so that we can check the additional identification
    1066                 :             :      * info that is present in the first page's "long" header.
    1067                 :             :      */
    1068   [ +  +  +  + ]:       49917 :     if (targetSegNo != state->seg.ws_segno && targetPageOff != 0)
    1069                 :             :     {
    1070                 :          48 :         XLogRecPtr  targetSegmentPtr = pageptr - targetPageOff;
    1071                 :             : 
    1072                 :          48 :         readLen = state->routine.page_read(state, targetSegmentPtr, XLOG_BLCKSZ,
    1073                 :             :                                            state->currRecPtr,
    1074                 :             :                                            state->readBuf);
    1075         [ -  + ]:          48 :         if (readLen == XLREAD_WOULDBLOCK)
    1076                 :           0 :             return XLREAD_WOULDBLOCK;
    1077         [ -  + ]:          48 :         else if (readLen < 0)
    1078                 :           0 :             goto err;
    1079                 :             : 
    1080                 :             :         /* we can be sure to have enough WAL available, we scrolled back */
    1081                 :             :         Assert(readLen == XLOG_BLCKSZ);
    1082                 :             : 
    1083         [ -  + ]:          48 :         if (!XLogReaderValidatePageHeader(state, targetSegmentPtr,
    1084                 :             :                                           state->readBuf))
    1085                 :           0 :             goto err;
    1086                 :             :     }
    1087                 :             : 
    1088                 :             :     /*
    1089                 :             :      * First, read the requested data length, but at least a short page header
    1090                 :             :      * so that we can validate it.
    1091                 :             :      */
    1092                 :       49917 :     readLen = state->routine.page_read(state, pageptr, Max(reqLen, SizeOfXLogShortPHD),
    1093                 :             :                                        state->currRecPtr,
    1094                 :             :                                        state->readBuf);
    1095         [ -  + ]:       49917 :     if (readLen == XLREAD_WOULDBLOCK)
    1096                 :           0 :         return XLREAD_WOULDBLOCK;
    1097         [ +  + ]:       49917 :     else if (readLen < 0)
    1098                 :         110 :         goto err;
    1099                 :             : 
    1100                 :             :     Assert(readLen <= XLOG_BLCKSZ);
    1101                 :             : 
    1102                 :             :     /* Do we have enough data to check the header length? */
    1103         [ -  + ]:       49807 :     if (readLen <= SizeOfXLogShortPHD)
    1104                 :           0 :         goto err;
    1105                 :             : 
    1106                 :             :     Assert(readLen >= reqLen);
    1107                 :             : 
    1108                 :       49807 :     hdr = (XLogPageHeader) state->readBuf;
    1109                 :             : 
    1110                 :             :     /* still not enough */
    1111   [ +  +  -  + ]:       49807 :     if (readLen < XLogPageHeaderSize(hdr))
    1112                 :             :     {
    1113         [ #  # ]:           0 :         readLen = state->routine.page_read(state, pageptr, XLogPageHeaderSize(hdr),
    1114                 :             :                                            state->currRecPtr,
    1115                 :             :                                            state->readBuf);
    1116         [ #  # ]:           0 :         if (readLen == XLREAD_WOULDBLOCK)
    1117                 :           0 :             return XLREAD_WOULDBLOCK;
    1118         [ #  # ]:           0 :         else if (readLen < 0)
    1119                 :           0 :             goto err;
    1120                 :             :     }
    1121                 :             : 
    1122                 :             :     /*
    1123                 :             :      * Now that we know we have the full header, validate it.
    1124                 :             :      */
    1125         [ +  + ]:       49807 :     if (!XLogReaderValidatePageHeader(state, pageptr, (char *) hdr))
    1126                 :           1 :         goto err;
    1127                 :             : 
    1128                 :             :     /* update read state information */
    1129                 :       49806 :     state->seg.ws_segno = targetSegNo;
    1130                 :       49806 :     state->segoff = targetPageOff;
    1131                 :       49806 :     state->readLen = readLen;
    1132                 :             : 
    1133                 :       49806 :     return readLen;
    1134                 :             : 
    1135                 :         111 : err:
    1136                 :         111 :     XLogReaderInvalReadState(state);
    1137                 :             : 
    1138                 :         111 :     return XLREAD_FAIL;
    1139                 :             : }
    1140                 :             : 
    1141                 :             : /*
    1142                 :             :  * Invalidate the xlogreader's read state to force a re-read.
    1143                 :             :  */
    1144                 :             : static void
    1145                 :         228 : XLogReaderInvalReadState(XLogReaderState *state)
    1146                 :             : {
    1147                 :         228 :     state->seg.ws_segno = 0;
    1148                 :         228 :     state->segoff = 0;
    1149                 :         228 :     state->readLen = 0;
    1150                 :         228 : }
    1151                 :             : 
    1152                 :             : /*
    1153                 :             :  * Validate an XLOG record header.
    1154                 :             :  *
    1155                 :             :  * This is just a convenience subroutine to avoid duplicated code in
    1156                 :             :  * XLogReadRecord.  It's not intended for use from anywhere else.
    1157                 :             :  */
    1158                 :             : static bool
    1159                 :     1572201 : ValidXLogRecordHeader(XLogReaderState *state, XLogRecPtr RecPtr,
    1160                 :             :                       XLogRecPtr PrevRecPtr, XLogRecord *record,
    1161                 :             :                       bool randAccess)
    1162                 :             : {
    1163         [ +  + ]:     1572201 :     if (record->xl_tot_len < SizeOfXLogRecord)
    1164                 :             :     {
    1165                 :           6 :         report_invalid_record(state,
    1166                 :             :                               "invalid record length at %X/%08X: expected at least %u, got %u",
    1167                 :           6 :                               LSN_FORMAT_ARGS(RecPtr),
    1168                 :             :                               (uint32) SizeOfXLogRecord, record->xl_tot_len);
    1169                 :           6 :         return false;
    1170                 :             :     }
    1171                 :             : 
    1172         [ -  + ]:     1572195 :     if (record->xl_tot_len > XLogRecordMaxSize)
    1173                 :             :     {
    1174                 :           0 :         report_invalid_record(state,
    1175                 :             :                               "invalid record length at %X/%08X: expected at most %u, got %u",
    1176                 :           0 :                               LSN_FORMAT_ARGS(RecPtr),
    1177                 :             :                               XLogRecordMaxSize, record->xl_tot_len);
    1178                 :           0 :         return false;
    1179                 :             :     }
    1180   [ -  +  -  - ]:     1572195 :     if (!RmgrIdIsValid(record->xl_rmid))
    1181                 :             :     {
    1182                 :           0 :         report_invalid_record(state,
    1183                 :             :                               "invalid resource manager ID %u at %X/%08X",
    1184                 :           0 :                               record->xl_rmid, LSN_FORMAT_ARGS(RecPtr));
    1185                 :           0 :         return false;
    1186                 :             :     }
    1187         [ +  + ]:     1572195 :     if (randAccess)
    1188                 :             :     {
    1189                 :             :         /*
    1190                 :             :          * We can't exactly verify the prev-link, but surely it should be less
    1191                 :             :          * than the record's own address.
    1192                 :             :          */
    1193         [ -  + ]:         238 :         if (!(record->xl_prev < RecPtr))
    1194                 :             :         {
    1195                 :           0 :             report_invalid_record(state,
    1196                 :             :                                   "record with incorrect prev-link %X/%08X at %X/%08X",
    1197                 :           0 :                                   LSN_FORMAT_ARGS(record->xl_prev),
    1198                 :           0 :                                   LSN_FORMAT_ARGS(RecPtr));
    1199                 :           0 :             return false;
    1200                 :             :         }
    1201                 :             :     }
    1202                 :             :     else
    1203                 :             :     {
    1204                 :             :         /*
    1205                 :             :          * Record's prev-link should exactly match our previous location. This
    1206                 :             :          * check guards against torn WAL pages where a stale but valid-looking
    1207                 :             :          * WAL record starts on a sector boundary.
    1208                 :             :          */
    1209         [ -  + ]:     1571957 :         if (record->xl_prev != PrevRecPtr)
    1210                 :             :         {
    1211                 :           0 :             report_invalid_record(state,
    1212                 :             :                                   "record with incorrect prev-link %X/%08X at %X/%08X",
    1213                 :           0 :                                   LSN_FORMAT_ARGS(record->xl_prev),
    1214                 :           0 :                                   LSN_FORMAT_ARGS(RecPtr));
    1215                 :           0 :             return false;
    1216                 :             :         }
    1217                 :             :     }
    1218                 :             : 
    1219                 :     1572195 :     return true;
    1220                 :             : }
    1221                 :             : 
    1222                 :             : 
    1223                 :             : /*
    1224                 :             :  * CRC-check an XLOG record.  We do not believe the contents of an XLOG
    1225                 :             :  * record (other than to the minimal extent of computing the amount of
    1226                 :             :  * data to read in) until we've checked the CRCs.
    1227                 :             :  *
    1228                 :             :  * We assume all of the record (that is, xl_tot_len bytes) has been read
    1229                 :             :  * into memory at *record.  Also, ValidXLogRecordHeader() has accepted the
    1230                 :             :  * record's header, which means in particular that xl_tot_len is at least
    1231                 :             :  * SizeOfXLogRecord.
    1232                 :             :  */
    1233                 :             : static bool
    1234                 :     1572193 : ValidXLogRecord(XLogReaderState *state, XLogRecord *record, XLogRecPtr recptr)
    1235                 :             : {
    1236                 :             :     pg_crc32c   crc;
    1237                 :             : 
    1238                 :             :     Assert(record->xl_tot_len >= SizeOfXLogRecord);
    1239                 :             : 
    1240                 :             :     /* Calculate the CRC */
    1241                 :     1572193 :     INIT_CRC32C(crc);
    1242                 :     1572193 :     COMP_CRC32C(crc, ((char *) record) + SizeOfXLogRecord, record->xl_tot_len - SizeOfXLogRecord);
    1243                 :             :     /* include the record header last */
    1244                 :     1572193 :     COMP_CRC32C(crc, (char *) record, offsetof(XLogRecord, xl_crc));
    1245                 :     1572193 :     FIN_CRC32C(crc);
    1246                 :             : 
    1247         [ -  + ]:     1572193 :     if (!EQ_CRC32C(record->xl_crc, crc))
    1248                 :             :     {
    1249                 :           0 :         report_invalid_record(state,
    1250                 :             :                               "incorrect resource manager data checksum in record at %X/%08X",
    1251                 :           0 :                               LSN_FORMAT_ARGS(recptr));
    1252                 :           0 :         return false;
    1253                 :             :     }
    1254                 :             : 
    1255                 :     1572193 :     return true;
    1256                 :             : }
    1257                 :             : 
    1258                 :             : /*
    1259                 :             :  * Validate a page header.
    1260                 :             :  *
    1261                 :             :  * Check if 'phdr' is valid as the header of the XLog page at position
    1262                 :             :  * 'recptr'.
    1263                 :             :  */
    1264                 :             : bool
    1265                 :       49855 : XLogReaderValidatePageHeader(XLogReaderState *state, XLogRecPtr recptr,
    1266                 :             :                              char *phdr)
    1267                 :             : {
    1268                 :             :     XLogSegNo   segno;
    1269                 :             :     int32       offset;
    1270                 :       49855 :     XLogPageHeader hdr = (XLogPageHeader) phdr;
    1271                 :             : 
    1272                 :             :     Assert((recptr % XLOG_BLCKSZ) == 0);
    1273                 :             : 
    1274                 :       49855 :     XLByteToSeg(recptr, segno, state->segcxt.ws_segsize);
    1275                 :       49855 :     offset = XLogSegmentOffset(recptr, state->segcxt.ws_segsize);
    1276                 :             : 
    1277         [ +  + ]:       49855 :     if (hdr->xlp_magic != XLOG_PAGE_MAGIC)
    1278                 :             :     {
    1279                 :             :         char        fname[MAXFNAMELEN];
    1280                 :             : 
    1281                 :           1 :         XLogFileName(fname, state->seg.ws_tli, segno, state->segcxt.ws_segsize);
    1282                 :             : 
    1283                 :           1 :         report_invalid_record(state,
    1284                 :             :                               "invalid magic number %04X in WAL segment %s, LSN %X/%08X, offset %u",
    1285                 :           1 :                               hdr->xlp_magic,
    1286                 :             :                               fname,
    1287                 :           1 :                               LSN_FORMAT_ARGS(recptr),
    1288                 :             :                               offset);
    1289                 :           1 :         return false;
    1290                 :             :     }
    1291                 :             : 
    1292         [ -  + ]:       49854 :     if ((hdr->xlp_info & ~XLP_ALL_FLAGS) != 0)
    1293                 :             :     {
    1294                 :             :         char        fname[MAXFNAMELEN];
    1295                 :             : 
    1296                 :           0 :         XLogFileName(fname, state->seg.ws_tli, segno, state->segcxt.ws_segsize);
    1297                 :             : 
    1298                 :           0 :         report_invalid_record(state,
    1299                 :             :                               "invalid info bits %04X in WAL segment %s, LSN %X/%08X, offset %u",
    1300                 :           0 :                               hdr->xlp_info,
    1301                 :             :                               fname,
    1302                 :           0 :                               LSN_FORMAT_ARGS(recptr),
    1303                 :             :                               offset);
    1304                 :           0 :         return false;
    1305                 :             :     }
    1306                 :             : 
    1307         [ +  + ]:       49854 :     if (hdr->xlp_info & XLP_LONG_HEADER)
    1308                 :             :     {
    1309                 :         174 :         XLogLongPageHeader longhdr = (XLogLongPageHeader) hdr;
    1310                 :             : 
    1311         [ -  + ]:         174 :         if (state->system_identifier &&
    1312         [ #  # ]:           0 :             longhdr->xlp_sysid != state->system_identifier)
    1313                 :             :         {
    1314                 :           0 :             report_invalid_record(state,
    1315                 :             :                                   "WAL file is from different database system: WAL file database system identifier is %" PRIu64 ", pg_control database system identifier is %" PRIu64,
    1316                 :             :                                   longhdr->xlp_sysid,
    1317                 :             :                                   state->system_identifier);
    1318                 :           0 :             return false;
    1319                 :             :         }
    1320         [ -  + ]:         174 :         else if (longhdr->xlp_seg_size != state->segcxt.ws_segsize)
    1321                 :             :         {
    1322                 :           0 :             report_invalid_record(state,
    1323                 :             :                                   "WAL file is from different database system: incorrect segment size in page header");
    1324                 :           0 :             return false;
    1325                 :             :         }
    1326         [ -  + ]:         174 :         else if (longhdr->xlp_xlog_blcksz != XLOG_BLCKSZ)
    1327                 :             :         {
    1328                 :           0 :             report_invalid_record(state,
    1329                 :             :                                   "WAL file is from different database system: incorrect XLOG_BLCKSZ in page header");
    1330                 :           0 :             return false;
    1331                 :             :         }
    1332                 :             :     }
    1333         [ -  + ]:       49680 :     else if (offset == 0)
    1334                 :             :     {
    1335                 :             :         char        fname[MAXFNAMELEN];
    1336                 :             : 
    1337                 :           0 :         XLogFileName(fname, state->seg.ws_tli, segno, state->segcxt.ws_segsize);
    1338                 :             : 
    1339                 :             :         /* hmm, first page of file doesn't have a long header? */
    1340                 :           0 :         report_invalid_record(state,
    1341                 :             :                               "invalid info bits %04X in WAL segment %s, LSN %X/%08X, offset %u",
    1342                 :           0 :                               hdr->xlp_info,
    1343                 :             :                               fname,
    1344                 :           0 :                               LSN_FORMAT_ARGS(recptr),
    1345                 :             :                               offset);
    1346                 :           0 :         return false;
    1347                 :             :     }
    1348                 :             : 
    1349                 :             :     /*
    1350                 :             :      * Check that the address on the page agrees with what we expected. This
    1351                 :             :      * check typically fails when an old WAL segment is recycled, and hasn't
    1352                 :             :      * yet been overwritten with new data yet.
    1353                 :             :      */
    1354         [ -  + ]:       49854 :     if (hdr->xlp_pageaddr != recptr)
    1355                 :             :     {
    1356                 :             :         char        fname[MAXFNAMELEN];
    1357                 :             : 
    1358                 :           0 :         XLogFileName(fname, state->seg.ws_tli, segno, state->segcxt.ws_segsize);
    1359                 :             : 
    1360                 :           0 :         report_invalid_record(state,
    1361                 :             :                               "unexpected pageaddr %X/%08X in WAL segment %s, LSN %X/%08X, offset %u",
    1362                 :           0 :                               LSN_FORMAT_ARGS(hdr->xlp_pageaddr),
    1363                 :             :                               fname,
    1364                 :           0 :                               LSN_FORMAT_ARGS(recptr),
    1365                 :             :                               offset);
    1366                 :           0 :         return false;
    1367                 :             :     }
    1368                 :             : 
    1369                 :             :     /*
    1370                 :             :      * Since child timelines are always assigned a TLI greater than their
    1371                 :             :      * immediate parent's TLI, we should never see TLI go backwards across
    1372                 :             :      * successive pages of a consistent WAL sequence.
    1373                 :             :      *
    1374                 :             :      * Sometimes we re-read a segment that's already been (partially) read. So
    1375                 :             :      * we only verify TLIs for pages that are later than the last remembered
    1376                 :             :      * LSN.
    1377                 :             :      */
    1378         [ +  + ]:       49854 :     if (recptr > state->latestPagePtr)
    1379                 :             :     {
    1380         [ -  + ]:       49851 :         if (hdr->xlp_tli < state->latestPageTLI)
    1381                 :             :         {
    1382                 :             :             char        fname[MAXFNAMELEN];
    1383                 :             : 
    1384                 :           0 :             XLogFileName(fname, state->seg.ws_tli, segno, state->segcxt.ws_segsize);
    1385                 :             : 
    1386                 :           0 :             report_invalid_record(state,
    1387                 :             :                                   "out-of-sequence timeline ID %u (after %u) in WAL segment %s, LSN %X/%08X, offset %u",
    1388                 :             :                                   hdr->xlp_tli,
    1389                 :             :                                   state->latestPageTLI,
    1390                 :             :                                   fname,
    1391                 :           0 :                                   LSN_FORMAT_ARGS(recptr),
    1392                 :             :                                   offset);
    1393                 :           0 :             return false;
    1394                 :             :         }
    1395                 :             :     }
    1396                 :       49854 :     state->latestPagePtr = recptr;
    1397                 :       49854 :     state->latestPageTLI = hdr->xlp_tli;
    1398                 :             : 
    1399                 :       49854 :     return true;
    1400                 :             : }
    1401                 :             : 
    1402                 :             : /*
    1403                 :             :  * Forget about an error produced by XLogReaderValidatePageHeader().
    1404                 :             :  */
    1405                 :             : void
    1406                 :           0 : XLogReaderResetError(XLogReaderState *state)
    1407                 :             : {
    1408                 :           0 :     state->errormsg_buf[0] = '\0';
    1409                 :           0 :     state->errormsg_deferred = false;
    1410                 :           0 : }
    1411                 :             : 
    1412                 :             : /*
    1413                 :             :  * Find the first record with an lsn >= RecPtr.
    1414                 :             :  *
    1415                 :             :  * This is different from XLogBeginRead() in that RecPtr doesn't need to point
    1416                 :             :  * to a valid record boundary.  Useful for checking whether RecPtr is a valid
    1417                 :             :  * xlog address for reading, and to find the first valid address after some
    1418                 :             :  * address when dumping records for debugging purposes.
    1419                 :             :  *
    1420                 :             :  * This positions the reader, like XLogBeginRead(), so that the next call to
    1421                 :             :  * XLogReadRecord() will read the next valid record.
    1422                 :             :  *
    1423                 :             :  * On failure, InvalidXLogRecPtr is returned, and *errormsg is set to a string
    1424                 :             :  * with details of the failure.
    1425                 :             :  *
    1426                 :             :  * When set, *errormsg points to an internal buffer that's valid until the next
    1427                 :             :  * call to XLogReadRecord.
    1428                 :             :  */
    1429                 :             : XLogRecPtr
    1430                 :         120 : XLogFindNextRecord(XLogReaderState *state, XLogRecPtr RecPtr, char **errormsg)
    1431                 :             : {
    1432                 :             :     XLogRecPtr  tmpRecPtr;
    1433                 :         120 :     XLogRecPtr  found = InvalidXLogRecPtr;
    1434                 :             :     XLogPageHeader header;
    1435                 :             : 
    1436                 :         120 :     *errormsg = NULL;
    1437                 :             : 
    1438                 :             :     Assert(XLogRecPtrIsValid(RecPtr));
    1439                 :             : 
    1440                 :             :     /* Make sure ReadPageInternal() can't return XLREAD_WOULDBLOCK. */
    1441                 :         120 :     state->nonblocking = false;
    1442                 :             : 
    1443                 :             :     /*
    1444                 :             :      * skip over potential continuation data, keeping in mind that it may span
    1445                 :             :      * multiple pages
    1446                 :             :      */
    1447                 :         120 :     tmpRecPtr = RecPtr;
    1448                 :             :     while (true)
    1449                 :           0 :     {
    1450                 :             :         XLogRecPtr  targetPagePtr;
    1451                 :             :         int         targetRecOff;
    1452                 :             :         uint32      pageHeaderSize;
    1453                 :             :         int         readLen;
    1454                 :             : 
    1455                 :             :         /*
    1456                 :             :          * Compute targetRecOff. It should typically be equal or greater than
    1457                 :             :          * short page-header since a valid record can't start anywhere before
    1458                 :             :          * that, except when caller has explicitly specified the offset that
    1459                 :             :          * falls somewhere there or when we are skipping multi-page
    1460                 :             :          * continuation record. It doesn't matter though because
    1461                 :             :          * ReadPageInternal() is prepared to handle that and will read at
    1462                 :             :          * least short page-header worth of data
    1463                 :             :          */
    1464                 :         120 :         targetRecOff = tmpRecPtr % XLOG_BLCKSZ;
    1465                 :             : 
    1466                 :             :         /* scroll back to page boundary */
    1467                 :         120 :         targetPagePtr = tmpRecPtr - targetRecOff;
    1468                 :             : 
    1469                 :             :         /* Read the page containing the record */
    1470                 :         120 :         readLen = ReadPageInternal(state, targetPagePtr, targetRecOff);
    1471         [ +  + ]:         120 :         if (readLen < 0)
    1472                 :           1 :             goto err;
    1473                 :             : 
    1474                 :         119 :         header = (XLogPageHeader) state->readBuf;
    1475                 :             : 
    1476         [ +  + ]:         119 :         pageHeaderSize = XLogPageHeaderSize(header);
    1477                 :             : 
    1478                 :             :         /* make sure we have enough data for the page header */
    1479                 :         119 :         readLen = ReadPageInternal(state, targetPagePtr, pageHeaderSize);
    1480         [ -  + ]:         119 :         if (readLen < 0)
    1481                 :           0 :             goto err;
    1482                 :             : 
    1483                 :             :         /* skip over potential continuation data */
    1484         [ +  + ]:         119 :         if (header->xlp_info & XLP_FIRST_IS_CONTRECORD)
    1485                 :             :         {
    1486                 :             :             /*
    1487                 :             :              * If the length of the remaining continuation data is more than
    1488                 :             :              * what can fit in this page, the continuation record crosses over
    1489                 :             :              * this page. Read the next page and try again. xlp_rem_len in the
    1490                 :             :              * next page header will contain the remaining length of the
    1491                 :             :              * continuation data
    1492                 :             :              *
    1493                 :             :              * Note that record headers are MAXALIGN'ed
    1494                 :             :              */
    1495         [ -  + ]:          45 :             if (MAXALIGN(header->xlp_rem_len) >= (XLOG_BLCKSZ - pageHeaderSize))
    1496                 :           0 :                 tmpRecPtr = targetPagePtr + XLOG_BLCKSZ;
    1497                 :             :             else
    1498                 :             :             {
    1499                 :             :                 /*
    1500                 :             :                  * The previous continuation record ends in this page. Set
    1501                 :             :                  * tmpRecPtr to point to the first valid record
    1502                 :             :                  */
    1503                 :          45 :                 tmpRecPtr = targetPagePtr + pageHeaderSize
    1504                 :          45 :                     + MAXALIGN(header->xlp_rem_len);
    1505                 :          45 :                 break;
    1506                 :             :             }
    1507                 :             :         }
    1508                 :             :         else
    1509                 :             :         {
    1510                 :          74 :             tmpRecPtr = targetPagePtr + pageHeaderSize;
    1511                 :          74 :             break;
    1512                 :             :         }
    1513                 :             :     }
    1514                 :             : 
    1515                 :             :     /*
    1516                 :             :      * we know now that tmpRecPtr is an address pointing to a valid XLogRecord
    1517                 :             :      * because either we're at the first record after the beginning of a page
    1518                 :             :      * or we just jumped over the remaining data of a continuation.
    1519                 :             :      */
    1520                 :         119 :     XLogBeginRead(state, tmpRecPtr);
    1521         [ +  - ]:         545 :     while (XLogReadRecord(state, errormsg) != NULL)
    1522                 :             :     {
    1523                 :             :         /* past the record we've found, break out */
    1524         [ +  + ]:         545 :         if (RecPtr <= state->ReadRecPtr)
    1525                 :             :         {
    1526                 :             :             /* Rewind the reader to the beginning of the last record. */
    1527                 :         119 :             found = state->ReadRecPtr;
    1528                 :         119 :             XLogBeginRead(state, found);
    1529                 :         119 :             return found;
    1530                 :             :         }
    1531                 :             :     }
    1532                 :             : 
    1533                 :           0 : err:
    1534                 :           1 :     XLogReaderInvalReadState(state);
    1535                 :             : 
    1536                 :             :     /*
    1537                 :             :      * We may have reported errors due to invalid WAL header, propagate the
    1538                 :             :      * error message to the caller.
    1539                 :             :      */
    1540         [ +  - ]:           1 :     if (state->errormsg_deferred)
    1541                 :             :     {
    1542         [ +  - ]:           1 :         if (state->errormsg_buf[0] != '\0')
    1543                 :           1 :             *errormsg = state->errormsg_buf;
    1544                 :           1 :         state->errormsg_deferred = false;
    1545                 :             :     }
    1546                 :             : 
    1547                 :           1 :     return InvalidXLogRecPtr;
    1548                 :             : }
    1549                 :             : 
    1550                 :             : /*
    1551                 :             :  * Helper function to ease writing of XLogReaderRoutine->page_read callbacks.
    1552                 :             :  * If this function is used, caller must supply a segment_open callback in
    1553                 :             :  * 'state', as that is used here.
    1554                 :             :  *
    1555                 :             :  * Read 'count' bytes into 'buf', starting at location 'startptr', from WAL
    1556                 :             :  * fetched from timeline 'tli'.
    1557                 :             :  *
    1558                 :             :  * Returns true if succeeded, false if an error occurs, in which case
    1559                 :             :  * 'errinfo' receives error details.
    1560                 :             :  */
    1561                 :             : bool
    1562                 :       21443 : WALRead(XLogReaderState *state,
    1563                 :             :         char *buf, XLogRecPtr startptr, Size count, TimeLineID tli,
    1564                 :             :         WALReadError *errinfo)
    1565                 :             : {
    1566                 :             :     char       *p;
    1567                 :             :     XLogRecPtr  recptr;
    1568                 :             :     Size        nbytes;
    1569                 :             : #ifndef FRONTEND
    1570                 :             :     instr_time  io_start;
    1571                 :             : #endif
    1572                 :             : 
    1573                 :       21443 :     p = buf;
    1574                 :       21443 :     recptr = startptr;
    1575                 :       21443 :     nbytes = count;
    1576                 :             : 
    1577         [ +  + ]:       42886 :     while (nbytes > 0)
    1578                 :             :     {
    1579                 :             :         uint32      startoff;
    1580                 :             :         size_t      segbytes;
    1581                 :             :         ssize_t     readbytes;
    1582                 :             : 
    1583                 :       21443 :         startoff = XLogSegmentOffset(recptr, state->segcxt.ws_segsize);
    1584                 :             : 
    1585                 :             :         /*
    1586                 :             :          * If the data we want is not in a segment we have open, close what we
    1587                 :             :          * have (if anything) and open the next one, using the caller's
    1588                 :             :          * provided segment_open callback.
    1589                 :             :          */
    1590         [ +  + ]:       21443 :         if (state->seg.ws_file < 0 ||
    1591         [ +  + ]:       21375 :             !XLByteInSeg(recptr, state->seg.ws_segno, state->segcxt.ws_segsize) ||
    1592         [ -  + ]:       21356 :             tli != state->seg.ws_tli)
    1593                 :             :         {
    1594                 :             :             XLogSegNo   nextSegNo;
    1595                 :             : 
    1596         [ +  + ]:          87 :             if (state->seg.ws_file >= 0)
    1597                 :          19 :                 state->routine.segment_close(state);
    1598                 :             : 
    1599                 :          87 :             XLByteToSeg(recptr, nextSegNo, state->segcxt.ws_segsize);
    1600                 :          87 :             state->routine.segment_open(state, nextSegNo, &tli);
    1601                 :             : 
    1602                 :             :             /* This shouldn't happen -- indicates a bug in segment_open */
    1603                 :             :             Assert(state->seg.ws_file >= 0);
    1604                 :             : 
    1605                 :             :             /* Update the current segment info. */
    1606                 :          87 :             state->seg.ws_tli = tli;
    1607                 :          87 :             state->seg.ws_segno = nextSegNo;
    1608                 :             :         }
    1609                 :             : 
    1610                 :             :         /* How many bytes are within this segment? */
    1611         [ -  + ]:       21443 :         if (nbytes > (state->segcxt.ws_segsize - startoff))
    1612                 :           0 :             segbytes = state->segcxt.ws_segsize - startoff;
    1613                 :             :         else
    1614                 :       21443 :             segbytes = nbytes;
    1615                 :             : 
    1616                 :             : #ifndef FRONTEND
    1617                 :             :         /* Measure I/O timing when reading segment */
    1618                 :             :         io_start = pgstat_prepare_io_time(track_wal_io_timing);
    1619                 :             : 
    1620                 :             :         pgstat_report_wait_start(WAIT_EVENT_WAL_READ);
    1621                 :             : #endif
    1622                 :             : 
    1623                 :             :         /* Reset errno first; eases reporting non-errno-affecting errors */
    1624                 :       21443 :         errno = 0;
    1625                 :       21443 :         readbytes = pg_pread(state->seg.ws_file, p, segbytes, (pgoff_t) startoff);
    1626                 :             : 
    1627                 :             : #ifndef FRONTEND
    1628                 :             :         pgstat_report_wait_end();
    1629                 :             : #endif
    1630                 :             : 
    1631         [ -  + ]:       21443 :         if (readbytes <= 0)
    1632                 :             :         {
    1633                 :           0 :             errinfo->wre_errno = errno;
    1634                 :           0 :             errinfo->wre_req = segbytes;
    1635                 :           0 :             errinfo->wre_read = readbytes;
    1636                 :           0 :             errinfo->wre_off = startoff;
    1637                 :           0 :             errinfo->wre_seg = state->seg;
    1638                 :           0 :             return false;
    1639                 :             :         }
    1640                 :             : 
    1641                 :             : #ifndef FRONTEND
    1642                 :             :         pgstat_count_io_op_time(IOOBJECT_WAL, IOCONTEXT_NORMAL, IOOP_READ,
    1643                 :             :                                 io_start, 1, readbytes);
    1644                 :             : #endif
    1645                 :             : 
    1646                 :             :         /* Update state for read */
    1647                 :       21443 :         recptr += readbytes;
    1648                 :       21443 :         nbytes -= readbytes;
    1649                 :       21443 :         p += readbytes;
    1650                 :             :     }
    1651                 :             : 
    1652                 :       21443 :     return true;
    1653                 :             : }
    1654                 :             : 
    1655                 :             : /* ----------------------------------------
    1656                 :             :  * Functions for decoding the data and block references in a record.
    1657                 :             :  * ----------------------------------------
    1658                 :             :  */
    1659                 :             : 
    1660                 :             : /*
    1661                 :             :  * Private function to reset the state, forgetting all decoded records, if we
    1662                 :             :  * are asked to move to a new read position.
    1663                 :             :  */
    1664                 :             : static void
    1665                 :         238 : ResetDecoder(XLogReaderState *state)
    1666                 :             : {
    1667                 :             :     DecodedXLogRecord *r;
    1668                 :             : 
    1669                 :             :     /* Reset the decoded record queue, freeing any oversized records. */
    1670         [ +  + ]:         595 :     while ((r = state->decode_queue_head) != NULL)
    1671                 :             :     {
    1672                 :         119 :         state->decode_queue_head = r->next;
    1673         [ +  + ]:         119 :         if (r->oversized)
    1674                 :           3 :             pfree(r);
    1675                 :             :     }
    1676                 :         238 :     state->decode_queue_tail = NULL;
    1677                 :         238 :     state->decode_queue_head = NULL;
    1678                 :         238 :     state->record = NULL;
    1679                 :             : 
    1680                 :             :     /* Reset the decode buffer to empty. */
    1681                 :         238 :     state->decode_buffer_tail = state->decode_buffer;
    1682                 :         238 :     state->decode_buffer_head = state->decode_buffer;
    1683                 :             : 
    1684                 :             :     /* Clear error state. */
    1685                 :         238 :     state->errormsg_buf[0] = '\0';
    1686                 :         238 :     state->errormsg_deferred = false;
    1687                 :         238 : }
    1688                 :             : 
    1689                 :             : /*
    1690                 :             :  * Compute the maximum possible amount of padding that could be required to
    1691                 :             :  * decode a record, given xl_tot_len from the record's header.  This is the
    1692                 :             :  * amount of output buffer space that we need to decode a record, though we
    1693                 :             :  * might not finish up using it all.
    1694                 :             :  *
    1695                 :             :  * This computation is pessimistic and assumes the maximum possible number of
    1696                 :             :  * blocks, due to lack of better information.
    1697                 :             :  */
    1698                 :             : size_t
    1699                 :     1572253 : DecodeXLogRecordRequiredSpace(size_t xl_tot_len)
    1700                 :             : {
    1701                 :     1572253 :     size_t      size = 0;
    1702                 :             : 
    1703                 :             :     /* Account for the fixed size part of the decoded record struct. */
    1704                 :     1572253 :     size += offsetof(DecodedXLogRecord, blocks[0]);
    1705                 :             :     /* Account for the flexible blocks array of maximum possible size. */
    1706                 :     1572253 :     size += sizeof(DecodedBkpBlock) * (XLR_MAX_BLOCK_ID + 1);
    1707                 :             :     /* Account for all the raw main and block data. */
    1708                 :     1572253 :     size += xl_tot_len;
    1709                 :             :     /* We might insert padding before main_data. */
    1710                 :     1572253 :     size += (MAXIMUM_ALIGNOF - 1);
    1711                 :             :     /* We might insert padding before each block's data. */
    1712                 :     1572253 :     size += (MAXIMUM_ALIGNOF - 1) * (XLR_MAX_BLOCK_ID + 1);
    1713                 :             :     /* We might insert padding at the end. */
    1714                 :     1572253 :     size += (MAXIMUM_ALIGNOF - 1);
    1715                 :             : 
    1716                 :     1572253 :     return size;
    1717                 :             : }
    1718                 :             : 
    1719                 :             : /*
    1720                 :             :  * Decode a record.  "decoded" must point to a MAXALIGNed memory area that has
    1721                 :             :  * space for at least DecodeXLogRecordRequiredSpace(record) bytes.  On
    1722                 :             :  * success, decoded->size contains the actual space occupied by the decoded
    1723                 :             :  * record, which may turn out to be less.
    1724                 :             :  *
    1725                 :             :  * Only decoded->oversized member must be initialized already, and will not be
    1726                 :             :  * modified.  Other members will be initialized as required.
    1727                 :             :  *
    1728                 :             :  * On error, a human-readable error message is returned in *errormsg, and
    1729                 :             :  * the return value is false.
    1730                 :             :  */
    1731                 :             : bool
    1732                 :     1572193 : DecodeXLogRecord(XLogReaderState *state,
    1733                 :             :                  DecodedXLogRecord *decoded,
    1734                 :             :                  XLogRecord *record,
    1735                 :             :                  XLogRecPtr lsn,
    1736                 :             :                  char **errormsg)
    1737                 :             : {
    1738                 :             :     /*
    1739                 :             :      * read next _size bytes from record buffer, but check for overrun first.
    1740                 :             :      */
    1741                 :             : #define COPY_HEADER_FIELD(_dst, _size)          \
    1742                 :             :     do {                                        \
    1743                 :             :         if (remaining < _size)                   \
    1744                 :             :             goto shortdata_err;                 \
    1745                 :             :         memcpy(_dst, ptr, _size);               \
    1746                 :             :         ptr += _size;                           \
    1747                 :             :         remaining -= _size;                     \
    1748                 :             :     } while(0)
    1749                 :             : 
    1750                 :             :     char       *ptr;
    1751                 :             :     char       *out;
    1752                 :             :     uint32      remaining;
    1753                 :             :     uint32      datatotal;
    1754                 :     1572193 :     RelFileLocator *rlocator = NULL;
    1755                 :             :     uint8       block_id;
    1756                 :             : 
    1757                 :     1572193 :     decoded->header = *record;
    1758                 :     1572193 :     decoded->lsn = lsn;
    1759                 :     1572193 :     decoded->next = NULL;
    1760                 :     1572193 :     decoded->record_origin = InvalidReplOriginId;
    1761                 :     1572193 :     decoded->toplevel_xid = InvalidTransactionId;
    1762                 :     1572193 :     decoded->main_data = NULL;
    1763                 :     1572193 :     decoded->main_data_len = 0;
    1764                 :     1572193 :     decoded->max_block_id = -1;
    1765                 :     1572193 :     ptr = (char *) record;
    1766                 :     1572193 :     ptr += SizeOfXLogRecord;
    1767                 :     1572193 :     remaining = record->xl_tot_len - SizeOfXLogRecord;
    1768                 :             : 
    1769                 :             :     /* Decode the headers */
    1770                 :     1572193 :     datatotal = 0;
    1771         [ +  + ]:     3365046 :     while (remaining > datatotal)
    1772                 :             :     {
    1773         [ -  + ]:     3323277 :         COPY_HEADER_FIELD(&block_id, sizeof(uint8));
    1774                 :             : 
    1775         [ +  + ]:     3323277 :         if (block_id == XLR_BLOCK_ID_DATA_SHORT)
    1776                 :             :         {
    1777                 :             :             /* XLogRecordDataHeaderShort */
    1778                 :             :             uint8       main_data_len;
    1779                 :             : 
    1780         [ -  + ]:     1528783 :             COPY_HEADER_FIELD(&main_data_len, sizeof(uint8));
    1781                 :             : 
    1782                 :     1528783 :             decoded->main_data_len = main_data_len;
    1783                 :     1528783 :             datatotal += main_data_len;
    1784                 :     1528783 :             break;              /* by convention, the main data fragment is
    1785                 :             :                                  * always last */
    1786                 :             :         }
    1787         [ +  + ]:     1794494 :         else if (block_id == XLR_BLOCK_ID_DATA_LONG)
    1788                 :             :         {
    1789                 :             :             /* XLogRecordDataHeaderLong */
    1790                 :             :             uint32      main_data_len;
    1791                 :             : 
    1792         [ -  + ]:        1641 :             COPY_HEADER_FIELD(&main_data_len, sizeof(uint32));
    1793                 :        1641 :             decoded->main_data_len = main_data_len;
    1794                 :        1641 :             datatotal += main_data_len;
    1795                 :        1641 :             break;              /* by convention, the main data fragment is
    1796                 :             :                                  * always last */
    1797                 :             :         }
    1798         [ -  + ]:     1792853 :         else if (block_id == XLR_BLOCK_ID_ORIGIN)
    1799                 :             :         {
    1800         [ #  # ]:           0 :             COPY_HEADER_FIELD(&decoded->record_origin, sizeof(ReplOriginId));
    1801                 :             :         }
    1802         [ -  + ]:     1792853 :         else if (block_id == XLR_BLOCK_ID_TOPLEVEL_XID)
    1803                 :             :         {
    1804         [ #  # ]:           0 :             COPY_HEADER_FIELD(&decoded->toplevel_xid, sizeof(TransactionId));
    1805                 :             :         }
    1806         [ +  - ]:     1792853 :         else if (block_id <= XLR_MAX_BLOCK_ID)
    1807                 :             :         {
    1808                 :             :             /* XLogRecordBlockHeader */
    1809                 :             :             DecodedBkpBlock *blk;
    1810                 :             :             uint8       fork_flags;
    1811                 :             : 
    1812                 :             :             /* mark any intervening block IDs as not in use */
    1813         [ +  + ]:     1793268 :             for (int i = decoded->max_block_id + 1; i < block_id; ++i)
    1814                 :         415 :                 decoded->blocks[i].in_use = false;
    1815                 :             : 
    1816         [ -  + ]:     1792853 :             if (block_id <= decoded->max_block_id)
    1817                 :             :             {
    1818                 :           0 :                 report_invalid_record(state,
    1819                 :             :                                       "out-of-order block_id %u at %X/%08X",
    1820                 :             :                                       block_id,
    1821                 :           0 :                                       LSN_FORMAT_ARGS(state->ReadRecPtr));
    1822                 :           0 :                 goto err;
    1823                 :             :             }
    1824                 :     1792853 :             decoded->max_block_id = block_id;
    1825                 :             : 
    1826                 :     1792853 :             blk = &decoded->blocks[block_id];
    1827                 :     1792853 :             blk->in_use = true;
    1828                 :     1792853 :             blk->apply_image = false;
    1829                 :             : 
    1830         [ -  + ]:     1792853 :             COPY_HEADER_FIELD(&fork_flags, sizeof(uint8));
    1831                 :     1792853 :             blk->forknum = fork_flags & BKPBLOCK_FORK_MASK;
    1832                 :     1792853 :             blk->flags = fork_flags;
    1833                 :     1792853 :             blk->has_image = ((fork_flags & BKPBLOCK_HAS_IMAGE) != 0);
    1834                 :     1792853 :             blk->has_data = ((fork_flags & BKPBLOCK_HAS_DATA) != 0);
    1835                 :             : 
    1836                 :     1792853 :             blk->prefetch_buffer = InvalidBuffer;
    1837                 :             : 
    1838         [ -  + ]:     1792853 :             COPY_HEADER_FIELD(&blk->data_len, sizeof(uint16));
    1839                 :             :             /* cross-check that the HAS_DATA flag is set iff data_length > 0 */
    1840   [ +  +  -  + ]:     1792853 :             if (blk->has_data && blk->data_len == 0)
    1841                 :             :             {
    1842                 :           0 :                 report_invalid_record(state,
    1843                 :             :                                       "BKPBLOCK_HAS_DATA set, but no data included at %X/%08X",
    1844                 :           0 :                                       LSN_FORMAT_ARGS(state->ReadRecPtr));
    1845                 :           0 :                 goto err;
    1846                 :             :             }
    1847   [ +  +  -  + ]:     1792853 :             if (!blk->has_data && blk->data_len != 0)
    1848                 :             :             {
    1849                 :           0 :                 report_invalid_record(state,
    1850                 :             :                                       "BKPBLOCK_HAS_DATA not set, but data length is %d at %X/%08X",
    1851                 :           0 :                                       blk->data_len,
    1852                 :           0 :                                       LSN_FORMAT_ARGS(state->ReadRecPtr));
    1853                 :           0 :                 goto err;
    1854                 :             :             }
    1855                 :     1792853 :             datatotal += blk->data_len;
    1856                 :             : 
    1857         [ +  + ]:     1792853 :             if (blk->has_image)
    1858                 :             :             {
    1859         [ -  + ]:       46688 :                 COPY_HEADER_FIELD(&blk->bimg_len, sizeof(uint16));
    1860         [ -  + ]:       46688 :                 COPY_HEADER_FIELD(&blk->hole_offset, sizeof(uint16));
    1861         [ -  + ]:       46688 :                 COPY_HEADER_FIELD(&blk->bimg_info, sizeof(uint8));
    1862                 :             : 
    1863                 :       46688 :                 blk->apply_image = ((blk->bimg_info & BKPIMAGE_APPLY) != 0);
    1864                 :             : 
    1865         [ -  + ]:       46688 :                 if (BKPIMAGE_COMPRESSED(blk->bimg_info))
    1866                 :             :                 {
    1867         [ #  # ]:           0 :                     if (blk->bimg_info & BKPIMAGE_HAS_HOLE)
    1868         [ #  # ]:           0 :                         COPY_HEADER_FIELD(&blk->hole_length, sizeof(uint16));
    1869                 :             :                     else
    1870                 :           0 :                         blk->hole_length = 0;
    1871                 :             :                 }
    1872                 :             :                 else
    1873                 :       46688 :                     blk->hole_length = BLCKSZ - blk->bimg_len;
    1874                 :       46688 :                 datatotal += blk->bimg_len;
    1875                 :             : 
    1876                 :             :                 /*
    1877                 :             :                  * cross-check that hole_offset > 0, hole_length > 0 and
    1878                 :             :                  * bimg_len < BLCKSZ if the HAS_HOLE flag is set.
    1879                 :             :                  */
    1880         [ +  + ]:       46688 :                 if ((blk->bimg_info & BKPIMAGE_HAS_HOLE) &&
    1881         [ +  - ]:       43238 :                     (blk->hole_offset == 0 ||
    1882         [ +  - ]:       43238 :                      blk->hole_length == 0 ||
    1883         [ -  + ]:       43238 :                      blk->bimg_len == BLCKSZ))
    1884                 :             :                 {
    1885                 :           0 :                     report_invalid_record(state,
    1886                 :             :                                           "BKPIMAGE_HAS_HOLE set, but hole offset %d length %d block image length %d at %X/%08X",
    1887                 :           0 :                                           blk->hole_offset,
    1888                 :           0 :                                           blk->hole_length,
    1889                 :           0 :                                           blk->bimg_len,
    1890                 :           0 :                                           LSN_FORMAT_ARGS(state->ReadRecPtr));
    1891                 :           0 :                     goto err;
    1892                 :             :                 }
    1893                 :             : 
    1894                 :             :                 /*
    1895                 :             :                  * cross-check that hole_offset == 0 and hole_length == 0 if
    1896                 :             :                  * the HAS_HOLE flag is not set.
    1897                 :             :                  */
    1898         [ +  + ]:       46688 :                 if (!(blk->bimg_info & BKPIMAGE_HAS_HOLE) &&
    1899   [ +  -  -  + ]:        3450 :                     (blk->hole_offset != 0 || blk->hole_length != 0))
    1900                 :             :                 {
    1901                 :           0 :                     report_invalid_record(state,
    1902                 :             :                                           "BKPIMAGE_HAS_HOLE not set, but hole offset %d length %d at %X/%08X",
    1903                 :           0 :                                           blk->hole_offset,
    1904                 :           0 :                                           blk->hole_length,
    1905                 :           0 :                                           LSN_FORMAT_ARGS(state->ReadRecPtr));
    1906                 :           0 :                     goto err;
    1907                 :             :                 }
    1908                 :             : 
    1909                 :             :                 /*
    1910                 :             :                  * Cross-check that bimg_len < BLCKSZ if it is compressed.
    1911                 :             :                  */
    1912         [ -  + ]:       46688 :                 if (BKPIMAGE_COMPRESSED(blk->bimg_info) &&
    1913         [ #  # ]:           0 :                     blk->bimg_len == BLCKSZ)
    1914                 :             :                 {
    1915                 :           0 :                     report_invalid_record(state,
    1916                 :             :                                           "BKPIMAGE_COMPRESSED set, but block image length %d at %X/%08X",
    1917                 :           0 :                                           blk->bimg_len,
    1918                 :           0 :                                           LSN_FORMAT_ARGS(state->ReadRecPtr));
    1919                 :           0 :                     goto err;
    1920                 :             :                 }
    1921                 :             : 
    1922                 :             :                 /*
    1923                 :             :                  * cross-check that bimg_len = BLCKSZ if neither HAS_HOLE is
    1924                 :             :                  * set nor COMPRESSED().
    1925                 :             :                  */
    1926         [ +  + ]:       46688 :                 if (!(blk->bimg_info & BKPIMAGE_HAS_HOLE) &&
    1927         [ +  - ]:        3450 :                     !BKPIMAGE_COMPRESSED(blk->bimg_info) &&
    1928         [ -  + ]:        3450 :                     blk->bimg_len != BLCKSZ)
    1929                 :             :                 {
    1930                 :           0 :                     report_invalid_record(state,
    1931                 :             :                                           "neither BKPIMAGE_HAS_HOLE nor BKPIMAGE_COMPRESSED set, but block image length is %d at %X/%08X",
    1932                 :           0 :                                           blk->data_len,
    1933                 :           0 :                                           LSN_FORMAT_ARGS(state->ReadRecPtr));
    1934                 :           0 :                     goto err;
    1935                 :             :                 }
    1936                 :             :             }
    1937         [ +  + ]:     1792853 :             if (!(fork_flags & BKPBLOCK_SAME_REL))
    1938                 :             :             {
    1939         [ -  + ]:     1527895 :                 COPY_HEADER_FIELD(&blk->rlocator, sizeof(RelFileLocator));
    1940                 :     1527895 :                 rlocator = &blk->rlocator;
    1941                 :             :             }
    1942                 :             :             else
    1943                 :             :             {
    1944         [ -  + ]:      264958 :                 if (rlocator == NULL)
    1945                 :             :                 {
    1946                 :           0 :                     report_invalid_record(state,
    1947                 :             :                                           "BKPBLOCK_SAME_REL set but no previous rel at %X/%08X",
    1948                 :           0 :                                           LSN_FORMAT_ARGS(state->ReadRecPtr));
    1949                 :           0 :                     goto err;
    1950                 :             :                 }
    1951                 :             : 
    1952                 :      264958 :                 blk->rlocator = *rlocator;
    1953                 :             :             }
    1954         [ -  + ]:     1792853 :             COPY_HEADER_FIELD(&blk->blkno, sizeof(BlockNumber));
    1955                 :             :         }
    1956                 :             :         else
    1957                 :             :         {
    1958                 :           0 :             report_invalid_record(state,
    1959                 :             :                                   "invalid block_id %u at %X/%08X",
    1960                 :           0 :                                   block_id, LSN_FORMAT_ARGS(state->ReadRecPtr));
    1961                 :           0 :             goto err;
    1962                 :             :         }
    1963                 :             :     }
    1964                 :             : 
    1965         [ -  + ]:     1572193 :     if (remaining != datatotal)
    1966                 :           0 :         goto shortdata_err;
    1967                 :             : 
    1968                 :             :     /*
    1969                 :             :      * Ok, we've parsed the fragment headers, and verified that the total
    1970                 :             :      * length of the payload in the fragments is equal to the amount of data
    1971                 :             :      * left.  Copy the data of each fragment to contiguous space after the
    1972                 :             :      * blocks array, inserting alignment padding before the data fragments so
    1973                 :             :      * they can be cast to struct pointers by REDO routines.
    1974                 :             :      */
    1975                 :     1572193 :     out = ((char *) decoded) +
    1976                 :     1572193 :         offsetof(DecodedXLogRecord, blocks) +
    1977                 :     1572193 :         sizeof(decoded->blocks[0]) * (decoded->max_block_id + 1);
    1978                 :             : 
    1979                 :             :     /* block data first */
    1980         [ +  + ]:     3365461 :     for (block_id = 0; block_id <= decoded->max_block_id; block_id++)
    1981                 :             :     {
    1982                 :     1793268 :         DecodedBkpBlock *blk = &decoded->blocks[block_id];
    1983                 :             : 
    1984         [ +  + ]:     1793268 :         if (!blk->in_use)
    1985                 :         415 :             continue;
    1986                 :             : 
    1987                 :             :         Assert(blk->has_image || !blk->apply_image);
    1988                 :             : 
    1989         [ +  + ]:     1792853 :         if (blk->has_image)
    1990                 :             :         {
    1991                 :             :             /* no need to align image */
    1992                 :       46688 :             blk->bkp_image = out;
    1993                 :       46688 :             memcpy(out, ptr, blk->bimg_len);
    1994                 :       46688 :             ptr += blk->bimg_len;
    1995                 :       46688 :             out += blk->bimg_len;
    1996                 :             :         }
    1997         [ +  + ]:     1792853 :         if (blk->has_data)
    1998                 :             :         {
    1999                 :     1281120 :             out = (char *) MAXALIGN(out);
    2000                 :     1281120 :             blk->data = out;
    2001                 :     1281120 :             memcpy(blk->data, ptr, blk->data_len);
    2002                 :     1281120 :             ptr += blk->data_len;
    2003                 :     1281120 :             out += blk->data_len;
    2004                 :             :         }
    2005                 :             :     }
    2006                 :             : 
    2007                 :             :     /* and finally, the main data */
    2008         [ +  + ]:     1572193 :     if (decoded->main_data_len > 0)
    2009                 :             :     {
    2010                 :     1530424 :         out = (char *) MAXALIGN(out);
    2011                 :     1530424 :         decoded->main_data = out;
    2012                 :     1530424 :         memcpy(decoded->main_data, ptr, decoded->main_data_len);
    2013                 :     1530424 :         ptr += decoded->main_data_len;
    2014                 :     1530424 :         out += decoded->main_data_len;
    2015                 :             :     }
    2016                 :             : 
    2017                 :             :     /* Report the actual size we used. */
    2018                 :     1572193 :     decoded->size = MAXALIGN(out - (char *) decoded);
    2019                 :             :     Assert(DecodeXLogRecordRequiredSpace(record->xl_tot_len) >=
    2020                 :             :            decoded->size);
    2021                 :             : 
    2022                 :     1572193 :     return true;
    2023                 :             : 
    2024                 :           0 : shortdata_err:
    2025                 :           0 :     report_invalid_record(state,
    2026                 :             :                           "record with invalid length at %X/%08X",
    2027                 :           0 :                           LSN_FORMAT_ARGS(state->ReadRecPtr));
    2028                 :           0 : err:
    2029                 :           0 :     *errormsg = state->errormsg_buf;
    2030                 :             : 
    2031                 :           0 :     return false;
    2032                 :             : }
    2033                 :             : 
    2034                 :             : /*
    2035                 :             :  * Returns information about the block that a block reference refers to.
    2036                 :             :  *
    2037                 :             :  * This is like XLogRecGetBlockTagExtended, except that the block reference
    2038                 :             :  * must exist and there's no access to prefetch_buffer.
    2039                 :             :  */
    2040                 :             : void
    2041                 :           0 : XLogRecGetBlockTag(XLogReaderState *record, uint8 block_id,
    2042                 :             :                    RelFileLocator *rlocator, ForkNumber *forknum,
    2043                 :             :                    BlockNumber *blknum)
    2044                 :             : {
    2045         [ #  # ]:           0 :     if (!XLogRecGetBlockTagExtended(record, block_id, rlocator, forknum,
    2046                 :             :                                     blknum, NULL))
    2047                 :             :     {
    2048                 :             : #ifndef FRONTEND
    2049                 :             :         elog(ERROR, "could not locate backup block with ID %d in WAL record",
    2050                 :             :              block_id);
    2051                 :             : #else
    2052                 :           0 :         pg_fatal("could not locate backup block with ID %d in WAL record",
    2053                 :             :                  block_id);
    2054                 :             : #endif
    2055                 :             :     }
    2056                 :           0 : }
    2057                 :             : 
    2058                 :             : /*
    2059                 :             :  * Returns information about the block that a block reference refers to,
    2060                 :             :  * optionally including the buffer that the block may already be in.
    2061                 :             :  *
    2062                 :             :  * If the WAL record contains a block reference with the given ID, *rlocator,
    2063                 :             :  * *forknum, *blknum and *prefetch_buffer are filled in (if not NULL), and
    2064                 :             :  * returns true.  Otherwise returns false.
    2065                 :             :  */
    2066                 :             : bool
    2067                 :     1083317 : XLogRecGetBlockTagExtended(XLogReaderState *record, uint8 block_id,
    2068                 :             :                            RelFileLocator *rlocator, ForkNumber *forknum,
    2069                 :             :                            BlockNumber *blknum,
    2070                 :             :                            Buffer *prefetch_buffer)
    2071                 :             : {
    2072                 :             :     DecodedBkpBlock *bkpb;
    2073                 :             : 
    2074   [ +  -  +  + ]:     1083317 :     if (!XLogRecHasBlockRef(record, block_id))
    2075                 :         273 :         return false;
    2076                 :             : 
    2077                 :     1083044 :     bkpb = &record->record->blocks[block_id];
    2078         [ +  - ]:     1083044 :     if (rlocator)
    2079                 :     1083044 :         *rlocator = bkpb->rlocator;
    2080         [ +  - ]:     1083044 :     if (forknum)
    2081                 :     1083044 :         *forknum = bkpb->forknum;
    2082         [ +  - ]:     1083044 :     if (blknum)
    2083                 :     1083044 :         *blknum = bkpb->blkno;
    2084         [ -  + ]:     1083044 :     if (prefetch_buffer)
    2085                 :           0 :         *prefetch_buffer = bkpb->prefetch_buffer;
    2086                 :     1083044 :     return true;
    2087                 :             : }
    2088                 :             : 
    2089                 :             : /*
    2090                 :             :  * Returns the data associated with a block reference, or NULL if there is
    2091                 :             :  * no data (e.g. because a full-page image was taken instead). The returned
    2092                 :             :  * pointer points to a MAXALIGNed buffer.
    2093                 :             :  */
    2094                 :             : char *
    2095                 :        2052 : XLogRecGetBlockData(XLogReaderState *record, uint8 block_id, Size *len)
    2096                 :             : {
    2097                 :             :     DecodedBkpBlock *bkpb;
    2098                 :             : 
    2099         [ +  - ]:        2052 :     if (block_id > record->record->max_block_id ||
    2100         [ -  + ]:        2052 :         !record->record->blocks[block_id].in_use)
    2101                 :           0 :         return NULL;
    2102                 :             : 
    2103                 :        2052 :     bkpb = &record->record->blocks[block_id];
    2104                 :             : 
    2105         [ -  + ]:        2052 :     if (!bkpb->has_data)
    2106                 :             :     {
    2107         [ #  # ]:           0 :         if (len)
    2108                 :           0 :             *len = 0;
    2109                 :           0 :         return NULL;
    2110                 :             :     }
    2111                 :             :     else
    2112                 :             :     {
    2113         [ +  + ]:        2052 :         if (len)
    2114                 :        1815 :             *len = bkpb->data_len;
    2115                 :        2052 :         return bkpb->data;
    2116                 :             :     }
    2117                 :             : }
    2118                 :             : 
    2119                 :             : /*
    2120                 :             :  * Restore a full-page image from a backup block attached to an XLOG record.
    2121                 :             :  *
    2122                 :             :  * Returns true if a full-page image is restored, and false on failure with
    2123                 :             :  * an error to be consumed by the caller.
    2124                 :             :  */
    2125                 :             : bool
    2126                 :           1 : RestoreBlockImage(XLogReaderState *record, uint8 block_id, char *page)
    2127                 :             : {
    2128                 :             :     DecodedBkpBlock *bkpb;
    2129                 :             :     char       *ptr;
    2130                 :             :     PGAlignedBlock tmp;
    2131                 :             : 
    2132         [ +  - ]:           1 :     if (block_id > record->record->max_block_id ||
    2133         [ -  + ]:           1 :         !record->record->blocks[block_id].in_use)
    2134                 :             :     {
    2135                 :           0 :         report_invalid_record(record,
    2136                 :             :                               "could not restore image at %X/%08X with invalid block %d specified",
    2137                 :           0 :                               LSN_FORMAT_ARGS(record->ReadRecPtr),
    2138                 :             :                               block_id);
    2139                 :           0 :         return false;
    2140                 :             :     }
    2141         [ -  + ]:           1 :     if (!record->record->blocks[block_id].has_image)
    2142                 :             :     {
    2143                 :           0 :         report_invalid_record(record, "could not restore image at %X/%08X with invalid state, block %d",
    2144                 :           0 :                               LSN_FORMAT_ARGS(record->ReadRecPtr),
    2145                 :             :                               block_id);
    2146                 :           0 :         return false;
    2147                 :             :     }
    2148                 :             : 
    2149                 :           1 :     bkpb = &record->record->blocks[block_id];
    2150                 :           1 :     ptr = bkpb->bkp_image;
    2151                 :             : 
    2152         [ -  + ]:           1 :     if (BKPIMAGE_COMPRESSED(bkpb->bimg_info))
    2153                 :             :     {
    2154                 :             :         /* If a backup block image is compressed, decompress it */
    2155                 :           0 :         bool        decomp_success = true;
    2156                 :             : 
    2157         [ #  # ]:           0 :         if ((bkpb->bimg_info & BKPIMAGE_COMPRESS_PGLZ) != 0)
    2158                 :             :         {
    2159         [ #  # ]:           0 :             if (pglz_decompress(ptr, bkpb->bimg_len, tmp.data,
    2160                 :           0 :                                 BLCKSZ - bkpb->hole_length, true) < 0)
    2161                 :           0 :                 decomp_success = false;
    2162                 :             :         }
    2163         [ #  # ]:           0 :         else if ((bkpb->bimg_info & BKPIMAGE_COMPRESS_LZ4) != 0)
    2164                 :             :         {
    2165                 :             : #ifdef USE_LZ4
    2166         [ #  # ]:           0 :             if (LZ4_decompress_safe(ptr, tmp.data,
    2167                 :           0 :                                     bkpb->bimg_len, BLCKSZ - bkpb->hole_length) <= 0)
    2168                 :           0 :                 decomp_success = false;
    2169                 :             : #else
    2170                 :             :             report_invalid_record(record, "could not restore image at %X/%08X compressed with %s not supported by build, block %d",
    2171                 :             :                                   LSN_FORMAT_ARGS(record->ReadRecPtr),
    2172                 :             :                                   "LZ4",
    2173                 :             :                                   block_id);
    2174                 :             :             return false;
    2175                 :             : #endif
    2176                 :             :         }
    2177         [ #  # ]:           0 :         else if ((bkpb->bimg_info & BKPIMAGE_COMPRESS_ZSTD) != 0)
    2178                 :             :         {
    2179                 :             : #ifdef USE_ZSTD
    2180                 :             :             size_t      decomp_result = ZSTD_decompress(tmp.data,
    2181                 :             :                                                         BLCKSZ - bkpb->hole_length,
    2182                 :             :                                                         ptr, bkpb->bimg_len);
    2183                 :             : 
    2184                 :             :             if (ZSTD_isError(decomp_result))
    2185                 :             :                 decomp_success = false;
    2186                 :             : #else
    2187                 :           0 :             report_invalid_record(record, "could not restore image at %X/%08X compressed with %s not supported by build, block %d",
    2188                 :           0 :                                   LSN_FORMAT_ARGS(record->ReadRecPtr),
    2189                 :             :                                   "zstd",
    2190                 :             :                                   block_id);
    2191                 :           0 :             return false;
    2192                 :             : #endif
    2193                 :             :         }
    2194                 :             :         else
    2195                 :             :         {
    2196                 :           0 :             report_invalid_record(record, "could not restore image at %X/%08X compressed with unknown method, block %d",
    2197                 :           0 :                                   LSN_FORMAT_ARGS(record->ReadRecPtr),
    2198                 :             :                                   block_id);
    2199                 :           0 :             return false;
    2200                 :             :         }
    2201                 :             : 
    2202         [ #  # ]:           0 :         if (!decomp_success)
    2203                 :             :         {
    2204                 :           0 :             report_invalid_record(record, "could not decompress image at %X/%08X, block %d",
    2205                 :           0 :                                   LSN_FORMAT_ARGS(record->ReadRecPtr),
    2206                 :             :                                   block_id);
    2207                 :           0 :             return false;
    2208                 :             :         }
    2209                 :             : 
    2210                 :           0 :         ptr = tmp.data;
    2211                 :             :     }
    2212                 :             : 
    2213                 :             :     /* generate page, taking into account hole if necessary */
    2214         [ -  + ]:           1 :     if (bkpb->hole_length == 0)
    2215                 :             :     {
    2216                 :           0 :         memcpy(page, ptr, BLCKSZ);
    2217                 :             :     }
    2218                 :             :     else
    2219                 :             :     {
    2220                 :           1 :         memcpy(page, ptr, bkpb->hole_offset);
    2221                 :             :         /* must zero-fill the hole */
    2222   [ +  -  +  -  :           1 :         MemSet(page + bkpb->hole_offset, 0, bkpb->hole_length);
          +  -  -  +  -  
                      - ]
    2223                 :           1 :         memcpy(page + (bkpb->hole_offset + bkpb->hole_length),
    2224                 :           1 :                ptr + bkpb->hole_offset,
    2225                 :           1 :                BLCKSZ - (bkpb->hole_offset + bkpb->hole_length));
    2226                 :             :     }
    2227                 :             : 
    2228                 :           1 :     return true;
    2229                 :             : }
    2230                 :             : 
    2231                 :             : #ifndef FRONTEND
    2232                 :             : 
    2233                 :             : /*
    2234                 :             :  * Extract the FullTransactionId from a WAL record.
    2235                 :             :  */
    2236                 :             : FullTransactionId
    2237                 :             : XLogRecGetFullXid(XLogReaderState *record)
    2238                 :             : {
    2239                 :             :     /*
    2240                 :             :      * This function is only safe during replay, because it depends on the
    2241                 :             :      * replay state.  See AdvanceNextFullTransactionIdPastXid() for more.
    2242                 :             :      */
    2243                 :             :     Assert(AmStartupProcess() || !IsUnderPostmaster);
    2244                 :             : 
    2245                 :             :     return FullTransactionIdFromAllowableAt(TransamVariables->nextXid,
    2246                 :             :                                             XLogRecGetXid(record));
    2247                 :             : }
    2248                 :             : 
    2249                 :             : #endif
        

Generated by: LCOV version 2.0-1