LCOV - code coverage report
Current view: top level - src/backend/access/transam - xlogreader.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13devel Lines: 334 488 68.4 %
Date: 2019-11-15 22:06:47 Functions: 16 17 94.1 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13