Fix bugs in sqlchar_to_unicode and unicode_to_sqlchar: both were measuring
authorTom Lane <tgl@sss.pgh.pa.us>
Mon, 10 Nov 2008 18:02:27 +0000 (18:02 +0000)
committerTom Lane <tgl@sss.pgh.pa.us>
Mon, 10 Nov 2008 18:02:27 +0000 (18:02 +0000)
the length of a UTF8 character with pg_mblen (wrong if DB encoding isn't
UTF8), and the latter was blithely assuming that a static buffer would somehow
revert to all zeroes for each use.

src/backend/utils/adt/xml.c

index 98781cc523b97f89a208d9462bd0db5a0e4ecb59..e3cd95bedd41402ba08e2dcd8997cc3cb9c1e850 100644 (file)
@@ -7,7 +7,7 @@
  * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
  * Portions Copyright (c) 1994, Regents of the University of California
  *
- * $PostgreSQL: pgsql/src/backend/utils/adt/xml.c,v 1.68.2.5 2008/10/09 15:49:10 tgl Exp $
+ * $PostgreSQL: pgsql/src/backend/utils/adt/xml.c,v 1.68.2.6 2008/11/10 18:02:27 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -1447,7 +1447,11 @@ sqlchar_to_unicode(char *s)
                                                    GetDatabaseEncoding(),
                                                    PG_UTF8);
 
-   pg_encoding_mb2wchar_with_len(PG_UTF8, utf8string, ret, pg_mblen(s));
+   pg_encoding_mb2wchar_with_len(PG_UTF8, utf8string, ret,
+                                 pg_encoding_mblen(PG_UTF8, utf8string));
+
+   if (utf8string != s)
+       pfree(utf8string);
 
    return ret[0];
 }
@@ -1537,7 +1541,10 @@ map_sql_identifier_to_xml_name(char *ident, bool fully_escaped,
 static char *
 unicode_to_sqlchar(pg_wchar c)
 {
-   static unsigned char utf8string[5]; /* need trailing zero */
+   unsigned char utf8string[5]; /* need room for trailing zero */
+   char       *result;
+
+   memset(utf8string, 0, sizeof(utf8string));
 
    if (c <= 0x7F)
    {
@@ -1562,10 +1569,15 @@ unicode_to_sqlchar(pg_wchar c)
        utf8string[3] = 0x80 | (c & 0x3F);
    }
 
-   return (char *) pg_do_encoding_conversion(utf8string,
-                                             pg_mblen((char *) utf8string),
-                                             PG_UTF8,
-                                             GetDatabaseEncoding());
+   result = (char *) pg_do_encoding_conversion(utf8string,
+                                               pg_encoding_mblen(PG_UTF8,
+                                                        (char *) utf8string),
+                                               PG_UTF8,
+                                               GetDatabaseEncoding());
+   /* if pg_do_encoding_conversion didn't strdup, we must */
+   if (result == (char *) utf8string)
+       result = pstrdup(result);
+   return result;
 }