Re: may be a buffer overflow problem

From: Laurenz Albe <laurenz(dot)albe(at)cybertec(dot)at>
To: Winter Loo <winterloo(at)126(dot)com>, pgsql-hackers(at)lists(dot)postgresql(dot)org
Subject: Re: may be a buffer overflow problem
Date: 2024-06-14 08:04:45
Message-ID: 07bbd5b66d15357a4da3a820550bf96e01367e0d.camel@cybertec.at
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On Fri, 2024-06-14 at 15:38 +0800, Winter Loo wrote:
> I am using gcc version 11.3.0 to compile postgres source code. Gcc complains about the following line:
>
> strncpy(sqlca->sqlstate, "YE001", sizeof(sqlca->sqlstate));
>
> with error as:
>
> misc.c:529:17: error: ‘strncpy’ output truncated before terminating nul
> copying 5 bytes from a string of the same length [-Werror=stringop-truncation]
>
> I find the definition of `sqlca->sqlstate` and it has only 5 bytes. When the statement
>
> strncpy(sqlca->sqlstate, "YE001", sizeof(sqlca->sqlstate));
>
> get executed, `sqlca->sqlstate` will have no '\0' byte which makes me anxious
> when someone prints that as a string. Indeed, I found the code(in src/interfaces/ecpg/ecpglib/misc.c) does that,
>
> fprintf(debugstream, "[NO_PID]: sqlca: code: %ld, state: %s\n",
> sqlca->sqlcode, sqlca->sqlstate);
>
> Is there any chance to fix the code?

I agree that that is wrong.

We could either use memcpy() to avoid the warning and use a format string
with %.*s in fprintf(), or we could make the "sqlstate" one byte longer.

I think that the second option would be less error-prone.

Yours,
Laurenz Albe

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message Laurenz Albe 2024-06-14 08:06:58 Re: may be a buffer overflow problem
Previous Message Daniel Gustafsson 2024-06-14 07:55:12 Re: may be a buffer overflow problem