Re: pnstrdup considered armed and dangerous

From: Andres Freund <andres(at)anarazel(dot)de>
To: pgsql-hackers(at)postgresql(dot)org
Subject: Re: pnstrdup considered armed and dangerous
Date: 2017-10-03 06:55:02
Message-ID: 20171003065502.4tve5ek2z46xdb6h@alap3.anarazel.de
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On 2016-10-03 14:55:24 -0700, Andres Freund wrote:
> Hi,
>
> A colleage of me just wrote innocent looking code like
> char *shardRelationName = pnstrdup(relationName, NAMEDATALEN);
> which is at the moment wrong if relationName isn't preallocated to
> NAMEDATALEN size.
>
> /*
> * pnstrdup
> * Like pstrdup(), but append null byte to a
> * not-necessarily-null-terminated input string.
> */
> char *
> pnstrdup(const char *in, Size len)
> {
> char *out = palloc(len + 1);
>
> memcpy(out, in, len);
> out[len] = '\0';
> return out;
> }
>
> isn't that a somewhat weird behaviour / implementation? Not really like
> strndup(), which one might believe to be analoguous...

I've since hit this bug again. To fix it, you'd need strnlen. The lack
of which I'd also independently hit twice. So here's a patch adding
pg_strnlen and using that to fix pnstrdup.

Greetings,

Andres Freund

Attachment Content-Type Size
0001-Add-pg_strnlen-a-portable-implementation-of-strlen.patch text/x-diff 4.4 KB
0002-Fix-pnstrdup-to-not-memcpy-the-maximum-allowed-lengt.patch text/x-diff 1.2 KB

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message Andreas Seltenreich 2017-10-03 07:04:50 Re: [sqlsmith] crash in RestoreLibraryState during low-memory testing
Previous Message Kyotaro HORIGUCHI 2017-10-03 06:16:49 Re: proposal - Default namespaces for XPath expressions (PostgreSQL 11)