From af0f20092c8662bf7610fab07b8a1e354abba67f Mon Sep 17 00:00:00 2001
From: Tom Lane <tgl@sss.pgh.pa.us>
Date: Mon, 25 Apr 2011 16:22:12 -0400
Subject: [PATCH] Fix pg_size_pretty() to avoid overflow for inputs close to
 INT64_MAX.

The expression that tried to round the value to the nearest TB could
overflow, leading to bogus output as reported in bug #5993 from Nicola
Cossu.  This isn't likely to ever happen in the intended usage of the
function (if it could, we'd be needing to use a wider datatype instead);
but it's not hard to give the expected output, so let's do so.
---
 src/backend/utils/adt/dbsize.c | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)

diff --git a/src/backend/utils/adt/dbsize.c b/src/backend/utils/adt/dbsize.c
index 73a6ad32808..aa4066f9f05 100644
--- a/src/backend/utils/adt/dbsize.c
+++ b/src/backend/utils/adt/dbsize.c
@@ -490,9 +490,15 @@ pg_size_pretty(PG_FUNCTION_ARGS)
 							 (size + mult / 2) / mult);
 				else
 				{
+					/* Here we have to worry about avoiding overflow */
+					int64	val;
+
 					mult *= 1024;
+					val = size / mult;
+					if ((size % mult) >= (mult / 2))
+						val++;
 					snprintf(buf, sizeof(buf), INT64_FORMAT " TB",
-							 (size + mult / 2) / mult);
+							 val);
 				}
 			}
 		}
-- 
GitLab