Introduce the concept of read-only StringInfos

There were various places in our codebase which conjured up a StringInfo
by manually assigning the StringInfo fields and setting the data field
to point to some existing buffer.  There wasn't much consistency here as
to what fields like maxlen got set to and in one location we didn't
correctly ensure that the buffer was correctly NUL terminated at len
bytes, as per what was documented as required in stringinfo.h

Here we introduce 2 new functions to initialize StringInfos.  One allows
callers to initialize a StringInfo passing along a buffer that is
already allocated by palloc.  Here the StringInfo code uses this buffer
directly rather than doing any memcpying into a new allocation.  Having
this as a function allows us to verify the buffer is correctly NUL
terminated.  StringInfos initialized this way can be appended to and
reset just like any other normal StringInfo.

The other new initialization function also accepts an existing buffer,
but the given buffer does not need to be a pointer to a palloc'd chunk.
This buffer could be a pointer pointing partway into some palloc'd chunk
or may not even be palloc'd at all.  StringInfos initialized this way
are deemed as "read-only".  This means that it's not possible to
append to them or reset them.

For the latter of the two new initialization functions mentioned above,
we relax the requirement that the data buffer must be NUL terminated.
Relaxing this requirement is convenient in a few places as it can save
us from having to allocate an entire new buffer just to add the NUL
terminator or save us from having to temporarily add a NUL only to have to
put the original char back again later.

Incompatibility note:

Here we also forego adding the NUL in a few places where it does not
seem to be required.  These locations are passing the given StringInfo
into a type's receive function.  It does not seem like any of our
built-in receive functions require this, but perhaps there's some UDT
out there in the wild which does require this.  It is likely worthy of
a mention in the release notes that a UDT's receive function mustn't rely
on the input StringInfo being NUL terminated.

Author: David Rowley
Reviewed-by: Tom Lane
Discussion: https://postgr.es/m/CAApHDvorfO3iBZ%3DxpiZvp3uHtJVLyFaPBSvcAhAq2HPLnaNSwQ%40mail.gmail.com
This commit is contained in:
David Rowley 2023-10-26 16:31:48 +13:00
parent 01575ad788
commit f0efa5aec1
9 changed files with 127 additions and 83 deletions

View File

