From: Tom Lane Date: Fri, 25 May 2012 21:34:58 +0000 (-0400) Subject: Fix string truncation to be multibyte-aware in text_name and bpchar_name. X-Git-Tag: REL9_1_4~11 X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=71e985a07a7ae9319c00629f319a4c30a9e32fd6;p=postgresql Fix string truncation to be multibyte-aware in text_name and bpchar_name. Previously, casts to name could generate invalidly-encoded results. Also, make these functions match namein() more exactly, by consistently using palloc0() instead of ad-hoc zeroing code. Back-patch to all supported branches. Karl Schnaitter and Tom Lane --- diff --git a/src/backend/utils/adt/name.c b/src/backend/utils/adt/name.c index 09c12efd8d..a2fee8e4d6 100644 --- a/src/backend/utils/adt/name.c +++ b/src/backend/utils/adt/name.c @@ -46,13 +46,17 @@ Datum namein(PG_FUNCTION_ARGS) { char *s = PG_GETARG_CSTRING(0); - NameData *result; + Name result; int len; len = strlen(s); - len = pg_mbcliplen(s, len, NAMEDATALEN - 1); - result = (NameData *) palloc0(NAMEDATALEN); + /* Truncate oversize input */ + if (len >= NAMEDATALEN) + len = pg_mbcliplen(s, len, NAMEDATALEN - 1); + + /* We use palloc0 here to ensure result is zero-padded */ + result = (Name) palloc0(NAMEDATALEN); memcpy(NameStr(*result), s, len); PG_RETURN_NAME(result); diff --git a/src/backend/utils/adt/varchar.c b/src/backend/utils/adt/varchar.c index 1c0ef921a7..7b84637f8c 100644 --- a/src/backend/utils/adt/varchar.c +++ b/src/backend/utils/adt/varchar.c @@ -371,9 +371,9 @@ bpchar_name(PG_FUNCTION_ARGS) len = VARSIZE_ANY_EXHDR(s); s_data = VARDATA_ANY(s); - /* Truncate to max length for a Name */ + /* Truncate oversize input */ if (len >= NAMEDATALEN) - len = NAMEDATALEN - 1; + len = pg_mbcliplen(s_data, len, NAMEDATALEN - 1); /* Remove trailing blanks */ while (len > 0) @@ -383,16 +383,10 @@ bpchar_name(PG_FUNCTION_ARGS) len--; } - result = (NameData *) palloc(NAMEDATALEN); + /* We use palloc0 here to ensure result is zero-padded */ + result = (Name) palloc0(NAMEDATALEN); memcpy(NameStr(*result), s_data, len); - /* Now null pad to full length... */ - while (len < NAMEDATALEN) - { - *(NameStr(*result) + len) = '\0'; - len++; - } - PG_RETURN_NAME(result); } diff --git a/src/backend/utils/adt/varlena.c b/src/backend/utils/adt/varlena.c index 124000fe7f..3e2243958a 100644 --- a/src/backend/utils/adt/varlena.c +++ b/src/backend/utils/adt/varlena.c @@ -2198,18 +2198,12 @@ text_name(PG_FUNCTION_ARGS) /* Truncate oversize input */ if (len >= NAMEDATALEN) - len = NAMEDATALEN - 1; + len = pg_mbcliplen(VARDATA_ANY(s), len, NAMEDATALEN - 1); - result = (Name) palloc(NAMEDATALEN); + /* We use palloc0 here to ensure result is zero-padded */ + result = (Name) palloc0(NAMEDATALEN); memcpy(NameStr(*result), VARDATA_ANY(s), len); - /* now null pad to full length... */ - while (len < NAMEDATALEN) - { - *(NameStr(*result) + len) = '\0'; - len++; - } - PG_RETURN_NAME(result); }