Fix string truncation to be multibyte-aware in text_name and bpchar_name.
authorTom Lane <tgl@sss.pgh.pa.us>
Fri, 25 May 2012 21:35:14 +0000 (17:35 -0400)
committerTom Lane <tgl@sss.pgh.pa.us>
Fri, 25 May 2012 21:35:14 +0000 (17:35 -0400)
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

src/backend/utils/adt/name.c
src/backend/utils/adt/varchar.c
src/backend/utils/adt/varlena.c

index 23b3722375e4674ba21237152a09a96dd2f34664..9729c0d3acca21288fdfa00482dbe30db535ecf1 100644 (file)
@@ -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);
index c25385dee77997a22b087b78d96bda382ad0468c..aac1039f5510ef9404be1b42a23fd85b92080bc3 100644 (file)
@@ -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);
 }
 
index b9b54e6db636fedd93ea3ea65e5087323dd78a6c..c8552a87c9f4621a30c20b867867b2345f5bedd3 100644 (file)
@@ -1936,18 +1936,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);
 }