LCOV - code coverage report
Current view: top level - src/bin/pg_rewind - xlogreader.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13devel Lines: 269 502 53.6 %
Date: 2019-08-24 16:07:17 Functions: 11 16 68.8 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * xlogreader.c
       4             :  *      Generic XLog reading facility
       5             :  *
       6             :  * Portions Copyright (c) 2013-2019, 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 "access/transam.h"
      21             : #include "access/xlogrecord.h"
      22             : #include "access/xlog_internal.h"
      23             : #include "access/xlogreader.h"
      24             : #include "catalog/pg_control.h"
      25             : #include "common/pg_lzcompress.h"
      26             : #include "replication/origin.h"
      27             : 
      28             : #ifndef FRONTEND
      29             : #include "miscadmin.h"
      30             : #include "utils/memutils.h"
      31             : #endif
      32             : 
      33             : static bool allocate_recordbuf(XLogReaderState *state, uint32 reclength);
      34             : 
      35             : static bool ValidXLogRecordHeader(XLogReaderState *state, XLogRecPtr RecPtr,
      36             :                                   XLogRecPtr PrevRecPtr, XLogRecord *record, bool randAccess);
      37             : static bool ValidXLogRecord(XLogReaderState *state, XLogRecord *record,
      38             :                             XLogRecPtr recptr);
      39             : static int  ReadPageInternal(XLogReaderState *state, XLogRecPtr pageptr,
      40             :                              int reqLen);
      41             : static void report_invalid_record(XLogReaderState *state, const char *fmt,...) pg_attribute_printf(2, 3);
      42             : 
      43             : static void ResetDecoder(XLogReaderState *state);
      44             : 
      45             : /* size of the buffer allocated for error message. */
      46             : #define MAX_ERRORMSG_LEN 1000
      47             : 
      48             : /*
      49             :  * Construct a string in state->errormsg_buf explaining what's wrong with
      50             :  * the current record being read.
      51             :  */
      52             : static void
      53           0 : report_invalid_record(XLogReaderState *state, const char *fmt,...)
      54             : {
      55             :     va_list     args;
      56             : 
      57           0 :     fmt = _(fmt);
      58             : 
      59           0 :     va_start(args, fmt);
      60           0 :     vsnprintf(state->errormsg_buf, MAX_ERRORMSG_LEN, fmt, args);
      61           0 :     va_end(args);
      62           0 : }
      63             : 
      64             : /*
      65             :  * Allocate and initialize a new XLogReader.
      66             :  *
      67             :  * Returns NULL if the xlogreader couldn't be allocated.
      68             :  */
      69             : XLogReaderState *
      70          32 : XLogReaderAllocate(int wal_segment_size, XLogPageReadCB pagereadfunc,
      71             :                    void *private_data)
      72             : {
      73             :     XLogReaderState *state;
      74             : 
      75          32 :     state = (XLogReaderState *)
      76             :         palloc_extended(sizeof(XLogReaderState),
      77             :                         MCXT_ALLOC_NO_OOM | MCXT_ALLOC_ZERO);
      78          32 :     if (!state)
      79           0 :         return NULL;
      80             : 
      81          32 :     state->max_block_id = -1;
      82             : 
      83             :     /*
      84             :      * Permanently allocate readBuf.  We do it this way, rather than just
      85             :      * making a static array, for two reasons: (1) no need to waste the
      86             :      * storage in most instantiations of the backend; (2) a static char array
      87             :      * isn't guaranteed to have any particular alignment, whereas
      88             :      * palloc_extended() will provide MAXALIGN'd storage.
      89             :      */
      90          32 :     state->readBuf = (char *) palloc_extended(XLOG_BLCKSZ,
      91             :                                               MCXT_ALLOC_NO_OOM);
      92          32 :     if (!state->readBuf)
      93             :     {
      94           0 :         pfree(state);
      95           0 :         return NULL;
      96             :     }
      97             : 
      98          32 :     state->wal_segment_size = wal_segment_size;
      99          32 :     state->read_page = pagereadfunc;
     100             :     /* system_identifier initialized to zeroes above */
     101          32 :     state->private_data = private_data;
     102             :     /* ReadRecPtr and EndRecPtr initialized to zeroes above */
     103             :     /* readSegNo, readOff, readLen, readPageTLI initialized to zeroes above */
     104          32 :     state->errormsg_buf = palloc_extended(MAX_ERRORMSG_LEN + 1,
     105             :                                           MCXT_ALLOC_NO_OOM);
     106          32 :     if (!state->errormsg_buf)
     107             :     {
     108           0 :         pfree(state->readBuf);
     109           0 :         pfree(state);
     110           0 :         return NULL;
     111             :     }
     112          32 :     state->errormsg_buf[0] = '\0';
     113             : 
     114             :     /*
     115             :      * Allocate an initial readRecordBuf of minimal size, which can later be
     116             :      * enlarged if necessary.
     117             :      */
     118          32 :     if (!allocate_recordbuf(state, 0))
     119             :     {
     120           0 :         pfree(state->errormsg_buf);
     121           0 :         pfree(state->readBuf);
     122           0 :         pfree(state);
     123           0 :         return NULL;
     124             :     }
     125             : 
     126          32 :     return state;
     127             : }
     128             : 
     129             : void
     130          32 : XLogReaderFree(XLogReaderState *state)
     131             : {
     132             :     int         block_id;
     133             : 
     134        1088 :     for (block_id = 0; block_id <= XLR_MAX_BLOCK_ID; block_id++)
     135             :     {
     136        1056 :         if (state->blocks[block_id].data)
     137          12 :             pfree(state->blocks[block_id].data);
     138             :     }
     139          32 :     if (state->main_data)
     140          32 :         pfree(state->main_data);
     141             : 
     142          32 :     pfree(state->errormsg_buf);
     143          32 :     if (state->readRecordBuf)
     144          32 :         pfree(state->readRecordBuf);
     145          32 :     pfree(state->readBuf);
     146          32 :     pfree(state);
     147          32 : }
     148             : 
     149             : /*
     150             :  * Allocate readRecordBuf to fit a record of at least the given length.
     151             :  * Returns true if successful, false if out of memory.
     152             :  *
     153             :  * readRecordBufSize is set to the new buffer size.
     154             :  *
     155             :  * To avoid useless small increases, round its size to a multiple of
     156             :  * XLOG_BLCKSZ, and make sure it's at least 5*Max(BLCKSZ, XLOG_BLCKSZ) to start
     157             :  * with.  (That is enough for all "normal" records, but very large commit or
     158             :  * abort records might need more space.)
     159             :  */
     160             : static bool
     161          32 : allocate_recordbuf(XLogReaderState *state, uint32 reclength)
     162             : {
     163          32 :     uint32      newSize = reclength;
     164             : 
     165          32 :     newSize += XLOG_BLCKSZ - (newSize % XLOG_BLCKSZ);
     166          32 :     newSize = Max(newSize, 5 * Max(BLCKSZ, XLOG_BLCKSZ));
     167             : 
     168             : #ifndef FRONTEND
     169             : 
     170             :     /*
     171             :      * Note that in much unlucky circumstances, the random data read from a
     172             :      * recycled segment can cause this routine to be called with a size
     173             :      * causing a hard failure at allocation.  For a standby, this would cause
     174             :      * the instance to stop suddenly with a hard failure, preventing it to
     175             :      * retry fetching WAL from one of its sources which could allow it to move
     176             :      * on with replay without a manual restart. If the data comes from a past
     177             :      * recycled segment and is still valid, then the allocation may succeed
     178             :      * but record checks are going to fail so this would be short-lived.  If
     179             :      * the allocation fails because of a memory shortage, then this is not a
     180             :      * hard failure either per the guarantee given by MCXT_ALLOC_NO_OOM.
     181             :      */
     182             :     if (!AllocSizeIsValid(newSize))
     183             :         return false;
     184             : 
     185             : #endif
     186             : 
     187          32 :     if (state->readRecordBuf)
     188           0 :         pfree(state->readRecordBuf);
     189          32 :     state->readRecordBuf =
     190          32 :         (char *) palloc_extended(newSize, MCXT_ALLOC_NO_OOM);
     191          32 :     if (state->readRecordBuf == NULL)
     192             :     {
     193           0 :         state->readRecordBufSize = 0;
     194           0 :         return false;
     195             :     }
     196          32 :     state->readRecordBufSize = newSize;
     197          32 :     return true;
     198             : }
     199             : 
     200             : /*
     201             :  * Attempt to read an XLOG record.
     202             :  *
     203             :  * If RecPtr is valid, try to read a record at that position.  Otherwise
     204             :  * try to read a record just after the last one previously read.
     205             :  *
     206             :  * If the read_page callback fails to read the requested data, NULL is
     207             :  * returned.  The callback is expected to have reported the error; errormsg
     208             :  * is set to NULL.
     209             :  *
     210             :  * If the reading fails for some other reason, NULL is also returned, and
     211             :  * *errormsg is set to a string with details of the failure.
     212             :  *
     213             :  * The returned pointer (or *errormsg) points to an internal buffer that's
     214             :  * valid until the next call to XLogReadRecord.
     215             :  */
     216             : XLogRecord *
     217       82056 : XLogReadRecord(XLogReaderState *state, XLogRecPtr RecPtr, char **errormsg)
     218             : {
     219             :     XLogRecord *record;
     220             :     XLogRecPtr  targetPagePtr;
     221             :     bool        randAccess;
     222             :     uint32      len,
     223             :                 total_len;
     224             :     uint32      targetRecOff;
     225             :     uint32      pageHeaderSize;
     226             :     bool        gotheader;
     227             :     int         readOff;
     228             : 
     229             :     /*
     230             :      * randAccess indicates whether to verify the previous-record pointer of
     231             :      * the record we're reading.  We only do this if we're reading
     232             :      * sequentially, which is what we initially assume.
     233             :      */
     234       82056 :     randAccess = false;
     235             : 
     236             :     /* reset error state */
     237       82056 :     *errormsg = NULL;
     238       82056 :     state->errormsg_buf[0] = '\0';
     239             : 
     240       82056 :     ResetDecoder(state);
     241             : 
     242       82056 :     if (RecPtr == InvalidXLogRecPtr)
     243             :     {
     244             :         /* No explicit start point; read the record after the one we just read */
     245       81816 :         RecPtr = state->EndRecPtr;
     246             : 
     247       81816 :         if (state->ReadRecPtr == InvalidXLogRecPtr)
     248           0 :             randAccess = true;
     249             : 
     250             :         /*
     251             :          * RecPtr is pointing to end+1 of the previous WAL record.  If we're
     252             :          * at a page boundary, no more records can fit on the current page. We
     253             :          * must skip over the page header, but we can't do that until we've
     254             :          * read in the page, since the header size is variable.
     255             :          */
     256             :     }
     257             :     else
     258             :     {
     259             :         /*
     260             :          * Caller supplied a position to start at.
     261             :          *
     262             :          * In this case, the passed-in record pointer should already be
     263             :          * pointing to a valid record starting position.
     264             :          */
     265             :         Assert(XRecOffIsValid(RecPtr));
     266         240 :         randAccess = true;
     267             :     }
     268             : 
     269       82056 :     state->currRecPtr = RecPtr;
     270             : 
     271       82056 :     targetPagePtr = RecPtr - (RecPtr % XLOG_BLCKSZ);
     272       82056 :     targetRecOff = RecPtr % XLOG_BLCKSZ;
     273             : 
     274             :     /*
     275             :      * Read the page containing the record into state->readBuf. Request enough
     276             :      * byte to cover the whole record header, or at least the part of it that
     277             :      * fits on the same page.
     278             :      */
     279       82056 :     readOff = ReadPageInternal(state,
     280             :                                targetPagePtr,
     281       82056 :                                Min(targetRecOff + SizeOfXLogRecord, XLOG_BLCKSZ));
     282       82056 :     if (readOff < 0)
     283           0 :         goto err;
     284             : 
     285             :     /*
     286             :      * ReadPageInternal always returns at least the page header, so we can
     287             :      * examine it now.
     288             :      */
     289       82056 :     pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) state->readBuf);
     290       82056 :     if (targetRecOff == 0)
     291             :     {
     292             :         /*
     293             :          * At page start, so skip over page header.
     294             :          */
     295          72 :         RecPtr += pageHeaderSize;
     296          72 :         targetRecOff = pageHeaderSize;
     297             :     }
     298       81984 :     else if (targetRecOff < pageHeaderSize)
     299             :     {
     300           0 :         report_invalid_record(state, "invalid record offset at %X/%X",
     301           0 :                               (uint32) (RecPtr >> 32), (uint32) RecPtr);
     302           0 :         goto err;
     303             :     }
     304             : 
     305       82056 :     if ((((XLogPageHeader) state->readBuf)->xlp_info & XLP_FIRST_IS_CONTRECORD) &&
     306             :         targetRecOff == pageHeaderSize)
     307             :     {
     308           0 :         report_invalid_record(state, "contrecord is requested by %X/%X",
     309           0 :                               (uint32) (RecPtr >> 32), (uint32) RecPtr);
     310           0 :         goto err;
     311             :     }
     312             : 
     313             :     /* ReadPageInternal has verified the page header */
     314             :     Assert(pageHeaderSize <= readOff);
     315             : 
     316             :     /*
     317             :      * Read the record length.
     318             :      *
     319             :      * NB: Even though we use an XLogRecord pointer here, the whole record
     320             :      * header might not fit on this page. xl_tot_len is the first field of the
     321             :      * struct, so it must be on this page (the records are MAXALIGNed), but we
     322             :      * cannot access any other fields until we've verified that we got the
     323             :      * whole header.
     324             :      */
     325       82056 :     record = (XLogRecord *) (state->readBuf + RecPtr % XLOG_BLCKSZ);
     326       82056 :     total_len = record->xl_tot_len;
     327             : 
     328             :     /*
     329             :      * If the whole record header is on this page, validate it immediately.
     330             :      * Otherwise do just a basic sanity check on xl_tot_len, and validate the
     331             :      * rest of the header after reading it from the next page.  The xl_tot_len
     332             :      * check is necessary here to ensure that we enter the "Need to reassemble
     333             :      * record" code path below; otherwise we might fail to apply
     334             :      * ValidXLogRecordHeader at all.
     335             :      */
     336       82056 :     if (targetRecOff <= XLOG_BLCKSZ - SizeOfXLogRecord)
     337             :     {
     338       81884 :         if (!ValidXLogRecordHeader(state, RecPtr, state->ReadRecPtr, record,
     339             :                                    randAccess))
     340           0 :             goto err;
     341       81884 :         gotheader = true;
     342             :     }
     343             :     else
     344             :     {
     345             :         /* XXX: more validation should be done here */
     346         172 :         if (total_len < SizeOfXLogRecord)
     347             :         {
     348           0 :             report_invalid_record(state,
     349             :                                   "invalid record length at %X/%X: wanted %u, got %u",
     350           0 :                                   (uint32) (RecPtr >> 32), (uint32) RecPtr,
     351             :                                   (uint32) SizeOfXLogRecord, total_len);
     352           0 :             goto err;
     353             :         }
     354         172 :         gotheader = false;
     355             :     }
     356             : 
     357       82056 :     len = XLOG_BLCKSZ - RecPtr % XLOG_BLCKSZ;
     358       82056 :     if (total_len > len)
     359             :     {
     360             :         /* Need to reassemble record */
     361             :         char       *contdata;
     362             :         XLogPageHeader pageHeader;
     363             :         char       *buffer;
     364             :         uint32      gotlen;
     365             : 
     366             :         /*
     367             :          * Enlarge readRecordBuf as needed.
     368             :          */
     369        1152 :         if (total_len > state->readRecordBufSize &&
     370           0 :             !allocate_recordbuf(state, total_len))
     371             :         {
     372             :             /* We treat this as a "bogus data" condition */
     373           0 :             report_invalid_record(state, "record length %u at %X/%X too long",
     374             :                                   total_len,
     375           0 :                                   (uint32) (RecPtr >> 32), (uint32) RecPtr);
     376           0 :             goto err;
     377             :         }
     378             : 
     379             :         /* Copy the first fragment of the record from the first page. */
     380        2304 :         memcpy(state->readRecordBuf,
     381        1152 :                state->readBuf + RecPtr % XLOG_BLCKSZ, len);
     382        1152 :         buffer = state->readRecordBuf + len;
     383        1152 :         gotlen = len;
     384             : 
     385             :         do
     386             :         {
     387             :             /* Calculate pointer to beginning of next page */
     388        1156 :             targetPagePtr += XLOG_BLCKSZ;
     389             : 
     390             :             /* Wait for the next page to become available */
     391        1156 :             readOff = ReadPageInternal(state, targetPagePtr,
     392        1156 :                                        Min(total_len - gotlen + SizeOfXLogShortPHD,
     393             :                                            XLOG_BLCKSZ));
     394             : 
     395        1156 :             if (readOff < 0)
     396           0 :                 goto err;
     397             : 
     398             :             Assert(SizeOfXLogShortPHD <= readOff);
     399             : 
     400             :             /* Check that the continuation on next page looks valid */
     401        1156 :             pageHeader = (XLogPageHeader) state->readBuf;
     402        1156 :             if (!(pageHeader->xlp_info & XLP_FIRST_IS_CONTRECORD))
     403             :             {
     404           0 :                 report_invalid_record(state,
     405             :                                       "there is no contrecord flag at %X/%X",
     406           0 :                                       (uint32) (RecPtr >> 32), (uint32) RecPtr);
     407           0 :                 goto err;
     408             :             }
     409             : 
     410             :             /*
     411             :              * Cross-check that xlp_rem_len agrees with how much of the record
     412             :              * we expect there to be left.
     413             :              */
     414        2312 :             if (pageHeader->xlp_rem_len == 0 ||
     415        1156 :                 total_len != (pageHeader->xlp_rem_len + gotlen))
     416             :             {
     417           0 :                 report_invalid_record(state,
     418             :                                       "invalid contrecord length %u at %X/%X",
     419             :                                       pageHeader->xlp_rem_len,
     420           0 :                                       (uint32) (RecPtr >> 32), (uint32) RecPtr);
     421           0 :                 goto err;
     422             :             }
     423             : 
     424             :             /* Append the continuation from this page to the buffer */
     425        1156 :             pageHeaderSize = XLogPageHeaderSize(pageHeader);
     426             : 
     427        1156 :             if (readOff < pageHeaderSize)
     428           0 :                 readOff = ReadPageInternal(state, targetPagePtr,
     429             :                                            pageHeaderSize);
     430             : 
     431             :             Assert(pageHeaderSize <= readOff);
     432             : 
     433        1156 :             contdata = (char *) state->readBuf + pageHeaderSize;
     434        1156 :             len = XLOG_BLCKSZ - pageHeaderSize;
     435        1156 :             if (pageHeader->xlp_rem_len < len)
     436        1152 :                 len = pageHeader->xlp_rem_len;
     437             : 
     438        1156 :             if (readOff < pageHeaderSize + len)
     439           0 :                 readOff = ReadPageInternal(state, targetPagePtr,
     440           0 :                                            pageHeaderSize + len);
     441             : 
     442        1156 :             memcpy(buffer, (char *) contdata, len);
     443        1156 :             buffer += len;
     444        1156 :             gotlen += len;
     445             : 
     446             :             /* If we just reassembled the record header, validate it. */
     447        1156 :             if (!gotheader)
     448             :             {
     449         172 :                 record = (XLogRecord *) state->readRecordBuf;
     450         172 :                 if (!ValidXLogRecordHeader(state, RecPtr, state->ReadRecPtr,
     451             :                                            record, randAccess))
     452           0 :                     goto err;
     453         172 :                 gotheader = true;
     454             :             }
     455        1156 :         } while (gotlen < total_len);
     456             : 
     457             :         Assert(gotheader);
     458             : 
     459        1152 :         record = (XLogRecord *) state->readRecordBuf;
     460        1152 :         if (!ValidXLogRecord(state, record, RecPtr))
     461           0 :             goto err;
     462             : 
     463        1152 :         pageHeaderSize = XLogPageHeaderSize((XLogPageHeader) state->readBuf);
     464        1152 :         state->ReadRecPtr = RecPtr;
     465        2304 :         state->EndRecPtr = targetPagePtr + pageHeaderSize
     466        1152 :             + MAXALIGN(pageHeader->xlp_rem_len);
     467             :     }
     468             :     else
     469             :     {
     470             :         /* Wait for the record data to become available */
     471       80904 :         readOff = ReadPageInternal(state, targetPagePtr,
     472       80904 :                                    Min(targetRecOff + total_len, XLOG_BLCKSZ));
     473       80904 :         if (readOff < 0)
     474           0 :             goto err;
     475             : 
     476             :         /* Record does not cross a page boundary */
     477       80904 :         if (!ValidXLogRecord(state, record, RecPtr))
     478           0 :             goto err;
     479             : 
     480       80904 :         state->EndRecPtr = RecPtr + MAXALIGN(total_len);
     481             : 
     482       80904 :         state->ReadRecPtr = RecPtr;
     483             :     }
     484             : 
     485             :     /*
     486             :      * Special processing if it's an XLOG SWITCH record
     487             :      */
     488       82536 :     if (record->xl_rmid == RM_XLOG_ID &&
     489         480 :         (record->xl_info & ~XLR_INFO_MASK) == XLOG_SWITCH)
     490             :     {
     491             :         /* Pretend it extends to end of segment */
     492           8 :         state->EndRecPtr += state->wal_segment_size - 1;
     493           8 :         state->EndRecPtr -= XLogSegmentOffset(state->EndRecPtr, state->wal_segment_size);
     494             :     }
     495             : 
     496       82056 :     if (DecodeXLogRecord(state, record, errormsg))
     497       82056 :         return record;
     498             :     else
     499           0 :         return NULL;
     500             : 
     501             : err:
     502             : 
     503             :     /*
     504             :      * Invalidate the read state. We might read from a different source after
     505             :      * failure.
     506             :      */
     507           0 :     XLogReaderInvalReadState(state);
     508             : 
     509           0 :     if (state->errormsg_buf[0] != '\0')
     510           0 :         *errormsg = state->errormsg_buf;
     511             : 
     512           0 :     return NULL;
     513             : }
     514             : 
     515             : /*
     516             :  * Read a single xlog page including at least [pageptr, reqLen] of valid data
     517             :  * via the read_page() callback.
     518             :  *
     519             :  * Returns -1 if the required page cannot be read for some reason; errormsg_buf
     520             :  * is set in that case (unless the error occurs in the read_page callback).
     521             :  *
     522             :  * We fetch the page from a reader-local cache if we know we have the required
     523             :  * data and if there hasn't been any error since caching the data.
     524             :  */
     525             : static int
     526      164116 : ReadPageInternal(XLogReaderState *state, XLogRecPtr pageptr, int reqLen)
     527             : {
     528             :     int         readLen;
     529             :     uint32      targetPageOff;
     530             :     XLogSegNo   targetSegNo;
     531             :     XLogPageHeader hdr;
     532             : 
     533             :     Assert((pageptr % XLOG_BLCKSZ) == 0);
     534             : 
     535      164116 :     XLByteToSeg(pageptr, targetSegNo, state->wal_segment_size);
     536      164116 :     targetPageOff = XLogSegmentOffset(pageptr, state->wal_segment_size);
     537             : 
     538             :     /* check whether we have all the requested data already */
     539      326900 :     if (targetSegNo == state->readSegNo && targetPageOff == state->readOff &&
     540      162784 :         reqLen <= state->readLen)
     541      162784 :         return state->readLen;
     542             : 
     543             :     /*
     544             :      * Data is not in our buffer.
     545             :      *
     546             :      * Every time we actually read the page, even if we looked at parts of it
     547             :      * before, we need to do verification as the read_page callback might now
     548             :      * be rereading data from a different source.
     549             :      *
     550             :      * Whenever switching to a new WAL segment, we read the first page of the
     551             :      * file and validate its header, even if that's not where the target
     552             :      * record is.  This is so that we can check the additional identification
     553             :      * info that is present in the first page's "long" header.
     554             :      */
     555        1332 :     if (targetSegNo != state->readSegNo && targetPageOff != 0)
     556             :     {
     557          12 :         XLogRecPtr  targetSegmentPtr = pageptr - targetPageOff;
     558             : 
     559          12 :         readLen = state->read_page(state, targetSegmentPtr, XLOG_BLCKSZ,
     560             :                                    state->currRecPtr,
     561             :                                    state->readBuf, &state->readPageTLI);
     562          12 :         if (readLen < 0)
     563           0 :             goto err;
     564             : 
     565             :         /* we can be sure to have enough WAL available, we scrolled back */
     566             :         Assert(readLen == XLOG_BLCKSZ);
     567             : 
     568          12 :         if (!XLogReaderValidatePageHeader(state, targetSegmentPtr,
     569             :                                           state->readBuf))
     570           0 :             goto err;
     571             :     }
     572             : 
     573             :     /*
     574             :      * First, read the requested data length, but at least a short page header
     575             :      * so that we can validate it.
     576             :      */
     577        1332 :     readLen = state->read_page(state, pageptr, Max(reqLen, SizeOfXLogShortPHD),
     578             :                                state->currRecPtr,
     579             :                                state->readBuf, &state->readPageTLI);
     580        1332 :     if (readLen < 0)
     581           0 :         goto err;
     582             : 
     583             :     Assert(readLen <= XLOG_BLCKSZ);
     584             : 
     585             :     /* Do we have enough data to check the header length? */
     586        1332 :     if (readLen <= SizeOfXLogShortPHD)
     587           0 :         goto err;
     588             : 
     589             :     Assert(readLen >= reqLen);
     590             : 
     591        1332 :     hdr = (XLogPageHeader) state->readBuf;
     592             : 
     593             :     /* still not enough */
     594        1332 :     if (readLen < XLogPageHeaderSize(hdr))
     595             :     {
     596           0 :         readLen = state->read_page(state, pageptr, XLogPageHeaderSize(hdr),
     597             :                                    state->currRecPtr,
     598             :                                    state->readBuf, &state->readPageTLI);
     599           0 :         if (readLen < 0)
     600           0 :             goto err;
     601             :     }
     602             : 
     603             :     /*
     604             :      * Now that we know we have the full header, validate it.
     605             :      */
     606        1332 :     if (!XLogReaderValidatePageHeader(state, pageptr, (char *) hdr))
     607           0 :         goto err;
     608             : 
     609             :     /* update read state information */
     610        1332 :     state->readSegNo = targetSegNo;
     611        1332 :     state->readOff = targetPageOff;
     612        1332 :     state->readLen = readLen;
     613             : 
     614        1332 :     return readLen;
     615             : 
     616             : err:
     617           0 :     XLogReaderInvalReadState(state);
     618           0 :     return -1;
     619             : }
     620             : 
     621             : /*
     622             :  * Invalidate the xlogreader's read state to force a re-read.
     623             :  */
     624             : void
     625           0 : XLogReaderInvalReadState(XLogReaderState *state)
     626             : {
     627           0 :     state->readSegNo = 0;
     628           0 :     state->readOff = 0;
     629           0 :     state->readLen = 0;
     630           0 : }
     631             : 
     632             : /*
     633             :  * Validate an XLOG record header.
     634             :  *
     635             :  * This is just a convenience subroutine to avoid duplicated code in
     636             :  * XLogReadRecord.  It's not intended for use from anywhere else.
     637             :  */
     638             : static bool
     639       82056 : ValidXLogRecordHeader(XLogReaderState *state, XLogRecPtr RecPtr,
     640             :                       XLogRecPtr PrevRecPtr, XLogRecord *record,
     641             :                       bool randAccess)
     642             : {
     643       82056 :     if (record->xl_tot_len < SizeOfXLogRecord)
     644             :     {
     645           0 :         report_invalid_record(state,
     646             :                               "invalid record length at %X/%X: wanted %u, got %u",
     647           0 :                               (uint32) (RecPtr >> 32), (uint32) RecPtr,
     648             :                               (uint32) SizeOfXLogRecord, record->xl_tot_len);
     649           0 :         return false;
     650             :     }
     651       82056 :     if (record->xl_rmid > RM_MAX_ID)
     652             :     {
     653           0 :         report_invalid_record(state,
     654             :                               "invalid resource manager ID %u at %X/%X",
     655           0 :                               record->xl_rmid, (uint32) (RecPtr >> 32),
     656             :                               (uint32) RecPtr);
     657           0 :         return false;
     658             :     }
     659       82056 :     if (randAccess)
     660             :     {
     661             :         /*
     662             :          * We can't exactly verify the prev-link, but surely it should be less
     663             :          * than the record's own address.
     664             :          */
     665         240 :         if (!(record->xl_prev < RecPtr))
     666             :         {
     667           0 :             report_invalid_record(state,
     668             :                                   "record with incorrect prev-link %X/%X at %X/%X",
     669           0 :                                   (uint32) (record->xl_prev >> 32),
     670           0 :                                   (uint32) record->xl_prev,
     671           0 :                                   (uint32) (RecPtr >> 32), (uint32) RecPtr);
     672           0 :             return false;
     673             :         }
     674             :     }
     675             :     else
     676             :     {
     677             :         /*
     678             :          * Record's prev-link should exactly match our previous location. This
     679             :          * check guards against torn WAL pages where a stale but valid-looking
     680             :          * WAL record starts on a sector boundary.
     681             :          */
     682       81816 :         if (record->xl_prev != PrevRecPtr)
     683             :         {
     684           0 :             report_invalid_record(state,
     685             :                                   "record with incorrect prev-link %X/%X at %X/%X",
     686           0 :                                   (uint32) (record->xl_prev >> 32),
     687           0 :                                   (uint32) record->xl_prev,
     688           0 :                                   (uint32) (RecPtr >> 32), (uint32) RecPtr);
     689           0 :             return false;
     690             :         }
     691             :     }
     692             : 
     693       82056 :     return true;
     694             : }
     695             : 
     696             : 
     697             : /*
     698             :  * CRC-check an XLOG record.  We do not believe the contents of an XLOG
     699             :  * record (other than to the minimal extent of computing the amount of
     700             :  * data to read in) until we've checked the CRCs.
     701             :  *
     702             :  * We assume all of the record (that is, xl_tot_len bytes) has been read
     703             :  * into memory at *record.  Also, ValidXLogRecordHeader() has accepted the
     704             :  * record's header, which means in particular that xl_tot_len is at least
     705             :  * SizeOfXLogRecord.
     706             :  */
     707             : static bool
     708       82056 : ValidXLogRecord(XLogReaderState *state, XLogRecord *record, XLogRecPtr recptr)
     709             : {
     710             :     pg_crc32c   crc;
     711             : 
     712             :     /* Calculate the CRC */
     713       82056 :     INIT_CRC32C(crc);
     714       82056 :     COMP_CRC32C(crc, ((char *) record) + SizeOfXLogRecord, record->xl_tot_len - SizeOfXLogRecord);
     715             :     /* include the record header last */
     716       82056 :     COMP_CRC32C(crc, (char *) record, offsetof(XLogRecord, xl_crc));
     717       82056 :     FIN_CRC32C(crc);
     718             : 
     719       82056 :     if (!EQ_CRC32C(record->xl_crc, crc))
     720             :     {
     721           0 :         report_invalid_record(state,
     722             :                               "incorrect resource manager data checksum in record at %X/%X",
     723           0 :                               (uint32) (recptr >> 32), (uint32) recptr);
     724           0 :         return false;
     725             :     }
     726             : 
     727       82056 :     return true;
     728             : }
     729             : 
     730             : /*
     731             :  * Validate a page header.
     732             :  *
     733             :  * Check if 'phdr' is valid as the header of the XLog page at position
     734             :  * 'recptr'.
     735             :  */
     736             : bool
     737        1344 : XLogReaderValidatePageHeader(XLogReaderState *state, XLogRecPtr recptr,
     738             :                              char *phdr)
     739             : {
     740             :     XLogRecPtr  recaddr;
     741             :     XLogSegNo   segno;
     742             :     int32       offset;
     743        1344 :     XLogPageHeader hdr = (XLogPageHeader) phdr;
     744             : 
     745             :     Assert((recptr % XLOG_BLCKSZ) == 0);
     746             : 
     747        1344 :     XLByteToSeg(recptr, segno, state->wal_segment_size);
     748        1344 :     offset = XLogSegmentOffset(recptr, state->wal_segment_size);
     749             : 
     750        1344 :     XLogSegNoOffsetToRecPtr(segno, offset, state->wal_segment_size, recaddr);
     751             : 
     752        1344 :     if (hdr->xlp_magic != XLOG_PAGE_MAGIC)
     753             :     {
     754             :         char        fname[MAXFNAMELEN];
     755             : 
     756           0 :         XLogFileName(fname, state->readPageTLI, segno, state->wal_segment_size);
     757             : 
     758           0 :         report_invalid_record(state,
     759             :                               "invalid magic number %04X in log segment %s, offset %u",
     760           0 :                               hdr->xlp_magic,
     761             :                               fname,
     762             :                               offset);
     763           0 :         return false;
     764             :     }
     765             : 
     766        1344 :     if ((hdr->xlp_info & ~XLP_ALL_FLAGS) != 0)
     767             :     {
     768             :         char        fname[MAXFNAMELEN];
     769             : 
     770           0 :         XLogFileName(fname, state->readPageTLI, segno, state->wal_segment_size);
     771             : 
     772           0 :         report_invalid_record(state,
     773             :                               "invalid info bits %04X in log segment %s, offset %u",
     774           0 :                               hdr->xlp_info,
     775             :                               fname,
     776             :                               offset);
     777           0 :         return false;
     778             :     }
     779             : 
     780        1344 :     if (hdr->xlp_info & XLP_LONG_HEADER)
     781             :     {
     782          48 :         XLogLongPageHeader longhdr = (XLogLongPageHeader) hdr;
     783             : 
     784          48 :         if (state->system_identifier &&
     785           0 :             longhdr->xlp_sysid != state->system_identifier)
     786             :         {
     787           0 :             report_invalid_record(state,
     788             :                                   "WAL file is from different database system: WAL file database system identifier is %llu, pg_control database system identifier is %llu",
     789           0 :                                   (unsigned long long) longhdr->xlp_sysid,
     790           0 :                                   (unsigned long long) state->system_identifier);
     791           0 :             return false;
     792             :         }
     793          48 :         else if (longhdr->xlp_seg_size != state->wal_segment_size)
     794             :         {
     795           0 :             report_invalid_record(state,
     796             :                                   "WAL file is from different database system: incorrect segment size in page header");
     797           0 :             return false;
     798             :         }
     799          48 :         else if (longhdr->xlp_xlog_blcksz != XLOG_BLCKSZ)
     800             :         {
     801           0 :             report_invalid_record(state,
     802             :                                   "WAL file is from different database system: incorrect XLOG_BLCKSZ in page header");
     803           0 :             return false;
     804             :         }
     805             :     }
     806        1296 :     else if (offset == 0)
     807             :     {
     808             :         char        fname[MAXFNAMELEN];
     809             : 
     810           0 :         XLogFileName(fname, state->readPageTLI, segno, state->wal_segment_size);
     811             : 
     812             :         /* hmm, first page of file doesn't have a long header? */
     813           0 :         report_invalid_record(state,
     814             :                               "invalid info bits %04X in log segment %s, offset %u",
     815           0 :                               hdr->xlp_info,
     816             :                               fname,
     817             :                               offset);
     818           0 :         return false;
     819             :     }
     820             : 
     821             :     /*
     822             :      * Check that the address on the page agrees with what we expected. This
     823             :      * check typically fails when an old WAL segment is recycled, and hasn't
     824             :      * yet been overwritten with new data yet.
     825             :      */
     826        1344 :     if (hdr->xlp_pageaddr != recaddr)
     827             :     {
     828             :         char        fname[MAXFNAMELEN];
     829             : 
     830           0 :         XLogFileName(fname, state->readPageTLI, segno, state->wal_segment_size);
     831             : 
     832           0 :         report_invalid_record(state,
     833             :                               "unexpected pageaddr %X/%X in log segment %s, offset %u",
     834           0 :                               (uint32) (hdr->xlp_pageaddr >> 32), (uint32) hdr->xlp_pageaddr,
     835             :                               fname,
     836             :                               offset);
     837           0 :         return false;
     838             :     }
     839             : 
     840             :     /*
     841             :      * Since child timelines are always assigned a TLI greater than their
     842             :      * immediate parent's TLI, we should never see TLI go backwards across
     843             :      * successive pages of a consistent WAL sequence.
     844             :      *
     845             :      * Sometimes we re-read a segment that's already been (partially) read. So
     846             :      * we only verify TLIs for pages that are later than the last remembered
     847             :      * LSN.
     848             :      */
     849        1344 :     if (recptr > state->latestPagePtr)
     850             :     {
     851        1272 :         if (hdr->xlp_tli < state->latestPageTLI)
     852             :         {
     853             :             char        fname[MAXFNAMELEN];
     854             : 
     855           0 :             XLogFileName(fname, state->readPageTLI, segno, state->wal_segment_size);
     856             : 
     857           0 :             report_invalid_record(state,
     858             :                                   "out-of-sequence timeline ID %u (after %u) in log segment %s, offset %u",
     859             :                                   hdr->xlp_tli,
     860             :                                   state->latestPageTLI,
     861             :                                   fname,
     862             :                                   offset);
     863           0 :             return false;
     864             :         }
     865             :     }
     866        1344 :     state->latestPagePtr = recptr;
     867        1344 :     state->latestPageTLI = hdr->xlp_tli;
     868             : 
     869        1344 :     return true;
     870             : }
     871             : 
     872             : #ifdef FRONTEND
     873             : /*
     874             :  * Functions that are currently not needed in the backend, but are better
     875             :  * implemented inside xlogreader.c because of the internal facilities available
     876             :  * here.
     877             :  */
     878             : 
     879             : /*
     880             :  * Find the first record with an lsn >= RecPtr.
     881             :  *
     882             :  * Useful for checking whether RecPtr is a valid xlog address for reading, and
     883             :  * to find the first valid address after some address when dumping records for
     884             :  * debugging purposes.
     885             :  */
     886             : XLogRecPtr
     887           0 : XLogFindNextRecord(XLogReaderState *state, XLogRecPtr RecPtr)
     888             : {
     889           0 :     XLogReaderState saved_state = *state;
     890             :     XLogRecPtr  tmpRecPtr;
     891           0 :     XLogRecPtr  found = InvalidXLogRecPtr;
     892             :     XLogPageHeader header;
     893             :     char       *errormsg;
     894             : 
     895             :     Assert(!XLogRecPtrIsInvalid(RecPtr));
     896             : 
     897             :     /*
     898             :      * skip over potential continuation data, keeping in mind that it may span
     899             :      * multiple pages
     900             :      */
     901           0 :     tmpRecPtr = RecPtr;
     902             :     while (true)
     903           0 :     {
     904             :         XLogRecPtr  targetPagePtr;
     905             :         int         targetRecOff;
     906             :         uint32      pageHeaderSize;
     907             :         int         readLen;
     908             : 
     909             :         /*
     910             :          * Compute targetRecOff. It should typically be equal or greater than
     911             :          * short page-header since a valid record can't start anywhere before
     912             :          * that, except when caller has explicitly specified the offset that
     913             :          * falls somewhere there or when we are skipping multi-page
     914             :          * continuation record. It doesn't matter though because
     915             :          * ReadPageInternal() is prepared to handle that and will read at
     916             :          * least short page-header worth of data
     917             :          */
     918           0 :         targetRecOff = tmpRecPtr % XLOG_BLCKSZ;
     919             : 
     920             :         /* scroll back to page boundary */
     921           0 :         targetPagePtr = tmpRecPtr - targetRecOff;
     922             : 
     923             :         /* Read the page containing the record */
     924           0 :         readLen = ReadPageInternal(state, targetPagePtr, targetRecOff);
     925           0 :         if (readLen < 0)
     926           0 :             goto err;
     927             : 
     928           0 :         header = (XLogPageHeader) state->readBuf;
     929             : 
     930           0 :         pageHeaderSize = XLogPageHeaderSize(header);
     931             : 
     932             :         /* make sure we have enough data for the page header */
     933           0 :         readLen = ReadPageInternal(state, targetPagePtr, pageHeaderSize);
     934           0 :         if (readLen < 0)
     935           0 :             goto err;
     936             : 
     937             :         /* skip over potential continuation data */
     938           0 :         if (header->xlp_info & XLP_FIRST_IS_CONTRECORD)
     939             :         {
     940             :             /*
     941             :              * If the length of the remaining continuation data is more than
     942             :              * what can fit in this page, the continuation record crosses over
     943             :              * this page. Read the next page and try again. xlp_rem_len in the
     944             :              * next page header will contain the remaining length of the
     945             :              * continuation data
     946             :              *
     947             :              * Note that record headers are MAXALIGN'ed
     948             :              */
     949           0 :             if (MAXALIGN(header->xlp_rem_len) > (XLOG_BLCKSZ - pageHeaderSize))
     950           0 :                 tmpRecPtr = targetPagePtr + XLOG_BLCKSZ;
     951             :             else
     952             :             {
     953             :                 /*
     954             :                  * The previous continuation record ends in this page. Set
     955             :                  * tmpRecPtr to point to the first valid record
     956             :                  */
     957           0 :                 tmpRecPtr = targetPagePtr + pageHeaderSize
     958           0 :                     + MAXALIGN(header->xlp_rem_len);
     959           0 :                 break;
     960             :             }
     961             :         }
     962             :         else
     963             :         {
     964           0 :             tmpRecPtr = targetPagePtr + pageHeaderSize;
     965           0 :             break;
     966             :         }
     967             :     }
     968             : 
     969             :     /*
     970             :      * we know now that tmpRecPtr is an address pointing to a valid XLogRecord
     971             :      * because either we're at the first record after the beginning of a page
     972             :      * or we just jumped over the remaining data of a continuation.
     973             :      */
     974           0 :     while (XLogReadRecord(state, tmpRecPtr, &errormsg) != NULL)
     975             :     {
     976             :         /* continue after the record */
     977           0 :         tmpRecPtr = InvalidXLogRecPtr;
     978             : 
     979             :         /* past the record we've found, break out */
     980           0 :         if (RecPtr <= state->ReadRecPtr)
     981             :         {
     982           0 :             found = state->ReadRecPtr;
     983           0 :             goto out;
     984             :         }
     985             :     }
     986             : 
     987             : err:
     988             : out:
     989             :     /* Reset state to what we had before finding the record */
     990           0 :     state->ReadRecPtr = saved_state.ReadRecPtr;
     991           0 :     state->EndRecPtr = saved_state.EndRecPtr;
     992           0 :     XLogReaderInvalReadState(state);
     993             : 
     994           0 :     return found;
     995             : }
     996             : 
     997             : #endif                          /* FRONTEND */
     998             : 
     999             : 
    1000             : /* ----------------------------------------
    1001             :  * Functions for decoding the data and block references in a record.
    1002             :  * ----------------------------------------
    1003             :  */
    1004             : 
    1005             : /* private function to reset the state between records */
    1006             : static void
    1007      164112 : ResetDecoder(XLogReaderState *state)
    1008             : {
    1009             :     int         block_id;
    1010             : 
    1011      164112 :     state->decoded_record = NULL;
    1012             : 
    1013      164112 :     state->main_data_len = 0;
    1014             : 
    1015      246340 :     for (block_id = 0; block_id <= state->max_block_id; block_id++)
    1016             :     {
    1017       82228 :         state->blocks[block_id].in_use = false;
    1018       82228 :         state->blocks[block_id].has_image = false;
    1019       82228 :         state->blocks[block_id].has_data = false;
    1020       82228 :         state->blocks[block_id].apply_image = false;
    1021             :     }
    1022      164112 :     state->max_block_id = -1;
    1023      164112 : }
    1024             : 
    1025             : /*
    1026             :  * Decode the previously read record.
    1027             :  *
    1028             :  * On error, a human-readable error message is returned in *errormsg, and
    1029             :  * the return value is false.
    1030             :  */
    1031             : bool
    1032       82056 : DecodeXLogRecord(XLogReaderState *state, XLogRecord *record, char **errormsg)
    1033             : {
    1034             :     /*
    1035             :      * read next _size bytes from record buffer, but check for overrun first.
    1036             :      */
    1037             : #define COPY_HEADER_FIELD(_dst, _size)          \
    1038             :     do {                                        \
    1039             :         if (remaining < _size)                   \
    1040             :             goto shortdata_err;                 \
    1041             :         memcpy(_dst, ptr, _size);               \
    1042             :         ptr += _size;                           \
    1043             :         remaining -= _size;                     \
    1044             :     } while(0)
    1045             : 
    1046             :     char       *ptr;
    1047             :     uint32      remaining;
    1048             :     uint32      datatotal;
    1049       82056 :     RelFileNode *rnode = NULL;
    1050             :     uint8       block_id;
    1051             : 
    1052       82056 :     ResetDecoder(state);
    1053             : 
    1054       82056 :     state->decoded_record = record;
    1055       82056 :     state->record_origin = InvalidRepOriginId;
    1056             : 
    1057       82056 :     ptr = (char *) record;
    1058       82056 :     ptr += SizeOfXLogRecord;
    1059       82056 :     remaining = record->xl_tot_len - SizeOfXLogRecord;
    1060             : 
    1061             :     /* Decode the headers */
    1062       82056 :     datatotal = 0;
    1063      246340 :     while (remaining > datatotal)
    1064             :     {
    1065      163868 :         COPY_HEADER_FIELD(&block_id, sizeof(uint8));
    1066             : 
    1067      163868 :         if (block_id == XLR_BLOCK_ID_DATA_SHORT)
    1068             :         {
    1069             :             /* XLogRecordDataHeaderShort */
    1070             :             uint8       main_data_len;
    1071             : 
    1072       81628 :             COPY_HEADER_FIELD(&main_data_len, sizeof(uint8));
    1073             : 
    1074       81628 :             state->main_data_len = main_data_len;
    1075       81628 :             datatotal += main_data_len;
    1076       81628 :             break;              /* by convention, the main data fragment is
    1077             :                                  * always last */
    1078             :         }
    1079       82240 :         else if (block_id == XLR_BLOCK_ID_DATA_LONG)
    1080             :         {
    1081             :             /* XLogRecordDataHeaderLong */
    1082             :             uint32      main_data_len;
    1083             : 
    1084          12 :             COPY_HEADER_FIELD(&main_data_len, sizeof(uint32));
    1085          12 :             state->main_data_len = main_data_len;
    1086          12 :             datatotal += main_data_len;
    1087          12 :             break;              /* by convention, the main data fragment is
    1088             :                                  * always last */
    1089             :         }
    1090       82228 :         else if (block_id == XLR_BLOCK_ID_ORIGIN)
    1091             :         {
    1092           0 :             COPY_HEADER_FIELD(&state->record_origin, sizeof(RepOriginId));
    1093             :         }
    1094       82228 :         else if (block_id <= XLR_MAX_BLOCK_ID)
    1095             :         {
    1096             :             /* XLogRecordBlockHeader */
    1097             :             DecodedBkpBlock *blk;
    1098             :             uint8       fork_flags;
    1099             : 
    1100       82228 :             if (block_id <= state->max_block_id)
    1101             :             {
    1102           0 :                 report_invalid_record(state,
    1103             :                                       "out-of-order block_id %u at %X/%X",
    1104             :                                       block_id,
    1105           0 :                                       (uint32) (state->ReadRecPtr >> 32),
    1106           0 :                                       (uint32) state->ReadRecPtr);
    1107           0 :                 goto err;
    1108             :             }
    1109       82228 :             state->max_block_id = block_id;
    1110             : 
    1111       82228 :             blk = &state->blocks[block_id];
    1112       82228 :             blk->in_use = true;
    1113       82228 :             blk->apply_image = false;
    1114             : 
    1115       82228 :             COPY_HEADER_FIELD(&fork_flags, sizeof(uint8));
    1116       82228 :             blk->forknum = fork_flags & BKPBLOCK_FORK_MASK;
    1117       82228 :             blk->flags = fork_flags;
    1118       82228 :             blk->has_image = ((fork_flags & BKPBLOCK_HAS_IMAGE) != 0);
    1119       82228 :             blk->has_data = ((fork_flags & BKPBLOCK_HAS_DATA) != 0);
    1120             : 
    1121       82228 :             COPY_HEADER_FIELD(&blk->data_len, sizeof(uint16));
    1122             :             /* cross-check that the HAS_DATA flag is set iff data_length > 0 */
    1123       82228 :             if (blk->has_data && blk->data_len == 0)
    1124             :             {
    1125           0 :                 report_invalid_record(state,
    1126             :                                       "BKPBLOCK_HAS_DATA set, but no data included at %X/%X",
    1127           0 :                                       (uint32) (state->ReadRecPtr >> 32), (uint32) state->ReadRecPtr);
    1128           0 :                 goto err;
    1129             :             }
    1130       82228 :             if (!blk->has_data && blk->data_len != 0)
    1131             :             {
    1132           0 :                 report_invalid_record(state,
    1133             :                                       "BKPBLOCK_HAS_DATA not set, but data length is %u at %X/%X",
    1134           0 :                                       (unsigned int) blk->data_len,
    1135           0 :                                       (uint32) (state->ReadRecPtr >> 32), (uint32) state->ReadRecPtr);
    1136           0 :                 goto err;
    1137             :             }
    1138       82228 :             datatotal += blk->data_len;
    1139             : 
    1140       82228 :             if (blk->has_image)
    1141             :             {
    1142         640 :                 COPY_HEADER_FIELD(&blk->bimg_len, sizeof(uint16));
    1143         640 :                 COPY_HEADER_FIELD(&blk->hole_offset, sizeof(uint16));
    1144         640 :                 COPY_HEADER_FIELD(&blk->bimg_info, sizeof(uint8));
    1145             : 
    1146         640 :                 blk->apply_image = ((blk->bimg_info & BKPIMAGE_APPLY) != 0);
    1147             : 
    1148         640 :                 if (blk->bimg_info & BKPIMAGE_IS_COMPRESSED)
    1149             :                 {
    1150           0 :                     if (blk->bimg_info & BKPIMAGE_HAS_HOLE)
    1151           0 :                         COPY_HEADER_FIELD(&blk->hole_length, sizeof(uint16));
    1152             :                     else
    1153           0 :                         blk->hole_length = 0;
    1154             :                 }
    1155             :                 else
    1156         640 :                     blk->hole_length = BLCKSZ - blk->bimg_len;
    1157         640 :                 datatotal += blk->bimg_len;
    1158             : 
    1159             :                 /*
    1160             :                  * cross-check that hole_offset > 0, hole_length > 0 and
    1161             :                  * bimg_len < BLCKSZ if the HAS_HOLE flag is set.
    1162             :                  */
    1163        1240 :                 if ((blk->bimg_info & BKPIMAGE_HAS_HOLE) &&
    1164        1200 :                     (blk->hole_offset == 0 ||
    1165        1200 :                      blk->hole_length == 0 ||
    1166         600 :                      blk->bimg_len == BLCKSZ))
    1167             :                 {
    1168           0 :                     report_invalid_record(state,
    1169             :                                           "BKPIMAGE_HAS_HOLE set, but hole offset %u length %u block image length %u at %X/%X",
    1170           0 :                                           (unsigned int) blk->hole_offset,
    1171           0 :                                           (unsigned int) blk->hole_length,
    1172           0 :                                           (unsigned int) blk->bimg_len,
    1173           0 :                                           (uint32) (state->ReadRecPtr >> 32), (uint32) state->ReadRecPtr);
    1174           0 :                     goto err;
    1175             :                 }
    1176             : 
    1177             :                 /*
    1178             :                  * cross-check that hole_offset == 0 and hole_length == 0 if
    1179             :                  * the HAS_HOLE flag is not set.
    1180             :                  */
    1181         680 :                 if (!(blk->bimg_info & BKPIMAGE_HAS_HOLE) &&
    1182          80 :                     (blk->hole_offset != 0 || blk->hole_length != 0))
    1183             :                 {
    1184           0 :                     report_invalid_record(state,
    1185             :                                           "BKPIMAGE_HAS_HOLE not set, but hole offset %u length %u at %X/%X",
    1186           0 :                                           (unsigned int) blk->hole_offset,
    1187           0 :                                           (unsigned int) blk->hole_length,
    1188           0 :                                           (uint32) (state->ReadRecPtr >> 32), (uint32) state->ReadRecPtr);
    1189           0 :                     goto err;
    1190             :                 }
    1191             : 
    1192             :                 /*
    1193             :                  * cross-check that bimg_len < BLCKSZ if the IS_COMPRESSED
    1194             :                  * flag is set.
    1195             :                  */
    1196         640 :                 if ((blk->bimg_info & BKPIMAGE_IS_COMPRESSED) &&
    1197           0 :                     blk->bimg_len == BLCKSZ)
    1198             :                 {
    1199           0 :                     report_invalid_record(state,
    1200             :                                           "BKPIMAGE_IS_COMPRESSED set, but block image length %u at %X/%X",
    1201           0 :                                           (unsigned int) blk->bimg_len,
    1202           0 :                                           (uint32) (state->ReadRecPtr >> 32), (uint32) state->ReadRecPtr);
    1203           0 :                     goto err;
    1204             :                 }
    1205             : 
    1206             :                 /*
    1207             :                  * cross-check that bimg_len = BLCKSZ if neither HAS_HOLE nor
    1208             :                  * IS_COMPRESSED flag is set.
    1209             :                  */
    1210         680 :                 if (!(blk->bimg_info & BKPIMAGE_HAS_HOLE) &&
    1211          80 :                     !(blk->bimg_info & BKPIMAGE_IS_COMPRESSED) &&
    1212          40 :                     blk->bimg_len != BLCKSZ)
    1213             :                 {
    1214           0 :                     report_invalid_record(state,
    1215             :                                           "neither BKPIMAGE_HAS_HOLE nor BKPIMAGE_IS_COMPRESSED set, but block image length is %u at %X/%X",
    1216           0 :                                           (unsigned int) blk->data_len,
    1217           0 :                                           (uint32) (state->ReadRecPtr >> 32), (uint32) state->ReadRecPtr);
    1218           0 :                     goto err;
    1219             :                 }
    1220             :             }
    1221       82228 :             if (!(fork_flags & BKPBLOCK_SAME_REL))
    1222             :             {
    1223       81892 :                 COPY_HEADER_FIELD(&blk->rnode, sizeof(RelFileNode));
    1224       81892 :                 rnode = &blk->rnode;
    1225             :             }
    1226             :             else
    1227             :             {
    1228         336 :                 if (rnode == NULL)
    1229             :                 {
    1230           0 :                     report_invalid_record(state,
    1231             :                                           "BKPBLOCK_SAME_REL set but no previous rel at %X/%X",
    1232           0 :                                           (uint32) (state->ReadRecPtr >> 32), (uint32) state->ReadRecPtr);
    1233           0 :                     goto err;
    1234             :                 }
    1235             : 
    1236         336 :                 blk->rnode = *rnode;
    1237             :             }
    1238       82228 :             COPY_HEADER_FIELD(&blk->blkno, sizeof(BlockNumber));
    1239             :         }
    1240             :         else
    1241             :         {
    1242           0 :             report_invalid_record(state,
    1243             :                                   "invalid block_id %u at %X/%X",
    1244             :                                   block_id,
    1245           0 :                                   (uint32) (state->ReadRecPtr >> 32),
    1246           0 :                                   (uint32) state->ReadRecPtr);
    1247           0 :             goto err;
    1248             :         }
    1249             :     }
    1250             : 
    1251       82056 :     if (remaining != datatotal)
    1252           0 :         goto shortdata_err;
    1253             : 
    1254             :     /*
    1255             :      * Ok, we've parsed the fragment headers, and verified that the total
    1256             :      * length of the payload in the fragments is equal to the amount of data
    1257             :      * left. Copy the data of each fragment to a separate buffer.
    1258             :      *
    1259             :      * We could just set up pointers into readRecordBuf, but we want to align
    1260             :      * the data for the convenience of the callers. Backup images are not
    1261             :      * copied, however; they don't need alignment.
    1262             :      */
    1263             : 
    1264             :     /* block data first */
    1265      164284 :     for (block_id = 0; block_id <= state->max_block_id; block_id++)
    1266             :     {
    1267       82228 :         DecodedBkpBlock *blk = &state->blocks[block_id];
    1268             : 
    1269       82228 :         if (!blk->in_use)
    1270           0 :             continue;
    1271             : 
    1272             :         Assert(blk->has_image || !blk->apply_image);
    1273             : 
    1274       82228 :         if (blk->has_image)
    1275             :         {
    1276         640 :             blk->bkp_image = ptr;
    1277         640 :             ptr += blk->bimg_len;
    1278             :         }
    1279       82228 :         if (blk->has_data)
    1280             :         {
    1281       40960 :             if (!blk->data || blk->data_len > blk->data_bufsz)
    1282             :             {
    1283          12 :                 if (blk->data)
    1284           0 :                     pfree(blk->data);
    1285             : 
    1286             :                 /*
    1287             :                  * Force the initial request to be BLCKSZ so that we don't
    1288             :                  * waste time with lots of trips through this stanza as a
    1289             :                  * result of WAL compression.
    1290             :                  */
    1291          12 :                 blk->data_bufsz = MAXALIGN(Max(blk->data_len, BLCKSZ));
    1292          12 :                 blk->data = palloc(blk->data_bufsz);
    1293             :             }
    1294       40960 :             memcpy(blk->data, ptr, blk->data_len);
    1295       40960 :             ptr += blk->data_len;
    1296             :         }
    1297             :     }
    1298             : 
    1299             :     /* and finally, the main data */
    1300       82056 :     if (state->main_data_len > 0)
    1301             :     {
    1302       81640 :         if (!state->main_data || state->main_data_len > state->main_data_bufsz)
    1303             :         {
    1304          32 :             if (state->main_data)
    1305           0 :                 pfree(state->main_data);
    1306             : 
    1307             :             /*
    1308             :              * main_data_bufsz must be MAXALIGN'ed.  In many xlog record
    1309             :              * types, we omit trailing struct padding on-disk to save a few
    1310             :              * bytes; but compilers may generate accesses to the xlog struct
    1311             :              * that assume that padding bytes are present.  If the palloc
    1312             :              * request is not large enough to include such padding bytes then
    1313             :              * we'll get valgrind complaints due to otherwise-harmless fetches
    1314             :              * of the padding bytes.
    1315             :              *
    1316             :              * In addition, force the initial request to be reasonably large
    1317             :              * so that we don't waste time with lots of trips through this
    1318             :              * stanza.  BLCKSZ / 2 seems like a good compromise choice.
    1319             :              */
    1320          32 :             state->main_data_bufsz = MAXALIGN(Max(state->main_data_len,
    1321             :                                                   BLCKSZ / 2));
    1322          32 :             state->main_data = palloc(state->main_data_bufsz);
    1323             :         }
    1324       81640 :         memcpy(state->main_data, ptr, state->main_data_len);
    1325       81640 :         ptr += state->main_data_len;
    1326             :     }
    1327             : 
    1328       82056 :     return true;
    1329             : 
    1330             : shortdata_err:
    1331           0 :     report_invalid_record(state,
    1332             :                           "record with invalid length at %X/%X",
    1333           0 :                           (uint32) (state->ReadRecPtr >> 32), (uint32) state->ReadRecPtr);
    1334             : err:
    1335           0 :     *errormsg = state->errormsg_buf;
    1336             : 
    1337           0 :     return false;
    1338             : }
    1339             : 
    1340             : /*
    1341             :  * Returns information about the block that a block reference refers to.
    1342             :  *
    1343             :  * If the WAL record contains a block reference with the given ID, *rnode,
    1344             :  * *forknum, and *blknum are filled in (if not NULL), and returns true.
    1345             :  * Otherwise returns false.
    1346             :  */
    1347             : bool
    1348       82048 : XLogRecGetBlockTag(XLogReaderState *record, uint8 block_id,
    1349             :                    RelFileNode *rnode, ForkNumber *forknum, BlockNumber *blknum)
    1350             : {
    1351             :     DecodedBkpBlock *bkpb;
    1352             : 
    1353       82048 :     if (!record->blocks[block_id].in_use)
    1354           0 :         return false;
    1355             : 
    1356       82048 :     bkpb = &record->blocks[block_id];
    1357       82048 :     if (rnode)
    1358       82048 :         *rnode = bkpb->rnode;
    1359       82048 :     if (forknum)
    1360       82048 :         *forknum = bkpb->forknum;
    1361       82048 :     if (blknum)
    1362       82048 :         *blknum = bkpb->blkno;
    1363       82048 :     return true;
    1364             : }
    1365             : 
    1366             : /*
    1367             :  * Returns the data associated with a block reference, or NULL if there is
    1368             :  * no data (e.g. because a full-page image was taken instead). The returned
    1369             :  * pointer points to a MAXALIGNed buffer.
    1370             :  */
    1371             : char *
    1372           0 : XLogRecGetBlockData(XLogReaderState *record, uint8 block_id, Size *len)
    1373             : {
    1374             :     DecodedBkpBlock *bkpb;
    1375             : 
    1376           0 :     if (!record->blocks[block_id].in_use)
    1377           0 :         return NULL;
    1378             : 
    1379           0 :     bkpb = &record->blocks[block_id];
    1380             : 
    1381           0 :     if (!bkpb->has_data)
    1382             :     {
    1383           0 :         if (len)
    1384           0 :             *len = 0;
    1385           0 :         return NULL;
    1386             :     }
    1387             :     else
    1388             :     {
    1389           0 :         if (len)
    1390           0 :             *len = bkpb->data_len;
    1391           0 :         return bkpb->data;
    1392             :     }
    1393             : }
    1394             : 
    1395             : /*
    1396             :  * Restore a full-page image from a backup block attached to an XLOG record.
    1397             :  *
    1398             :  * Returns the buffer number containing the page.
    1399             :  */
    1400             : bool
    1401           0 : RestoreBlockImage(XLogReaderState *record, uint8 block_id, char *page)
    1402             : {
    1403             :     DecodedBkpBlock *bkpb;
    1404             :     char       *ptr;
    1405             :     PGAlignedBlock tmp;
    1406             : 
    1407           0 :     if (!record->blocks[block_id].in_use)
    1408           0 :         return false;
    1409           0 :     if (!record->blocks[block_id].has_image)
    1410           0 :         return false;
    1411             : 
    1412           0 :     bkpb = &record->blocks[block_id];
    1413           0 :     ptr = bkpb->bkp_image;
    1414             : 
    1415           0 :     if (bkpb->bimg_info & BKPIMAGE_IS_COMPRESSED)
    1416             :     {
    1417             :         /* If a backup block image is compressed, decompress it */
    1418           0 :         if (pglz_decompress(ptr, bkpb->bimg_len, tmp.data,
    1419           0 :                             BLCKSZ - bkpb->hole_length, true) < 0)
    1420             :         {
    1421           0 :             report_invalid_record(record, "invalid compressed image at %X/%X, block %d",
    1422           0 :                                   (uint32) (record->ReadRecPtr >> 32),
    1423           0 :                                   (uint32) record->ReadRecPtr,
    1424             :                                   block_id);
    1425           0 :             return false;
    1426             :         }
    1427           0 :         ptr = tmp.data;
    1428             :     }
    1429             : 
    1430             :     /* generate page, taking into account hole if necessary */
    1431           0 :     if (bkpb->hole_length == 0)
    1432             :     {
    1433           0 :         memcpy(page, ptr, BLCKSZ);
    1434             :     }
    1435             :     else
    1436             :     {
    1437           0 :         memcpy(page, ptr, bkpb->hole_offset);
    1438             :         /* must zero-fill the hole */
    1439           0 :         MemSet(page + bkpb->hole_offset, 0, bkpb->hole_length);
    1440           0 :         memcpy(page + (bkpb->hole_offset + bkpb->hole_length),
    1441           0 :                ptr + bkpb->hole_offset,
    1442           0 :                BLCKSZ - (bkpb->hole_offset + bkpb->hole_length));
    1443             :     }
    1444             : 
    1445           0 :     return true;
    1446             : }
    1447             : 
    1448             : #ifndef FRONTEND
    1449             : 
    1450             : /*
    1451             :  * Extract the FullTransactionId from a WAL record.
    1452             :  */
    1453             : FullTransactionId
    1454             : XLogRecGetFullXid(XLogReaderState *record)
    1455             : {
    1456             :     TransactionId   xid,
    1457             :                     next_xid;
    1458             :     uint32          epoch;
    1459             : 
    1460             :     /*
    1461             :      * This function is only safe during replay, because it depends on the
    1462             :      * replay state.  See AdvanceNextFullTransactionIdPastXid() for more.
    1463             :      */
    1464             :     Assert(AmStartupProcess() || !IsUnderPostmaster);
    1465             : 
    1466             :     xid = XLogRecGetXid(record);
    1467             :     next_xid = XidFromFullTransactionId(ShmemVariableCache->nextFullXid);
    1468             :     epoch = EpochFromFullTransactionId(ShmemVariableCache->nextFullXid);
    1469             : 
    1470             :     /*
    1471             :      * If xid is numerically greater than next_xid, it has to be from the
    1472             :      * last epoch.
    1473             :      */
    1474             :     if (unlikely(xid > next_xid))
    1475             :         --epoch;
    1476             : 
    1477             :     return FullTransactionIdFromEpochAndXid(epoch, xid);
    1478             : }
    1479             : 
    1480             : #endif

Generated by: LCOV version 1.13