pgsql: Preserve memory context of VarStringSortSupport buffers. - Mailing list pgsql-committers

From Tom Lane
Subject pgsql: Preserve memory context of VarStringSortSupport buffers.
Date
Msg-id E1oNG7Q-000lBv-Pn@gemulon.postgresql.org
Whole thread Raw
List pgsql-committers
Preserve memory context of VarStringSortSupport buffers.

When enlarging the work buffers of a VarStringSortSupport object,
varstrfastcmp_locale was careful to keep them in the ssup_cxt
memory context; but varstr_abbrev_convert just used palloc().
The latter creates a hazard that the buffers could be freed out
from under the VarStringSortSupport object, resulting in stomping
on whatever gets allocated in that memory later.

In practice, because we only use this code for ICU collations
(cf. 3df9c374e), the problem is confined to use of ICU collations.
I believe it may have been unreachable before the introduction
of incremental sort, too, as traditional sorting usually just
uses one context for the duration of the sort.

We could fix this by making the broken stanzas in varstr_abbrev_convert
match the non-broken ones in varstrfastcmp_locale.  However, it seems
like a better idea to dodge the issue altogether by replacing the
pfree-and-allocate-anew coding with repalloc, which automatically
preserves the chunk's memory context.  This fix does add a few cycles
because repalloc will copy the chunk's content, which the existing
coding assumes is useless.  However, we don't expect that these buffer
enlargement operations are performance-critical.  Besides that, it's
far from obvious that copying the buffer contents isn't required, since
these stanzas make no effort to mark the buffers invalid by resetting
last_returned, cache_blob, etc.  That seems to be safe upon examination,
but it's fragile and could easily get broken in future, which wouldn't
get revealed in testing with short-to-moderate-size strings.

Per bug #17584 from James Inform.  Whether or not the issue is
reachable in the older branches, this code has been broken on its
own terms from its introduction, so patch all the way back.

Discussion: https://postgr.es/m/17584-95c79b4a7d771f44@postgresql.org

Branch
------
REL_13_STABLE

Details
-------
https://git.postgresql.org/pg/commitdiff/9fe285f8597d4a3ab3fce9223891b2af01a3393b

Modified Files
--------------
src/backend/utils/adt/varlena.c | 16 ++++++----------
1 file changed, 6 insertions(+), 10 deletions(-)


pgsql-committers by date:

Previous
From: Andres Freund
Date:
Subject: Re: [HACKERS] [COMMITTERS] pgsql: Improve performance of SendRowDescriptionMessage.
Next
From: Michael Paquier
Date:
Subject: pgsql: Fix outdated --help message for postgres -f