@ -774,10 +774,7 @@ LogicalParallelApplyLoop(shm_mq_handle *mqh)
if (len == 0) if (len == 0)
elog(ERROR, "invalid message length"); elog(ERROR, "invalid message length");
s.cursor = 0; initReadOnlyStringInfo(&s, data, len);
s.maxlen = -1;
s.data = (char *) data;
s.len = len;
/* /*
* The first byte of messages sent from leader apply worker to * The first byte of messages sent from leader apply worker to

View File

@ -879,6 +879,7 @@ logicalrep_read_tuple(StringInfo in, LogicalRepTupleData *tuple)
/* Read the data */ /* Read the data */
for (i = 0; i < natts; i++) for (i = 0; i < natts; i++)
{ {
char *buff;
char kind; char kind;
int len; int len;
StringInfo value = &tuple->colvalues[i]; StringInfo value = &tuple->colvalues[i];
@ -899,19 +900,18 @@ logicalrep_read_tuple(StringInfo in, LogicalRepTupleData *tuple)
len = pq_getmsgint(in, 4); /* read length */ len = pq_getmsgint(in, 4); /* read length */
/* and data */ /* and data */
value->data = palloc(len + 1); buff = palloc(len + 1);
pq_copymsgbytes(in, value->data, len); pq_copymsgbytes(in, buff, len);
/* /*
* Not strictly necessary for LOGICALREP_COLUMN_BINARY, but * NUL termination is required for LOGICALREP_COLUMN_TEXT mode
* per StringInfo practice. * as input functions require that. For
* LOGICALREP_COLUMN_BINARY it's not technically required, but
* it's harmless.
*/ */
value->data[len] = '\0'; buff[len] = '\0';
/* make StringInfo fully valid */ initStringInfoFromString(value, buff, len);
value->len = len;
value->cursor = 0;
value->maxlen = len;
break; break;
default: default:
elog(ERROR, "unrecognized data representation type '%c'", kind); elog(ERROR, "unrecognized data representation type '%c'", kind);

View File

@ -3582,10 +3582,7 @@ LogicalRepApplyLoop(XLogRecPtr last_received)
/* Ensure we are reading the data into our memory context. */ /* Ensure we are reading the data into our memory context. */
MemoryContextSwitchTo(ApplyMessageContext); MemoryContextSwitchTo(ApplyMessageContext);
s.data = buf; initReadOnlyStringInfo(&s, buf, len);
s.len = len;
s.cursor = 0;
s.maxlen = -1;
c = pq_getmsgbyte(&s); c = pq_getmsgbyte(&s);

View File

@ -1817,23 +1817,19 @@ exec_bind_message(StringInfo input_message)
if (!isNull) if (!isNull)
{ {
const char *pvalue = pq_getmsgbytes(input_message, plength); char *pvalue;
/* /*
* Rather than copying data around, we just set up a phony * Rather than copying data around, we just initialize a
* StringInfo pointing to the correct portion of the message * StringInfo pointing to the correct portion of the message
* buffer. We assume we can scribble on the message buffer so * buffer. We assume we can scribble on the message buffer to
* as to maintain the convention that StringInfos have a * add a trailing NUL which is required for the input function
* trailing null. This is grotty but is a big win when * call.
* dealing with very large parameter strings.
*/ */
pbuf.data = unconstify(char *, pvalue); pvalue = unconstify(char *, pq_getmsgbytes(input_message, plength));
pbuf.maxlen = plength + 1; csave = pvalue[plength];
pbuf.len = plength; pvalue[plength] = '\0';
pbuf.cursor = 0; initReadOnlyStringInfo(&pbuf, pvalue, plength);
csave = pbuf.data[plength];
pbuf.data[plength] = '\0';
} }
else else
{ {

View File

@ -784,7 +784,6 @@ array_agg_deserialize(PG_FUNCTION_ARGS)
{ {
int itemlen; int itemlen;
StringInfoData elem_buf; StringInfoData elem_buf;
char csave;
if (result->dnulls[i]) if (result->dnulls[i])
{ {
@ -799,28 +798,19 @@ array_agg_deserialize(PG_FUNCTION_ARGS)
errmsg("insufficient data left in message"))); errmsg("insufficient data left in message")));
/* /*
* Rather than copying data around, we just set up a phony * Rather than copying data around, we just initialize a
* StringInfo pointing to the correct portion of the input buffer. * StringInfo pointing to the correct portion of the message
* We assume we can scribble on the input buffer so as to maintain * buffer.
* the convention that StringInfos have a trailing null.
*/ */
elem_buf.data = &buf.data[buf.cursor]; initReadOnlyStringInfo(&elem_buf, &buf.data[buf.cursor], itemlen);
elem_buf.maxlen = itemlen + 1;
elem_buf.len = itemlen;
elem_buf.cursor = 0;
buf.cursor += itemlen; buf.cursor += itemlen;
csave = buf.data[buf.cursor];
buf.data[buf.cursor] = '\0';
/* Now call the element's receiveproc */ /* Now call the element's receiveproc */
result->dvalues[i] = ReceiveFunctionCall(&iodata->typreceive, result->dvalues[i] = ReceiveFunctionCall(&iodata->typreceive,
&elem_buf, &elem_buf,
iodata->typioparam, iodata->typioparam,
-1); -1);
buf.data[buf.cursor] = csave;
} }
} }

View File

