Re: Small patch to improve safety of utf8_to_unicode().

From: Jeff Davis <pgsql(at)j-davis(dot)com>
To: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>, Chao Li <li(dot)evan(dot)chao(at)gmail(dot)com>
Cc: pgsql-hackers(at)postgresql(dot)org
Subject: Re: Small patch to improve safety of utf8_to_unicode().
Date: 2026-07-13 17:09:34
Message-ID: ea061fe938602cd4321ed17742284ca86310defe.camel@j-davis.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On Mon, 2026-07-13 at 09:42 -0400, Tom Lane wrote:
> What I think this is pointing out is that even if the input string's
> length fits in size_t, the length of the case-converted equivalent
> string might not.  The code won't write past dstsize, but it will
> try to compute the full output length required, and it won't notice
> if result_len overflows and wraps around.
>
> I would have written this off as an unreachable edge case, but our
> recent experience with unicode_normalize (cf. commit 066b7b144)
> makes me hesitant to assume that case-folding can't result in
> integer-multiple growth of the string length.  If it can, the
> overflow
> might be reachable on 32-bit platforms, resulting in a silently-
> broken
> result (but no memory clobber AFAICS).

From Unicode 17.0 section 5.18.2: "the maximum string expansion as a
result of case mapping in the Unicode Standard is three". Along with a
potential for 4X difference in byte length for a single code point in
UTF8, that makes a maximum of 12X expansion.

> Catering for this case seems like it would require messy warts on the
> casefolding functions' API.  So if we can convince ourselves that
> overflow can't really occur, I'd be content to add a comment
> demonstrating that.

Based on the actual data I expect the worst case to be smaller,
probably 3X. That would be convenient because I think that means it
can't overflow: the largest text value we support is 1GB, while 3GB
would still fit in a size_t. Unfortunately, even if that's true today,
it would be hard to be confident it won't change in a future version of
Unicode.

>   But if we can't prove that, I think we need some
> warts :-(

07211f64ac at least has an error path already, so we could set
*pconsumed=0 on overflow and return SIZE_MAX. It would be extra work
for the caller if it wants to distinguish between overflow and an
encoding error, but if we aren't expecting to hit it in practice, then
maybe it's OK to give an incorrect error.

Regards,
Jeff Davis

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Tom Lane 2026-07-13 17:19:03 Re: Small patch to improve safety of utf8_to_unicode().
Previous Message Diego 2026-07-13 17:02:03 Re: libpq: decouple the .pgpass lookup port from the connection port