Re: pg_stat_get_activity(): integer overflow due to (int) * (int) for MemoryContextAllocHuge()

From: Michael Paquier <michael(at)paquier(dot)xyz>
To: Jakub Wartak <jakub(dot)wartak(at)enterprisedb(dot)com>
Cc: Andres Freund <andres(at)anarazel(dot)de>, Peter Eisentraut <peter(at)eisentraut(dot)org>, PostgreSQL Hackers <pgsql-hackers(at)postgresql(dot)org>, Robert Haas <robertmhaas(at)gmail(dot)com>
Subject: Re: pg_stat_get_activity(): integer overflow due to (int) * (int) for MemoryContextAllocHuge()
Date: 2023-09-29 02:00:07
Message-ID: ZRYvp0vW_i4mWwIE@paquier.xyz
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On Thu, Sep 28, 2023 at 11:01:14AM +0200, Jakub Wartak wrote:
> v3 attached. I had a problem coming out with a better error message,
> so suggestions are welcome. The cast still needs to be present as per
> above suggestion as 3GB is still valid buf size and still was causing
> integer overflow. We just throw an error on >= 4GB with v3.

+/* Safety net to prevent requesting huge memory by each query to pg_stat_activity */
+#define PGSTAT_MAX_ACTIVITY_BUF_SIZE 4 * 1024 * 1024 * 1024L

- size = add_size(size,
- mul_size(pgstat_track_activity_query_size, NumBackendStatSlots));
+ pgstat_track_size = mul_size(pgstat_track_activity_query_size,
+ NumBackendStatSlots);
+ if(pgstat_track_size >= PGSTAT_MAX_ACTIVITY_BUF_SIZE)
+ elog(FATAL, "too big Backend Activity Buffer allocation of %zu bytes", pgstat_track_size);
+ size = add_size(size, pgstat_track_size);

That should be enough to put in a hardcoded 4GB safety limit, while
mul_size() detects it at a higher range. Note, however, that elog()
is only used for internal errors that users should never face, but
this one can come from a misconfiguration. This would be better as an
ereport(), with ERRCODE_CONFIG_FILE_ERROR as errcode, I guess.

"Backend Activity Buffer" is the name of the internal struct. Sure,
it shows up on the system views for shmem, but I wouldn't use this
term in a user-facing error message. Perhaps something like "size
requested for backend status is out of range" would be cleaner. Other
ideas are welcome.
--
Michael

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Hayato Kuroda (Fujitsu) 2023-09-29 02:05:46 RE: [PGdocs] fix description for handling pf non-ASCII characters
Previous Message Peter Geoghegan 2023-09-29 01:57:07 Re: Index range search optimization