Skip to content

Commit cb6ab91

Browse files
committed
Fix cidin() to handle values above 2^31 platform-independently.
CommandId is declared as uint32, and values up to 4G are indeed legal. cidout() handles them properly by treating the value as unsigned int. But cidin() was just using atoi(), which has platform-dependent behavior for values outside the range of signed int, as reported by Bart Lengkeek in bug #14379. Use strtoul() instead, as xidin() does. In passing, make some purely cosmetic changes to make xidin/xidout look more like cidin/cidout; the former didn't have a monopoly on best practice IMO. Neither xidin nor cidin make any attempt to throw error for invalid input. I didn't change that here, and am not sure it's worth worrying about since neither is really a user-facing type. The point is just to ensure that indubitably-valid inputs work as expected. It's been like this for a long time, so back-patch to all supported branches. Report: <20161018152550.1413.6439@wrigleys.postgresql.org>
1 parent a5f0bd7 commit cb6ab91

File tree

1 file changed

+6
-12
lines changed
  • src/backend/utils/adt

1 file changed

+6
-12
lines changed

src/backend/utils/adt/xid.c

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -41,13 +41,10 @@ Datum
4141
xidout(PG_FUNCTION_ARGS)
4242
{
4343
TransactionId transactionId = PG_GETARG_TRANSACTIONID(0);
44+
char *result = (char *) palloc(16);
4445

45-
/* maximum 32 bit unsigned integer representation takes 10 chars */
46-
char *str = palloc(11);
47-
48-
snprintf(str, 11, "%lu", (unsigned long) transactionId);
49-
50-
PG_RETURN_CSTRING(str);
46+
snprintf(result, 16, "%lu", (unsigned long) transactionId);
47+
PG_RETURN_CSTRING(result);
5148
}
5249

5350
/*
@@ -160,12 +157,9 @@ xidComparator(const void *arg1, const void *arg2)
160157
Datum
161158
cidin(PG_FUNCTION_ARGS)
162159
{
163-
char *s = PG_GETARG_CSTRING(0);
164-
CommandId c;
165-
166-
c = atoi(s);
160+
char *str = PG_GETARG_CSTRING(0);
167161

168-
PG_RETURN_COMMANDID(c);
162+
PG_RETURN_COMMANDID((CommandId) strtoul(str, NULL, 0));
169163
}
170164

171165
/*
@@ -177,7 +171,7 @@ cidout(PG_FUNCTION_ARGS)
177171
CommandId c = PG_GETARG_COMMANDID(0);
178172
char *result = (char *) palloc(16);
179173

180-
snprintf(result, 16, "%u", (unsigned int) c);
174+
snprintf(result, 16, "%lu", (unsigned long) c);
181175
PG_RETURN_CSTRING(result);
182176
}
183177

0 commit comments

Comments
 (0)