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

Generated by: LCOV version 1.13