@ -1475,7 +1475,6 @@ ReadArrayBinary(StringInfo buf,
{ {
int itemlen; int itemlen;
StringInfoData elem_buf; StringInfoData elem_buf;
char csave;
/* Get and check the item length */ /* Get and check the item length */
itemlen = pq_getmsgint(buf, 4); itemlen = pq_getmsgint(buf, 4);
@ -1494,21 +1493,13 @@ ReadArrayBinary(StringInfo buf,
} }
/* /*
* Rather than copying data around, we just set up a phony StringInfo * Rather than copying data around, we just initialize a StringInfo
* pointing to the correct portion of the input buffer. We assume we * pointing to the correct portion of the message buffer.
* can scribble on the input buffer so as to maintain the convention
* that StringInfos have a trailing null.
*/ */
elem_buf.data = &buf->data[buf->cursor]; initReadOnlyStringInfo(&elem_buf, &buf->data[buf->cursor], itemlen);
elem_buf.maxlen = itemlen + 1;
elem_buf.len = itemlen;
elem_buf.cursor = 0;
buf->cursor += itemlen; buf->cursor += itemlen;
csave = buf->data[buf->cursor];
buf->data[buf->cursor] = '\0';
/* Now call the element's receiveproc */ /* Now call the element's receiveproc */
values[i] = ReceiveFunctionCall(receiveproc, &elem_buf, values[i] = ReceiveFunctionCall(receiveproc, &elem_buf,
typioparam, typmod); typioparam, typmod);
@ -1520,8 +1511,6 @@ ReadArrayBinary(StringInfo buf,
(errcode(ERRCODE_INVALID_BINARY_REPRESENTATION), (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
errmsg("improper binary format in array element %d", errmsg("improper binary format in array element %d",
i + 1))); i + 1)));
buf->data[buf->cursor] = csave;
} }
/* /*

View File

@ -569,7 +569,6 @@ record_recv(PG_FUNCTION_ARGS)
int itemlen; int itemlen;
StringInfoData item_buf; StringInfoData item_buf;
StringInfo bufptr; StringInfo bufptr;
char csave;
/* Ignore dropped columns in datatype, but fill with nulls */ /* Ignore dropped columns in datatype, but fill with nulls */
if (att->attisdropped) if (att->attisdropped)
@ -619,25 +618,19 @@ record_recv(PG_FUNCTION_ARGS)
/* -1 length means NULL */ /* -1 length means NULL */
bufptr = NULL; bufptr = NULL;
nulls[i] = true; nulls[i] = true;
csave = 0; /* keep compiler quiet */
} }
else else
{ {
char *strbuff;
/* /*
* Rather than copying data around, we just set up a phony * Rather than copying data around, we just initialize a
* StringInfo pointing to the correct portion of the input buffer. * StringInfo pointing to the correct portion of the message
* We assume we can scribble on the input buffer so as to maintain * buffer.
* the convention that StringInfos have a trailing null.
*/ */
item_buf.data = &buf->data[buf->cursor]; strbuff = &buf->data[buf->cursor];
item_buf.maxlen = itemlen + 1;
item_buf.len = itemlen;
item_buf.cursor = 0;
buf->cursor += itemlen; buf->cursor += itemlen;
initReadOnlyStringInfo(&item_buf, strbuff, itemlen);
csave = buf->data[buf->cursor];
buf->data[buf->cursor] = '\0';
bufptr = &item_buf; bufptr = &item_buf;
nulls[i] = false; nulls[i] = false;
@ -667,8 +660,6 @@ record_recv(PG_FUNCTION_ARGS)
(errcode(ERRCODE_INVALID_BINARY_REPRESENTATION), (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
errmsg("improper binary format in record column %d", errmsg("improper binary format in record column %d",
i + 1))); i + 1)));
buf->data[buf->cursor] = csave;
} }
} }

View File

