LCOV - differential code coverage report
Current view: top level - src/backend/access/transam - xlogreader.c (source / functions) Coverage Total Hit UNC UBC GNC CBC DCB
Current: c38de3ae6098ccf1904109f2e550eb4777f66024 vs e352ac8c5c90ed6ce792f044c22145578542a330 Lines: 81.3 % 792 644 3 145 22 622 3
Current Date: 2026-11-05 14:14:01 +0100 Functions: 96.8 % 31 30 1 7 23
Baseline: lcov-20261105-baseline Branches: 71.5 % 492 352 3 137 11 341
Baseline Date: 2026-11-05 14:14:01 +0100 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
[..1] days: 100.0 % 1 1 1
(1,7] days: 0.0 % 10 0 10
(7,30] days: 100.0 % 15 15 15
(30,360] days: 63.3 % 30 19 3 8 7 12
(360..) days: 82.7 % 736 609 127 609
Function coverage date bins:
(7,30] days: 100.0 % 2 2 2
(30,360] days: 100.0 % 2 2 2
(360..) days: 96.3 % 27 26 1 5 21
Branch coverage date bins:
(7,30] days: 87.5 % 8 7 1 7
(30,360] days: 57.1 % 14 8 2 4 4 4
(360..) days: 71.7 % 470 337 133 337

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

Generated by: LCOV version 2.0-1