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

Generated by: LCOV version 1.13