@ -70,10 +70,16 @@ initStringInfo(StringInfo str)
* *
* Reset the StringInfo: the data buffer remains valid, but its * Reset the StringInfo: the data buffer remains valid, but its
* previous content, if any, is cleared. * previous content, if any, is cleared.
*
* Read-only StringInfos as initialized by initReadOnlyStringInfo cannot be
* reset.
*/ */
void void
resetStringInfo(StringInfo str) resetStringInfo(StringInfo str)
{ {
/* don't allow resets of read-only StringInfos */
Assert(str->maxlen != 0);
str->data[0] = '\0'; str->data[0] = '\0';
str->len = 0; str->len = 0;
str->cursor = 0; str->cursor = 0;
@ -284,6 +290,9 @@ enlargeStringInfo(StringInfo str, int needed)
{ {
int newlen; int newlen;
/* validate this is not a read-only StringInfo */
Assert(str->maxlen != 0);
/* /*
* Guard against out-of-range "needed" values. Without this, we can get * Guard against out-of-range "needed" values. Without this, we can get
* an overflow or infinite loop in the following. * an overflow or infinite loop in the following.

View File

@ -20,17 +20,27 @@
/*------------------------- /*-------------------------
* StringInfoData holds information about an extensible string. * StringInfoData holds information about an extensible string.
* data is the current buffer for the string (allocated with palloc). * data is the current buffer for the string.
* len is the current string length. There is guaranteed to be * len is the current string length. Except in the case of read-only
* a terminating '\0' at data[len], although this is not very * strings described below, there is guaranteed to be a
* useful when the string holds binary data rather than text. * terminating '\0' at data[len].
* maxlen is the allocated size in bytes of 'data', i.e. the maximum * maxlen is the allocated size in bytes of 'data', i.e. the maximum
* string size (including the terminating '\0' char) that we can * string size (including the terminating '\0' char) that we can
* currently store in 'data' without having to reallocate * currently store in 'data' without having to reallocate
* more space. We must always have maxlen > len. * more space. We must always have maxlen > len, except
* cursor is initialized to zero by makeStringInfo or initStringInfo, * in the read-only case described below.
* but is not otherwise touched by the stringinfo.c routines. * cursor is initialized to zero by makeStringInfo, initStringInfo,
* Some routines use it to scan through a StringInfo. * initReadOnlyStringInfo and initStringInfoFromString but is not
* otherwise touched by the stringinfo.c routines. Some routines
* use it to scan through a StringInfo.
*
* As a special case, a StringInfoData can be initialized with a read-only
* string buffer. In this case "data" does not necessarily point at a
* palloc'd chunk, and management of the buffer storage is the caller's
* responsibility. maxlen is set to zero to indicate that this is the case.
* Read-only StringInfoDatas cannot be appended to or reset.
* Also, it is caller's option whether a read-only string buffer has a
* terminating '\0' or not. This depends on the intended usage.
*------------------------- *-------------------------
*/ */
typedef struct StringInfoData typedef struct StringInfoData
@ -45,7 +55,7 @@ typedef StringInfoData *StringInfo;
/*------------------------ /*------------------------
* There are two ways to create a StringInfo object initially: * There are four ways to create a StringInfo object initially:
* *
* StringInfo stringptr = makeStringInfo(); * StringInfo stringptr = makeStringInfo();
* Both the StringInfoData and the data buffer are palloc'd. * Both the StringInfoData and the data buffer are palloc'd.
@ -56,8 +66,31 @@ typedef StringInfoData *StringInfo;
* This is the easiest approach for a StringInfo object that will * This is the easiest approach for a StringInfo object that will
* only live as long as the current routine. * only live as long as the current routine.
* *
* StringInfoData string;
* initReadOnlyStringInfo(&string, existingbuf, len);
* The StringInfoData's data field is set to point directly to the
* existing buffer and the StringInfoData's len is set to the given len.
* The given buffer can point to memory that's not managed by palloc or
* is pointing partway through a palloc'd chunk. The maxlen field is set
* to 0. A read-only StringInfo cannot be appended to using any of the
* appendStringInfo functions or reset with resetStringInfo(). The given
* buffer can optionally omit the trailing NUL.
*
* StringInfoData string;
* initStringInfoFromString(&string, palloced_buf, len);
* The StringInfoData's data field is set to point directly to the given
* buffer and the StringInfoData's len is set to the given len. This
* method of initialization is useful when the buffer already exists.
* StringInfos initialized this way can be appended to using the
* appendStringInfo functions and reset with resetStringInfo(). The
* given buffer must be NUL-terminated. The palloc'd buffer is assumed
* to be len + 1 in size.
*
* To destroy a StringInfo, pfree() the data buffer, and then pfree() the * To destroy a StringInfo, pfree() the data buffer, and then pfree() the
* StringInfoData if it was palloc'd. There's no special support for this. * StringInfoData if it was palloc'd. There's no special support for this.
* However, if the StringInfo was initialized using initReadOnlyStringInfo()
* then the caller will need to consider if it is safe to pfree the data
* buffer.
* *
* NOTE: some routines build up a string using StringInfo, and then * NOTE: some routines build up a string using StringInfo, and then
* release the StringInfoData but return the data string itself to their * release the StringInfoData but return the data string itself to their
@ -79,6 +112,48 @@ extern StringInfo makeStringInfo(void);
*/ */
extern void initStringInfo(StringInfo str); extern void initStringInfo(StringInfo str);
/*------------------------
* initReadOnlyStringInfo
* Initialize a StringInfoData struct from an existing string without copying
* the string. The caller is responsible for ensuring the given string
* remains valid as long as the StringInfoData does. Calls to this are used
* in performance critical locations where allocating a new buffer and copying
* would be too costly. Read-only StringInfoData's may not be appended to
* using any of the appendStringInfo functions or reset with
* resetStringInfo().
*
* 'data' does not need to point directly to a palloc'd chunk of memory and may
* omit the NUL termination character at data[len].
*/
static inline void
initReadOnlyStringInfo(StringInfo str, char *data, int len)
{
str->data = data;
str->len = len;
str->maxlen = 0; /* read-only */
str->cursor = 0;
}
/*------------------------
* initStringInfoFromString
* Initialize a StringInfoData struct from an existing string without copying
* the string. 'data' must be a valid palloc'd chunk of memory that can have
* repalloc() called should more space be required during a call to any of the
* appendStringInfo functions.
*
* 'data' must be NUL terminated at 'len' bytes.
*/
static inline void
initStringInfoFromString(StringInfo str, char *data, int len)
{
Assert(data[len] == '\0');
str->data = data;
str->len = len;
str->maxlen = len + 1;
str->cursor = 0;
}
/*------------------------ /*------------------------
* resetStringInfo * resetStringInfo
* Clears the current content of the StringInfo, if any. The * Clears the current content of the StringInfo, if any. The