LCOV - differential code coverage report
Current view: top level - src/backend/utils/mb - mbutils.c (source / functions) Coverage Total Hit UBC CBC EUB ECB
Current: c70b6db34ffeab48beef1fb4ce61bcad3772b8dd vs 06473f5a344df8c9594ead90a609b86f6724cff8 Lines: 63.9 % 537 343 194 343
Current Date: 2025-09-06 07:49:51 +0900 Functions: 81.8 % 55 45 10 45
Baseline: lcov-20250906-005545-baseline Branches: 46.3 % 378 175 203 175 19 5
Baseline Date: 2025-09-05 08:21:35 +0100 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(30,360] days: 100.0 % 3 3 3
(360..) days: 63.7 % 534 340 194 340
Function coverage date bins:
(360..) days: 81.8 % 55 45 10 45
Branch coverage date bins:
(360..) days: 43.5 % 402 175 203 175 19 5

 Age         Owner                    Branch data    TLA  Line data    Source code
                                  1                 :                : /*-------------------------------------------------------------------------
                                  2                 :                :  *
                                  3                 :                :  * mbutils.c
                                  4                 :                :  *    This file contains functions for encoding conversion.
                                  5                 :                :  *
                                  6                 :                :  * The string-conversion functions in this file share some API quirks.
                                  7                 :                :  * Note the following:
                                  8                 :                :  *
                                  9                 :                :  * The functions return a palloc'd, null-terminated string if conversion
                                 10                 :                :  * is required.  However, if no conversion is performed, the given source
                                 11                 :                :  * string pointer is returned as-is.
                                 12                 :                :  *
                                 13                 :                :  * Although the presence of a length argument means that callers can pass
                                 14                 :                :  * non-null-terminated strings, care is required because the same string
                                 15                 :                :  * will be passed back if no conversion occurs.  Such callers *must* check
                                 16                 :                :  * whether result == src and handle that case differently.
                                 17                 :                :  *
                                 18                 :                :  * If the source and destination encodings are the same, the source string
                                 19                 :                :  * is returned without any verification; it's assumed to be valid data.
                                 20                 :                :  * If that might not be the case, the caller is responsible for validating
                                 21                 :                :  * the string using a separate call to pg_verify_mbstr().  Whenever the
                                 22                 :                :  * source and destination encodings are different, the functions ensure that
                                 23                 :                :  * the result is validly encoded according to the destination encoding.
                                 24                 :                :  *
                                 25                 :                :  *
                                 26                 :                :  * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
                                 27                 :                :  * Portions Copyright (c) 1994, Regents of the University of California
                                 28                 :                :  *
                                 29                 :                :  *
                                 30                 :                :  * IDENTIFICATION
                                 31                 :                :  *    src/backend/utils/mb/mbutils.c
                                 32                 :                :  *
                                 33                 :                :  *-------------------------------------------------------------------------
                                 34                 :                :  */
                                 35                 :                : #include "postgres.h"
                                 36                 :                : 
                                 37                 :                : #include "access/xact.h"
                                 38                 :                : #include "catalog/namespace.h"
                                 39                 :                : #include "mb/pg_wchar.h"
                                 40                 :                : #include "utils/fmgrprotos.h"
                                 41                 :                : #include "utils/memutils.h"
                                 42                 :                : #include "utils/relcache.h"
                                 43                 :                : #include "varatt.h"
                                 44                 :                : 
                                 45                 :                : /*
                                 46                 :                :  * We maintain a simple linked list caching the fmgr lookup info for the
                                 47                 :                :  * currently selected conversion functions, as well as any that have been
                                 48                 :                :  * selected previously in the current session.  (We remember previous
                                 49                 :                :  * settings because we must be able to restore a previous setting during
                                 50                 :                :  * transaction rollback, without doing any fresh catalog accesses.)
                                 51                 :                :  *
                                 52                 :                :  * Since we'll never release this data, we just keep it in TopMemoryContext.
                                 53                 :                :  */
                                 54                 :                : typedef struct ConvProcInfo
                                 55                 :                : {
                                 56                 :                :     int         s_encoding;     /* server and client encoding IDs */
                                 57                 :                :     int         c_encoding;
                                 58                 :                :     FmgrInfo    to_server_info; /* lookup info for conversion procs */
                                 59                 :                :     FmgrInfo    to_client_info;
                                 60                 :                : } ConvProcInfo;
                                 61                 :                : 
                                 62                 :                : static List *ConvProcList = NIL;    /* List of ConvProcInfo */
                                 63                 :                : 
                                 64                 :                : /*
                                 65                 :                :  * These variables point to the currently active conversion functions,
                                 66                 :                :  * or are NULL when no conversion is needed.
                                 67                 :                :  */
                                 68                 :                : static FmgrInfo *ToServerConvProc = NULL;
                                 69                 :                : static FmgrInfo *ToClientConvProc = NULL;
                                 70                 :                : 
                                 71                 :                : /*
                                 72                 :                :  * This variable stores the conversion function to convert from UTF-8
                                 73                 :                :  * to the server encoding.  It's NULL if the server encoding *is* UTF-8,
                                 74                 :                :  * or if we lack a conversion function for this.
                                 75                 :                :  */
                                 76                 :                : static FmgrInfo *Utf8ToServerConvProc = NULL;
                                 77                 :                : 
                                 78                 :                : /*
                                 79                 :                :  * These variables track the currently-selected encodings.
                                 80                 :                :  */
                                 81                 :                : static const pg_enc2name *ClientEncoding = &pg_enc2name_tbl[PG_SQL_ASCII];
                                 82                 :                : static const pg_enc2name *DatabaseEncoding = &pg_enc2name_tbl[PG_SQL_ASCII];
                                 83                 :                : static const pg_enc2name *MessageEncoding = &pg_enc2name_tbl[PG_SQL_ASCII];
                                 84                 :                : 
                                 85                 :                : /*
                                 86                 :                :  * During backend startup we can't set client encoding because we (a)
                                 87                 :                :  * can't look up the conversion functions, and (b) may not know the database
                                 88                 :                :  * encoding yet either.  So SetClientEncoding() just accepts anything and
                                 89                 :                :  * remembers it for InitializeClientEncoding() to apply later.
                                 90                 :                :  */
                                 91                 :                : static bool backend_startup_complete = false;
                                 92                 :                : static int  pending_client_encoding = PG_SQL_ASCII;
                                 93                 :                : 
                                 94                 :                : 
                                 95                 :                : /* Internal functions */
                                 96                 :                : static char *perform_default_encoding_conversion(const char *src,
                                 97                 :                :                                                  int len, bool is_client_to_server);
                                 98                 :                : static int  cliplen(const char *str, int len, int limit);
                                 99                 :                : 
                                100                 :                : 
                                101                 :                : /*
                                102                 :                :  * Prepare for a future call to SetClientEncoding.  Success should mean
                                103                 :                :  * that SetClientEncoding is guaranteed to succeed for this encoding request.
                                104                 :                :  *
                                105                 :                :  * (But note that success before backend_startup_complete does not guarantee
                                106                 :                :  * success after ...)
                                107                 :                :  *
                                108                 :                :  * Returns 0 if okay, -1 if not (bad encoding or can't support conversion)
                                109                 :                :  */
                                110                 :                : int
 5266 tgl@sss.pgh.pa.us         111                 :CBC       28892 : PrepareClientEncoding(int encoding)
                                112                 :                : {
                                113                 :                :     int         current_server_encoding;
                                114                 :                :     ListCell   *lc;
                                115                 :                : 
 8766 ishii@postgresql.org      116   [ +  -  -  + ]:          28892 :     if (!PG_VALID_FE_ENCODING(encoding))
 7178 neilc@samurai.com         117                 :UBC           0 :         return -1;
                                118                 :                : 
                                119                 :                :     /* Can't do anything during startup, per notes above */
 8168 tgl@sss.pgh.pa.us         120         [ +  + ]:CBC       28892 :     if (!backend_startup_complete)
 8451 ishii@postgresql.org      121                 :          14603 :         return 0;
                                122                 :                : 
 8168 tgl@sss.pgh.pa.us         123                 :          14289 :     current_server_encoding = GetDatabaseEncoding();
                                124                 :                : 
                                125                 :                :     /*
                                126                 :                :      * Check for cases that require no conversion function.
                                127                 :                :      */
                                128   [ +  +  +  + ]:          14289 :     if (current_server_encoding == encoding ||
 7178 neilc@samurai.com         129         [ +  + ]:           1396 :         current_server_encoding == PG_SQL_ASCII ||
                                130                 :                :         encoding == PG_SQL_ASCII)
 8168 tgl@sss.pgh.pa.us         131                 :          14279 :         return 0;
                                132                 :                : 
 6001                           133         [ +  - ]:             10 :     if (IsTransactionState())
                                134                 :                :     {
                                135                 :                :         /*
                                136                 :                :          * If we're in a live transaction, it's safe to access the catalogs,
                                137                 :                :          * so look up the functions.  We repeat the lookup even if the info is
                                138                 :                :          * already cached, so that we can react to changes in the contents of
                                139                 :                :          * pg_conversion.
                                140                 :                :          */
                                141                 :                :         Oid         to_server_proc,
                                142                 :                :                     to_client_proc;
                                143                 :                :         ConvProcInfo *convinfo;
                                144                 :                :         MemoryContext oldcontext;
                                145                 :                : 
                                146                 :             10 :         to_server_proc = FindDefaultConversionProc(encoding,
                                147                 :                :                                                    current_server_encoding);
                                148         [ -  + ]:             10 :         if (!OidIsValid(to_server_proc))
 6001 tgl@sss.pgh.pa.us         149                 :UBC           0 :             return -1;
 6001 tgl@sss.pgh.pa.us         150                 :CBC          10 :         to_client_proc = FindDefaultConversionProc(current_server_encoding,
                                151                 :                :                                                    encoding);
                                152         [ -  + ]:             10 :         if (!OidIsValid(to_client_proc))
 6001 tgl@sss.pgh.pa.us         153                 :UBC           0 :             return -1;
                                154                 :                : 
                                155                 :                :         /*
                                156                 :                :          * Load the fmgr info into TopMemoryContext (could still fail here)
                                157                 :                :          */
 6001 tgl@sss.pgh.pa.us         158                 :CBC          10 :         convinfo = (ConvProcInfo *) MemoryContextAlloc(TopMemoryContext,
                                159                 :                :                                                        sizeof(ConvProcInfo));
                                160                 :             10 :         convinfo->s_encoding = current_server_encoding;
                                161                 :             10 :         convinfo->c_encoding = encoding;
                                162                 :             10 :         fmgr_info_cxt(to_server_proc, &convinfo->to_server_info,
                                163                 :                :                       TopMemoryContext);
                                164                 :             10 :         fmgr_info_cxt(to_client_proc, &convinfo->to_client_info,
                                165                 :                :                       TopMemoryContext);
                                166                 :                : 
                                167                 :                :         /* Attach new info to head of list */
                                168                 :             10 :         oldcontext = MemoryContextSwitchTo(TopMemoryContext);
                                169                 :             10 :         ConvProcList = lcons(convinfo, ConvProcList);
                                170                 :             10 :         MemoryContextSwitchTo(oldcontext);
                                171                 :                : 
                                172                 :                :         /*
                                173                 :                :          * We cannot yet remove any older entry for the same encoding pair,
                                174                 :                :          * since it could still be in use.  SetClientEncoding will clean up.
                                175                 :                :          */
                                176                 :                : 
                                177                 :             10 :         return 0;               /* success */
                                178                 :                :     }
                                179                 :                :     else
                                180                 :                :     {
                                181                 :                :         /*
                                182                 :                :          * If we're not in a live transaction, the only thing we can do is
                                183                 :                :          * restore a previous setting using the cache.  This covers all
                                184                 :                :          * transaction-rollback cases.  The only case it might not work for is
                                185                 :                :          * trying to change client_encoding on the fly by editing
                                186                 :                :          * postgresql.conf and SIGHUP'ing.  Which would probably be a stupid
                                187                 :                :          * thing to do anyway.
                                188                 :                :          */
 6001 tgl@sss.pgh.pa.us         189   [ #  #  #  #  :UBC           0 :         foreach(lc, ConvProcList)
                                              #  # ]
                                190                 :                :         {
                                191                 :              0 :             ConvProcInfo *oldinfo = (ConvProcInfo *) lfirst(lc);
                                192                 :                : 
                                193         [ #  # ]:              0 :             if (oldinfo->s_encoding == current_server_encoding &&
                                194         [ #  # ]:              0 :                 oldinfo->c_encoding == encoding)
                                195                 :              0 :                 return 0;
                                196                 :                :         }
                                197                 :                : 
                                198                 :              0 :         return -1;              /* it's not cached, so fail */
                                199                 :                :     }
                                200                 :                : }
                                201                 :                : 
                                202                 :                : /*
                                203                 :                :  * Set the active client encoding and set up the conversion-function pointers.
                                204                 :                :  * PrepareClientEncoding should have been called previously for this encoding.
                                205                 :                :  *
                                206                 :                :  * Returns 0 if okay, -1 if not (bad encoding or can't support conversion)
                                207                 :                :  */
                                208                 :                : int
 5266 tgl@sss.pgh.pa.us         209                 :CBC       30180 : SetClientEncoding(int encoding)
                                210                 :                : {
                                211                 :                :     int         current_server_encoding;
                                212                 :                :     bool        found;
                                213                 :                :     ListCell   *lc;
                                214                 :                : 
                                215   [ +  -  -  + ]:          30180 :     if (!PG_VALID_FE_ENCODING(encoding))
 5266 tgl@sss.pgh.pa.us         216                 :UBC           0 :         return -1;
                                217                 :                : 
                                218                 :                :     /* Can't do anything during startup, per notes above */
 5266 tgl@sss.pgh.pa.us         219         [ +  + ]:CBC       30180 :     if (!backend_startup_complete)
                                220                 :                :     {
                                221                 :          14515 :         pending_client_encoding = encoding;
                                222                 :          14515 :         return 0;
                                223                 :                :     }
                                224                 :                : 
                                225                 :          15665 :     current_server_encoding = GetDatabaseEncoding();
                                226                 :                : 
                                227                 :                :     /*
                                228                 :                :      * Check for cases that require no conversion function.
                                229                 :                :      */
                                230   [ +  +  +  + ]:          15665 :     if (current_server_encoding == encoding ||
                                231         [ +  + ]:           1396 :         current_server_encoding == PG_SQL_ASCII ||
                                232                 :                :         encoding == PG_SQL_ASCII)
                                233                 :                :     {
                                234                 :          15655 :         ClientEncoding = &pg_enc2name_tbl[encoding];
                                235                 :          15655 :         ToServerConvProc = NULL;
                                236                 :          15655 :         ToClientConvProc = NULL;
                                237                 :          15655 :         return 0;
                                238                 :                :     }
                                239                 :                : 
                                240                 :                :     /*
                                241                 :                :      * Search the cache for the entry previously prepared by
                                242                 :                :      * PrepareClientEncoding; if there isn't one, we lose.  While at it,
                                243                 :                :      * release any duplicate entries so that repeated Prepare/Set cycles don't
                                244                 :                :      * leak memory.
                                245                 :                :      */
                                246                 :             10 :     found = false;
 2245                           247   [ +  -  +  +  :             23 :     foreach(lc, ConvProcList)
                                              +  + ]
                                248                 :                :     {
 5266                           249                 :             13 :         ConvProcInfo *convinfo = (ConvProcInfo *) lfirst(lc);
                                250                 :                : 
                                251         [ +  - ]:             13 :         if (convinfo->s_encoding == current_server_encoding &&
                                252         [ +  + ]:             13 :             convinfo->c_encoding == encoding)
                                253                 :                :         {
                                254         [ +  - ]:             10 :             if (!found)
                                255                 :                :             {
                                256                 :                :                 /* Found newest entry, so set up */
                                257                 :             10 :                 ClientEncoding = &pg_enc2name_tbl[encoding];
                                258                 :             10 :                 ToServerConvProc = &convinfo->to_server_info;
                                259                 :             10 :                 ToClientConvProc = &convinfo->to_client_info;
                                260                 :             10 :                 found = true;
                                261                 :                :             }
                                262                 :                :             else
                                263                 :                :             {
                                264                 :                :                 /* Duplicate entry, release it */
 2245 tgl@sss.pgh.pa.us         265                 :UBC           0 :                 ConvProcList = foreach_delete_current(ConvProcList, lc);
 5266                           266                 :              0 :                 pfree(convinfo);
                                267                 :                :             }
                                268                 :                :         }
                                269                 :                :     }
                                270                 :                : 
 5266 tgl@sss.pgh.pa.us         271         [ +  - ]:CBC          10 :     if (found)
                                272                 :             10 :         return 0;               /* success */
                                273                 :                :     else
 5266 tgl@sss.pgh.pa.us         274                 :UBC           0 :         return -1;              /* it's not cached, so fail */
                                275                 :                : }
                                276                 :                : 
                                277                 :                : /*
                                278                 :                :  * Initialize client encoding conversions.
                                279                 :                :  *      Called from InitPostgres() once during backend startup.
                                280                 :                :  */
                                281                 :                : void
 8168 tgl@sss.pgh.pa.us         282                 :CBC       13972 : InitializeClientEncoding(void)
                                283                 :                : {
                                284                 :                :     int         current_server_encoding;
                                285                 :                : 
                                286         [ -  + ]:          13972 :     Assert(!backend_startup_complete);
                                287                 :          13972 :     backend_startup_complete = true;
                                288                 :                : 
 5266                           289   [ +  -  -  + ]:          27944 :     if (PrepareClientEncoding(pending_client_encoding) < 0 ||
                                290                 :          13972 :         SetClientEncoding(pending_client_encoding) < 0)
                                291                 :                :     {
                                292                 :                :         /*
                                293                 :                :          * Oops, the requested conversion is not available. We couldn't fail
                                294                 :                :          * before, but we can now.
                                295                 :                :          */
 8079 tgl@sss.pgh.pa.us         296         [ #  # ]:UBC           0 :         ereport(FATAL,
                                297                 :                :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                                298                 :                :                  errmsg("conversion between %s and %s is not supported",
                                299                 :                :                         pg_enc2name_tbl[pending_client_encoding].name,
                                300                 :                :                         GetDatabaseEncodingName())));
                                301                 :                :     }
                                302                 :                : 
                                303                 :                :     /*
                                304                 :                :      * Also look up the UTF8-to-server conversion function if needed.  Since
                                305                 :                :      * the server encoding is fixed within any one backend process, we don't
                                306                 :                :      * have to do this more than once.
                                307                 :                :      */
 2010 tgl@sss.pgh.pa.us         308                 :CBC       13972 :     current_server_encoding = GetDatabaseEncoding();
                                309   [ +  +  +  + ]:          13972 :     if (current_server_encoding != PG_UTF8 &&
                                310                 :                :         current_server_encoding != PG_SQL_ASCII)
                                311                 :                :     {
                                312                 :                :         Oid         utf8_to_server_proc;
                                313                 :                : 
  142 noah@leadboat.com         314                 :            100 :         AssertCouldGetRelation();
                                315                 :                :         utf8_to_server_proc =
 2010 tgl@sss.pgh.pa.us         316                 :            100 :             FindDefaultConversionProc(PG_UTF8,
                                317                 :                :                                       current_server_encoding);
                                318                 :                :         /* If there's no such conversion, just leave the pointer as NULL */
                                319         [ +  - ]:            100 :         if (OidIsValid(utf8_to_server_proc))
                                320                 :                :         {
                                321                 :                :             FmgrInfo   *finfo;
                                322                 :                : 
                                323                 :            100 :             finfo = (FmgrInfo *) MemoryContextAlloc(TopMemoryContext,
                                324                 :                :                                                     sizeof(FmgrInfo));
                                325                 :            100 :             fmgr_info_cxt(utf8_to_server_proc, finfo,
                                326                 :                :                           TopMemoryContext);
                                327                 :                :             /* Set Utf8ToServerConvProc only after data is fully valid */
                                328                 :            100 :             Utf8ToServerConvProc = finfo;
                                329                 :                :         }
                                330                 :                :     }
 8235 ishii@postgresql.org      331                 :          13972 : }
                                332                 :                : 
                                333                 :                : /*
                                334                 :                :  * returns the current client encoding
                                335                 :                :  */
                                336                 :                : int
 8751 tgl@sss.pgh.pa.us         337                 :           5794 : pg_get_client_encoding(void)
                                338                 :                : {
 7178 neilc@samurai.com         339                 :           5794 :     return ClientEncoding->encoding;
                                340                 :                : }
                                341                 :                : 
                                342                 :                : /*
                                343                 :                :  * returns the current client encoding name
                                344                 :                :  */
                                345                 :                : const char *
 8751 tgl@sss.pgh.pa.us         346                 :UBC           0 : pg_get_client_encoding_name(void)
                                347                 :                : {
 7178 neilc@samurai.com         348                 :              0 :     return ClientEncoding->name;
                                349                 :                : }
                                350                 :                : 
                                351                 :                : /*
                                352                 :                :  * Convert src string to another encoding (general case).
                                353                 :                :  *
                                354                 :                :  * See the notes about string conversion functions at the top of this file.
                                355                 :                :  */
                                356                 :                : unsigned char *
 8751 tgl@sss.pgh.pa.us         357                 :CBC        1509 : pg_do_encoding_conversion(unsigned char *src, int len,
                                358                 :                :                           int src_encoding, int dest_encoding)
                                359                 :                : {
                                360                 :                :     unsigned char *result;
                                361                 :                :     Oid         proc;
                                362                 :                : 
 4213                           363         [ +  + ]:           1509 :     if (len <= 0)
                                364                 :             15 :         return src;             /* empty string is always valid */
                                365                 :                : 
 8451 ishii@postgresql.org      366         [ +  + ]:           1494 :     if (src_encoding == dest_encoding)
 4213 tgl@sss.pgh.pa.us         367                 :           1102 :         return src;             /* no conversion required, assume valid */
                                368                 :                : 
                                369         [ -  + ]:            392 :     if (dest_encoding == PG_SQL_ASCII)
 4213 tgl@sss.pgh.pa.us         370                 :UBC           0 :         return src;             /* any string is valid in SQL_ASCII */
                                371                 :                : 
 4213 tgl@sss.pgh.pa.us         372         [ +  + ]:CBC         392 :     if (src_encoding == PG_SQL_ASCII)
                                373                 :                :     {
                                374                 :                :         /* No conversion is possible, but we must validate the result */
                                375                 :              8 :         (void) pg_verify_mbstr(dest_encoding, (const char *) src, len, false);
 8320 ishii@postgresql.org      376                 :              8 :         return src;
                                377                 :                :     }
                                378                 :                : 
 4213 tgl@sss.pgh.pa.us         379         [ -  + ]:            384 :     if (!IsTransactionState())  /* shouldn't happen */
 4213 tgl@sss.pgh.pa.us         380         [ #  # ]:UBC           0 :         elog(ERROR, "cannot perform encoding conversion outside a transaction");
                                381                 :                : 
 8451 ishii@postgresql.org      382                 :CBC         384 :     proc = FindDefaultConversionProc(src_encoding, dest_encoding);
                                383         [ -  + ]:            384 :     if (!OidIsValid(proc))
 4213 tgl@sss.pgh.pa.us         384         [ #  # ]:UBC           0 :         ereport(ERROR,
                                385                 :                :                 (errcode(ERRCODE_UNDEFINED_FUNCTION),
                                386                 :                :                  errmsg("default conversion function for encoding \"%s\" to \"%s\" does not exist",
                                387                 :                :                         pg_encoding_to_char(src_encoding),
                                388                 :                :                         pg_encoding_to_char(dest_encoding))));
                                389                 :                : 
                                390                 :                :     /*
                                391                 :                :      * Allocate space for conversion result, being wary of integer overflow.
                                392                 :                :      *
                                393                 :                :      * len * MAX_CONVERSION_GROWTH is typically a vast overestimate of the
                                394                 :                :      * required space, so it might exceed MaxAllocSize even though the result
                                395                 :                :      * would actually fit.  We do not want to hand back a result string that
                                396                 :                :      * exceeds MaxAllocSize, because callers might not cope gracefully --- but
                                397                 :                :      * if we just allocate more than that, and don't use it, that's fine.
                                398                 :                :      */
 2165 tgl@sss.pgh.pa.us         399         [ -  + ]:CBC         384 :     if ((Size) len >= (MaxAllocHugeSize / (Size) MAX_CONVERSION_GROWTH))
 6676 tgl@sss.pgh.pa.us         400         [ #  # ]:UBC           0 :         ereport(ERROR,
                                401                 :                :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                                402                 :                :                  errmsg("out of memory"),
                                403                 :                :                  errdetail("String of %d bytes is too long for encoding conversion.",
                                404                 :                :                            len)));
                                405                 :                : 
                                406                 :                :     result = (unsigned char *)
 2165 tgl@sss.pgh.pa.us         407                 :CBC         384 :         MemoryContextAllocHuge(CurrentMemoryContext,
                                408                 :            384 :                                (Size) len * MAX_CONVERSION_GROWTH + 1);
                                409                 :                : 
 1619 heikki.linnakangas@i      410                 :            384 :     (void) OidFunctionCall6(proc,
                                411                 :                :                             Int32GetDatum(src_encoding),
                                412                 :                :                             Int32GetDatum(dest_encoding),
                                413                 :                :                             CStringGetDatum((char *) src),
                                414                 :                :                             CStringGetDatum((char *) result),
                                415                 :                :                             Int32GetDatum(len),
                                416                 :                :                             BoolGetDatum(false));
                                417                 :                : 
                                418                 :                :     /*
                                419                 :                :      * If the result is large, it's worth repalloc'ing to release any extra
                                420                 :                :      * space we asked for.  The cutoff here is somewhat arbitrary, but we
                                421                 :                :      * *must* check when len * MAX_CONVERSION_GROWTH exceeds MaxAllocSize.
                                422                 :                :      */
 2165 tgl@sss.pgh.pa.us         423         [ -  + ]:            384 :     if (len > 1000000)
                                424                 :                :     {
 2165 tgl@sss.pgh.pa.us         425                 :UBC           0 :         Size        resultlen = strlen((char *) result);
                                426                 :                : 
                                427         [ #  # ]:              0 :         if (resultlen >= MaxAllocSize)
                                428         [ #  # ]:              0 :             ereport(ERROR,
                                429                 :                :                     (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                                430                 :                :                      errmsg("out of memory"),
                                431                 :                :                      errdetail("String of %d bytes is too long for encoding conversion.",
                                432                 :                :                                len)));
                                433                 :                : 
                                434                 :              0 :         result = (unsigned char *) repalloc(result, resultlen + 1);
                                435                 :                :     }
                                436                 :                : 
 9492 tgl@sss.pgh.pa.us         437                 :CBC         384 :     return result;
                                438                 :                : }
                                439                 :                : 
                                440                 :                : /*
                                441                 :                :  * Convert src string to another encoding.
                                442                 :                :  *
                                443                 :                :  * This function has a different API than the other conversion functions.
                                444                 :                :  * The caller should've looked up the conversion function using
                                445                 :                :  * FindDefaultConversionProc().  Unlike the other functions, the converted
                                446                 :                :  * result is not palloc'd.  It is written to the caller-supplied buffer
                                447                 :                :  * instead.
                                448                 :                :  *
                                449                 :                :  * src_encoding   - encoding to convert from
                                450                 :                :  * dest_encoding  - encoding to convert to
                                451                 :                :  * src, srclen    - input buffer and its length in bytes
                                452                 :                :  * dest, destlen  - destination buffer and its size in bytes
                                453                 :                :  *
                                454                 :                :  * The output is null-terminated.
                                455                 :                :  *
                                456                 :                :  * If destlen < srclen * MAX_CONVERSION_INPUT_LENGTH + 1, the converted output
                                457                 :                :  * wouldn't necessarily fit in the output buffer, and the function will not
                                458                 :                :  * convert the whole input.
                                459                 :                :  *
                                460                 :                :  * TODO: The conversion function interface is not great.  Firstly, it
                                461                 :                :  * would be nice to pass through the destination buffer size to the
                                462                 :                :  * conversion function, so that if you pass a shorter destination buffer, it
                                463                 :                :  * could still continue to fill up the whole buffer.  Currently, we have to
                                464                 :                :  * assume worst case expansion and stop the conversion short, even if there
                                465                 :                :  * is in fact space left in the destination buffer.  Secondly, it would be
                                466                 :                :  * nice to return the number of bytes written to the caller, to avoid a call
                                467                 :                :  * to strlen().
                                468                 :                :  */
                                469                 :                : int
 1619 heikki.linnakangas@i      470                 :           2895 : pg_do_encoding_conversion_buf(Oid proc,
                                471                 :                :                               int src_encoding,
                                472                 :                :                               int dest_encoding,
                                473                 :                :                               unsigned char *src, int srclen,
                                474                 :                :                               unsigned char *dest, int destlen,
                                475                 :                :                               bool noError)
                                476                 :                : {
                                477                 :                :     Datum       result;
                                478                 :                : 
                                479                 :                :     /*
                                480                 :                :      * If the destination buffer is not large enough to hold the result in the
                                481                 :                :      * worst case, limit the input size passed to the conversion function.
                                482                 :                :      */
                                483         [ +  + ]:           2895 :     if ((Size) srclen >= ((destlen - 1) / (Size) MAX_CONVERSION_GROWTH))
                                484                 :           2871 :         srclen = ((destlen - 1) / (Size) MAX_CONVERSION_GROWTH);
                                485                 :                : 
                                486                 :           2895 :     result = OidFunctionCall6(proc,
                                487                 :                :                               Int32GetDatum(src_encoding),
                                488                 :                :                               Int32GetDatum(dest_encoding),
                                489                 :                :                               CStringGetDatum((char *) src),
                                490                 :                :                               CStringGetDatum((char *) dest),
                                491                 :                :                               Int32GetDatum(srclen),
                                492                 :                :                               BoolGetDatum(noError));
                                493                 :           1710 :     return DatumGetInt32(result);
                                494                 :                : }
                                495                 :                : 
                                496                 :                : /*
                                497                 :                :  * Convert string to encoding encoding_name. The source
                                498                 :                :  * encoding is the DB encoding.
                                499                 :                :  *
                                500                 :                :  * BYTEA convert_to(TEXT string, NAME encoding_name) */
                                501                 :                : Datum
 6563 andrew@dunslane.net       502                 :            198 : pg_convert_to(PG_FUNCTION_ARGS)
                                503                 :                : {
 8403 bruce@momjian.us          504                 :            198 :     Datum       string = PG_GETARG_DATUM(0);
                                505                 :            198 :     Datum       dest_encoding_name = PG_GETARG_DATUM(1);
 6450 tgl@sss.pgh.pa.us         506                 :            198 :     Datum       src_encoding_name = DirectFunctionCall1(namein,
                                507                 :                :                                                         CStringGetDatum(DatabaseEncoding->name));
                                508                 :                :     Datum       result;
                                509                 :                : 
                                510                 :                :     /*
                                511                 :                :      * pg_convert expects a bytea as its first argument. We're passing it a
                                512                 :                :      * text argument here, relying on the fact that they are both in fact
                                513                 :                :      * varlena types, and thus structurally identical.
                                514                 :                :      */
                                515                 :            198 :     result = DirectFunctionCall3(pg_convert, string,
                                516                 :                :                                  src_encoding_name, dest_encoding_name);
                                517                 :                : 
 6356                           518                 :            198 :     PG_RETURN_DATUM(result);
                                519                 :                : }
                                520                 :                : 
                                521                 :                : /*
                                522                 :                :  * Convert string from encoding encoding_name. The destination
                                523                 :                :  * encoding is the DB encoding.
                                524                 :                :  *
                                525                 :                :  * TEXT convert_from(BYTEA string, NAME encoding_name) */
                                526                 :                : Datum
 6563 andrew@dunslane.net       527                 :            290 : pg_convert_from(PG_FUNCTION_ARGS)
                                528                 :                : {
                                529                 :            290 :     Datum       string = PG_GETARG_DATUM(0);
                                530                 :            290 :     Datum       src_encoding_name = PG_GETARG_DATUM(1);
 6450 tgl@sss.pgh.pa.us         531                 :            290 :     Datum       dest_encoding_name = DirectFunctionCall1(namein,
                                532                 :                :                                                          CStringGetDatum(DatabaseEncoding->name));
                                533                 :                :     Datum       result;
                                534                 :                : 
                                535                 :            290 :     result = DirectFunctionCall3(pg_convert, string,
                                536                 :                :                                  src_encoding_name, dest_encoding_name);
                                537                 :                : 
                                538                 :                :     /*
                                539                 :                :      * pg_convert returns a bytea, which we in turn return as text, relying on
                                540                 :                :      * the fact that they are both in fact varlena types, and thus
                                541                 :                :      * structurally identical. Although not all bytea values are valid text,
                                542                 :                :      * in this case it will be because we've told pg_convert to return one
                                543                 :                :      * that is valid as text in the current database encoding.
                                544                 :                :      */
 6356                           545                 :            287 :     PG_RETURN_DATUM(result);
                                546                 :                : }
                                547                 :                : 
                                548                 :                : /*
                                549                 :                :  * Convert string between two arbitrary encodings.
                                550                 :                :  *
                                551                 :                :  * BYTEA convert(BYTEA string, NAME src_encoding_name, NAME dest_encoding_name)
                                552                 :                :  */
                                553                 :                : Datum
 6563 andrew@dunslane.net       554                 :            872 : pg_convert(PG_FUNCTION_ARGS)
                                555                 :                : {
 5391 itagaki.takahiro@gma      556                 :            872 :     bytea      *string = PG_GETARG_BYTEA_PP(0);
 8717 bruce@momjian.us          557                 :            872 :     char       *src_encoding_name = NameStr(*PG_GETARG_NAME(1));
                                558                 :            872 :     int         src_encoding = pg_char_to_encoding(src_encoding_name);
                                559                 :            872 :     char       *dest_encoding_name = NameStr(*PG_GETARG_NAME(2));
                                560                 :            872 :     int         dest_encoding = pg_char_to_encoding(dest_encoding_name);
                                561                 :                :     const char *src_str;
                                562                 :                :     char       *dest_str;
                                563                 :                :     bytea      *retval;
                                564                 :                :     int         len;
                                565                 :                : 
 8788 ishii@postgresql.org      566         [ -  + ]:            872 :     if (src_encoding < 0)
 8079 tgl@sss.pgh.pa.us         567         [ #  # ]:UBC           0 :         ereport(ERROR,
                                568                 :                :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                                569                 :                :                  errmsg("invalid source encoding name \"%s\"",
                                570                 :                :                         src_encoding_name)));
 8788 ishii@postgresql.org      571         [ -  + ]:CBC         872 :     if (dest_encoding < 0)
 8079 tgl@sss.pgh.pa.us         572         [ #  # ]:UBC           0 :         ereport(ERROR,
                                573                 :                :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                                574                 :                :                  errmsg("invalid destination encoding name \"%s\"",
                                575                 :                :                         dest_encoding_name)));
                                576                 :                : 
                                577                 :                :     /* make sure that source string is valid */
 5391 itagaki.takahiro@gma      578   [ -  +  -  -  :CBC         872 :     len = VARSIZE_ANY_EXHDR(string);
                                     -  -  -  -  +  
                                                 + ]
                                579         [ +  + ]:            872 :     src_str = VARDATA_ANY(string);
 1682 heikki.linnakangas@i      580                 :            872 :     (void) pg_verify_mbstr(src_encoding, src_str, len, false);
                                581                 :                : 
                                582                 :                :     /* perform conversion */
 2412 peter@eisentraut.org      583                 :            869 :     dest_str = (char *) pg_do_encoding_conversion((unsigned char *) unconstify(char *, src_str),
                                584                 :                :                                                   len,
                                585                 :                :                                                   src_encoding,
                                586                 :                :                                                   dest_encoding);
                                587                 :                : 
                                588                 :                : 
                                589                 :                :     /* return source string if no conversion happened */
  642 nathan@postgresql.or      590         [ +  + ]:            869 :     if (dest_str == src_str)
                                591                 :            485 :         PG_RETURN_BYTEA_P(string);
                                592                 :                : 
                                593                 :                :     /*
                                594                 :                :      * build bytea data type structure.
                                595                 :                :      */
                                596                 :            384 :     len = strlen(dest_str);
 5391 itagaki.takahiro@gma      597                 :            384 :     retval = (bytea *) palloc(len + VARHDRSZ);
                                598                 :            384 :     SET_VARSIZE(retval, len + VARHDRSZ);
                                599                 :            384 :     memcpy(VARDATA(retval), dest_str, len);
  642 nathan@postgresql.or      600                 :            384 :     pfree(dest_str);
                                601                 :                : 
                                602                 :                :     /* free memory if allocated by the toaster */
 8788 ishii@postgresql.org      603         [ -  + ]:            384 :     PG_FREE_IF_COPY(string, 0);
                                604                 :                : 
 6563 andrew@dunslane.net       605                 :            384 :     PG_RETURN_BYTEA_P(retval);
                                606                 :                : }
                                607                 :                : 
                                608                 :                : /*
                                609                 :                :  * get the length of the string considered as text in the specified
                                610                 :                :  * encoding. Raises an error if the data is not valid in that
                                611                 :                :  * encoding.
                                612                 :                :  *
                                613                 :                :  * INT4 length (BYTEA string, NAME src_encoding_name)
                                614                 :                :  */
                                615                 :                : Datum
 6563 andrew@dunslane.net       616                 :UBC           0 : length_in_encoding(PG_FUNCTION_ARGS)
                                617                 :                : {
 4213 tgl@sss.pgh.pa.us         618                 :              0 :     bytea      *string = PG_GETARG_BYTEA_PP(0);
 6563 andrew@dunslane.net       619                 :              0 :     char       *src_encoding_name = NameStr(*PG_GETARG_NAME(1));
                                620                 :              0 :     int         src_encoding = pg_char_to_encoding(src_encoding_name);
                                621                 :                :     const char *src_str;
                                622                 :                :     int         len;
                                623                 :                :     int         retval;
                                624                 :                : 
 6538 tgl@sss.pgh.pa.us         625         [ #  # ]:              0 :     if (src_encoding < 0)
                                626         [ #  # ]:              0 :         ereport(ERROR,
                                627                 :                :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                                628                 :                :                  errmsg("invalid encoding name \"%s\"",
                                629                 :                :                         src_encoding_name)));
                                630                 :                : 
 4213                           631   [ #  #  #  #  :              0 :     len = VARSIZE_ANY_EXHDR(string);
                                     #  #  #  #  #  
                                                 # ]
                                632         [ #  # ]:              0 :     src_str = VARDATA_ANY(string);
                                633                 :                : 
                                634                 :              0 :     retval = pg_verify_mbstr_len(src_encoding, src_str, len, false);
                                635                 :                : 
                                636                 :              0 :     PG_RETURN_INT32(retval);
                                637                 :                : }
                                638                 :                : 
                                639                 :                : /*
                                640                 :                :  * Get maximum multibyte character length in the specified encoding.
                                641                 :                :  *
                                642                 :                :  * Note encoding is specified numerically, not by name as above.
                                643                 :                :  */
                                644                 :                : Datum
 5905 peter_e@gmx.net           645                 :              0 : pg_encoding_max_length_sql(PG_FUNCTION_ARGS)
                                646                 :                : {
 5671 bruce@momjian.us          647                 :              0 :     int         encoding = PG_GETARG_INT32(0);
                                648                 :                : 
 5905 peter_e@gmx.net           649   [ #  #  #  # ]:              0 :     if (PG_VALID_ENCODING(encoding))
      tgl@sss.pgh.pa.us         650                 :              0 :         PG_RETURN_INT32(pg_wchar_table[encoding].maxmblen);
                                651                 :                :     else
      peter_e@gmx.net           652                 :              0 :         PG_RETURN_NULL();
                                653                 :                : }
                                654                 :                : 
                                655                 :                : /*
                                656                 :                :  * Convert client encoding to server encoding.
                                657                 :                :  *
                                658                 :                :  * See the notes about string conversion functions at the top of this file.
                                659                 :                :  */
                                660                 :                : char *
 7287 tgl@sss.pgh.pa.us         661                 :CBC      392420 : pg_client_to_server(const char *s, int len)
                                662                 :                : {
 5311 itagaki.takahiro@gma      663                 :         392420 :     return pg_any_to_server(s, len, ClientEncoding->encoding);
                                664                 :                : }
                                665                 :                : 
                                666                 :                : /*
                                667                 :                :  * Convert any encoding to server encoding.
                                668                 :                :  *
                                669                 :                :  * See the notes about string conversion functions at the top of this file.
                                670                 :                :  *
                                671                 :                :  * Unlike the other string conversion functions, this will apply validation
                                672                 :                :  * even if encoding == DatabaseEncoding->encoding.  This is because this is
                                673                 :                :  * used to process data coming in from outside the database, and we never
                                674                 :                :  * want to just assume validity.
                                675                 :                :  */
                                676                 :                : char *
                                677                 :         435163 : pg_any_to_server(const char *s, int len, int encoding)
                                678                 :                : {
 7048 tgl@sss.pgh.pa.us         679         [ +  + ]:         435163 :     if (len <= 0)
 2299                           680                 :          35121 :         return unconstify(char *, s);   /* empty string is always valid */
                                681                 :                : 
 5311 itagaki.takahiro@gma      682   [ +  +  +  + ]:         400042 :     if (encoding == DatabaseEncoding->encoding ||
                                683                 :                :         encoding == PG_SQL_ASCII)
                                684                 :                :     {
                                685                 :                :         /*
                                686                 :                :          * No conversion is needed, but we must still validate the data.
                                687                 :                :          */
 7048 tgl@sss.pgh.pa.us         688                 :         399858 :         (void) pg_verify_mbstr(DatabaseEncoding->encoding, s, len, false);
 2412 peter@eisentraut.org      689                 :         399857 :         return unconstify(char *, s);
                                690                 :                :     }
                                691                 :                : 
 7048 tgl@sss.pgh.pa.us         692         [ +  + ]:            184 :     if (DatabaseEncoding->encoding == PG_SQL_ASCII)
                                693                 :                :     {
                                694                 :                :         /*
                                695                 :                :          * No conversion is possible, but we must still validate the data,
                                696                 :                :          * because the client-side code might have done string escaping using
                                697                 :                :          * the selected client_encoding.  If the client encoding is ASCII-safe
                                698                 :                :          * then we just do a straight validation under that encoding.  For an
                                699                 :                :          * ASCII-unsafe encoding we have a problem: we dare not pass such data
                                700                 :                :          * to the parser but we have no way to convert it.  We compromise by
                                701                 :                :          * rejecting the data if it contains any non-ASCII characters.
                                702                 :                :          */
 5311 itagaki.takahiro@gma      703   [ +  -  +  + ]:            154 :         if (PG_VALID_BE_ENCODING(encoding))
                                704                 :            124 :             (void) pg_verify_mbstr(encoding, s, len, false);
                                705                 :                :         else
                                706                 :                :         {
                                707                 :                :             int         i;
                                708                 :                : 
 7048 tgl@sss.pgh.pa.us         709         [ +  + ]:            954 :             for (i = 0; i < len; i++)
                                710                 :                :             {
                                711   [ +  -  -  + ]:            924 :                 if (s[i] == '\0' || IS_HIGHBIT_SET(s[i]))
 7048 tgl@sss.pgh.pa.us         712         [ #  # ]:UBC           0 :                     ereport(ERROR,
                                713                 :                :                             (errcode(ERRCODE_CHARACTER_NOT_IN_REPERTOIRE),
                                714                 :                :                              errmsg("invalid byte value for encoding \"%s\": 0x%02x",
                                715                 :                :                                     pg_enc2name_tbl[PG_SQL_ASCII].name,
                                716                 :                :                                     (unsigned char) s[i])));
                                717                 :                :             }
                                718                 :                :         }
 2412 peter@eisentraut.org      719                 :CBC         154 :         return unconstify(char *, s);
                                720                 :                :     }
                                721                 :                : 
                                722                 :                :     /* Fast path if we can use cached conversion function */
 4213 tgl@sss.pgh.pa.us         723         [ +  - ]:             30 :     if (encoding == ClientEncoding->encoding)
 5311 itagaki.takahiro@gma      724                 :             30 :         return perform_default_encoding_conversion(s, len, true);
                                725                 :                : 
                                726                 :                :     /* General case ... will not work outside transactions */
 2412 peter@eisentraut.org      727                 :UBC           0 :     return (char *) pg_do_encoding_conversion((unsigned char *) unconstify(char *, s),
                                728                 :                :                                               len,
                                729                 :                :                                               encoding,
 4213 tgl@sss.pgh.pa.us         730                 :              0 :                                               DatabaseEncoding->encoding);
                                731                 :                : }
                                732                 :                : 
                                733                 :                : /*
                                734                 :                :  * Convert server encoding to client encoding.
                                735                 :                :  *
                                736                 :                :  * See the notes about string conversion functions at the top of this file.
                                737                 :                :  */
                                738                 :                : char *
 7287 tgl@sss.pgh.pa.us         739                 :CBC    18596812 : pg_server_to_client(const char *s, int len)
                                740                 :                : {
 5311 itagaki.takahiro@gma      741                 :       18596812 :     return pg_server_to_any(s, len, ClientEncoding->encoding);
                                742                 :                : }
                                743                 :                : 
                                744                 :                : /*
                                745                 :                :  * Convert server encoding to any encoding.
                                746                 :                :  *
                                747                 :                :  * See the notes about string conversion functions at the top of this file.
                                748                 :                :  */
                                749                 :                : char *
                                750                 :       18616531 : pg_server_to_any(const char *s, int len, int encoding)
                                751                 :                : {
 7048 tgl@sss.pgh.pa.us         752         [ +  + ]:       18616531 :     if (len <= 0)
 2299                           753                 :         133474 :         return unconstify(char *, s);   /* empty string is always valid */
                                754                 :                : 
 5311 itagaki.takahiro@gma      755   [ +  +  +  + ]:       18483057 :     if (encoding == DatabaseEncoding->encoding ||
                                756                 :                :         encoding == PG_SQL_ASCII)
 2299 tgl@sss.pgh.pa.us         757                 :       18482781 :         return unconstify(char *, s);   /* assume data is valid */
                                758                 :                : 
 4213                           759         [ +  + ]:            276 :     if (DatabaseEncoding->encoding == PG_SQL_ASCII)
                                760                 :                :     {
                                761                 :                :         /* No conversion is possible, but we must validate the result */
                                762                 :             84 :         (void) pg_verify_mbstr(encoding, s, len, false);
 2412 peter@eisentraut.org      763                 :             84 :         return unconstify(char *, s);
                                764                 :                :     }
                                765                 :                : 
                                766                 :                :     /* Fast path if we can use cached conversion function */
 4213 tgl@sss.pgh.pa.us         767         [ +  - ]:            192 :     if (encoding == ClientEncoding->encoding)
 5311 itagaki.takahiro@gma      768                 :            192 :         return perform_default_encoding_conversion(s, len, false);
                                769                 :                : 
                                770                 :                :     /* General case ... will not work outside transactions */
 2412 peter@eisentraut.org      771                 :UBC           0 :     return (char *) pg_do_encoding_conversion((unsigned char *) unconstify(char *, s),
                                772                 :                :                                               len,
 4213 tgl@sss.pgh.pa.us         773                 :              0 :                                               DatabaseEncoding->encoding,
                                774                 :                :                                               encoding);
                                775                 :                : }
                                776                 :                : 
                                777                 :                : /*
                                778                 :                :  *  Perform default encoding conversion using cached FmgrInfo. Since
                                779                 :                :  *  this function does not access database at all, it is safe to call
                                780                 :                :  *  outside transactions.  If the conversion has not been set up by
                                781                 :                :  *  SetClientEncoding(), no conversion is performed.
                                782                 :                :  */
                                783                 :                : static char *
 4213 tgl@sss.pgh.pa.us         784                 :CBC         222 : perform_default_encoding_conversion(const char *src, int len,
                                785                 :                :                                     bool is_client_to_server)
                                786                 :                : {
                                787                 :                :     char       *result;
                                788                 :                :     int         src_encoding,
                                789                 :                :                 dest_encoding;
                                790                 :                :     FmgrInfo   *flinfo;
                                791                 :                : 
 8430 ishii@postgresql.org      792         [ +  + ]:            222 :     if (is_client_to_server)
                                793                 :                :     {
                                794                 :             30 :         src_encoding = ClientEncoding->encoding;
                                795                 :             30 :         dest_encoding = DatabaseEncoding->encoding;
 8344 tgl@sss.pgh.pa.us         796                 :             30 :         flinfo = ToServerConvProc;
                                797                 :                :     }
                                798                 :                :     else
                                799                 :                :     {
 8430 ishii@postgresql.org      800                 :            192 :         src_encoding = DatabaseEncoding->encoding;
                                801                 :            192 :         dest_encoding = ClientEncoding->encoding;
 8344 tgl@sss.pgh.pa.us         802                 :            192 :         flinfo = ToClientConvProc;
                                803                 :                :     }
                                804                 :                : 
 8430 ishii@postgresql.org      805         [ -  + ]:            222 :     if (flinfo == NULL)
 2412 peter@eisentraut.org      806                 :UBC           0 :         return unconstify(char *, src);
                                807                 :                : 
                                808                 :                :     /*
                                809                 :                :      * Allocate space for conversion result, being wary of integer overflow.
                                810                 :                :      * See comments in pg_do_encoding_conversion.
                                811                 :                :      */
 2165 tgl@sss.pgh.pa.us         812         [ -  + ]:CBC         222 :     if ((Size) len >= (MaxAllocHugeSize / (Size) MAX_CONVERSION_GROWTH))
 6676 tgl@sss.pgh.pa.us         813         [ #  # ]:UBC           0 :         ereport(ERROR,
                                814                 :                :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                                815                 :                :                  errmsg("out of memory"),
                                816                 :                :                  errdetail("String of %d bytes is too long for encoding conversion.",
                                817                 :                :                            len)));
                                818                 :                : 
                                819                 :                :     result = (char *)
 2165 tgl@sss.pgh.pa.us         820                 :CBC         222 :         MemoryContextAllocHuge(CurrentMemoryContext,
                                821                 :            222 :                                (Size) len * MAX_CONVERSION_GROWTH + 1);
                                822                 :                : 
 1619 heikki.linnakangas@i      823                 :            222 :     FunctionCall6(flinfo,
                                824                 :                :                   Int32GetDatum(src_encoding),
                                825                 :                :                   Int32GetDatum(dest_encoding),
                                826                 :                :                   CStringGetDatum(src),
                                827                 :                :                   CStringGetDatum(result),
                                828                 :                :                   Int32GetDatum(len),
                                829                 :                :                   BoolGetDatum(false));
                                830                 :                : 
                                831                 :                :     /*
                                832                 :                :      * Release extra space if there might be a lot --- see comments in
                                833                 :                :      * pg_do_encoding_conversion.
                                834                 :                :      */
 2165 tgl@sss.pgh.pa.us         835         [ -  + ]:            222 :     if (len > 1000000)
                                836                 :                :     {
 2165 tgl@sss.pgh.pa.us         837                 :UBC           0 :         Size        resultlen = strlen(result);
                                838                 :                : 
                                839         [ #  # ]:              0 :         if (resultlen >= MaxAllocSize)
                                840         [ #  # ]:              0 :             ereport(ERROR,
                                841                 :                :                     (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                                842                 :                :                      errmsg("out of memory"),
                                843                 :                :                      errdetail("String of %d bytes is too long for encoding conversion.",
                                844                 :                :                                len)));
                                845                 :                : 
                                846                 :              0 :         result = (char *) repalloc(result, resultlen + 1);
                                847                 :                :     }
                                848                 :                : 
 8430 ishii@postgresql.org      849                 :CBC         222 :     return result;
                                850                 :                : }
                                851                 :                : 
                                852                 :                : /*
                                853                 :                :  * Convert a single Unicode code point into a string in the server encoding.
                                854                 :                :  *
                                855                 :                :  * The code point given by "c" is converted and stored at *s, which must
                                856                 :                :  * have at least MAX_UNICODE_EQUIVALENT_STRING+1 bytes available.
                                857                 :                :  * The output will have a trailing '\0'.  Throws error if the conversion
                                858                 :                :  * cannot be performed.
                                859                 :                :  *
                                860                 :                :  * Note that this relies on having previously looked up any required
                                861                 :                :  * conversion function.  That's partly for speed but mostly because the parser
                                862                 :                :  * may call this outside any transaction, or in an aborted transaction.
                                863                 :                :  */
                                864                 :                : void
 2010 tgl@sss.pgh.pa.us         865                 :            501 : pg_unicode_to_server(pg_wchar c, unsigned char *s)
                                866                 :                : {
                                867                 :                :     unsigned char c_as_utf8[MAX_MULTIBYTE_CHAR_LEN + 1];
                                868                 :                :     int         c_as_utf8_len;
                                869                 :                :     int         server_encoding;
                                870                 :                : 
                                871                 :                :     /*
                                872                 :                :      * Complain if invalid Unicode code point.  The choice of errcode here is
                                873                 :                :      * debatable, but really our caller should have checked this anyway.
                                874                 :                :      */
                                875         [ -  + ]:            501 :     if (!is_valid_unicode_codepoint(c))
 2010 tgl@sss.pgh.pa.us         876         [ #  # ]:UBC           0 :         ereport(ERROR,
                                877                 :                :                 (errcode(ERRCODE_SYNTAX_ERROR),
                                878                 :                :                  errmsg("invalid Unicode code point")));
                                879                 :                : 
                                880                 :                :     /* Otherwise, if it's in ASCII range, conversion is trivial */
 2010 tgl@sss.pgh.pa.us         881         [ +  + ]:CBC         501 :     if (c <= 0x7F)
                                882                 :                :     {
                                883                 :            172 :         s[0] = (unsigned char) c;
                                884                 :            172 :         s[1] = '\0';
                                885                 :            501 :         return;
                                886                 :                :     }
                                887                 :                : 
                                888                 :                :     /* If the server encoding is UTF-8, we just need to reformat the code */
                                889                 :            329 :     server_encoding = GetDatabaseEncoding();
                                890         [ +  - ]:            329 :     if (server_encoding == PG_UTF8)
                                891                 :                :     {
                                892                 :            329 :         unicode_to_utf8(c, s);
                                893                 :            329 :         s[pg_utf_mblen(s)] = '\0';
                                894                 :            329 :         return;
                                895                 :                :     }
                                896                 :                : 
                                897                 :                :     /* For all other cases, we must have a conversion function available */
 2010 tgl@sss.pgh.pa.us         898         [ #  # ]:UBC           0 :     if (Utf8ToServerConvProc == NULL)
                                899         [ #  # ]:              0 :         ereport(ERROR,
                                900                 :                :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                                901                 :                :                  errmsg("conversion between %s and %s is not supported",
                                902                 :                :                         pg_enc2name_tbl[PG_UTF8].name,
                                903                 :                :                         GetDatabaseEncodingName())));
                                904                 :                : 
                                905                 :                :     /* Construct UTF-8 source string */
                                906                 :              0 :     unicode_to_utf8(c, c_as_utf8);
                                907                 :              0 :     c_as_utf8_len = pg_utf_mblen(c_as_utf8);
                                908                 :              0 :     c_as_utf8[c_as_utf8_len] = '\0';
                                909                 :                : 
                                910                 :                :     /* Convert, or throw error if we can't */
 1619 heikki.linnakangas@i      911                 :              0 :     FunctionCall6(Utf8ToServerConvProc,
                                912                 :                :                   Int32GetDatum(PG_UTF8),
                                913                 :                :                   Int32GetDatum(server_encoding),
                                914                 :                :                   CStringGetDatum((char *) c_as_utf8),
                                915                 :                :                   CStringGetDatum((char *) s),
                                916                 :                :                   Int32GetDatum(c_as_utf8_len),
                                917                 :                :                   BoolGetDatum(false));
                                918                 :                : }
                                919                 :                : 
                                920                 :                : /*
                                921                 :                :  * Convert a single Unicode code point into a string in the server encoding.
                                922                 :                :  *
                                923                 :                :  * Same as pg_unicode_to_server(), except that we don't throw errors,
                                924                 :                :  * but simply return false on conversion failure.
                                925                 :                :  */
                                926                 :                : bool
 1000 tgl@sss.pgh.pa.us         927                 :CBC          42 : pg_unicode_to_server_noerror(pg_wchar c, unsigned char *s)
                                928                 :                : {
                                929                 :                :     unsigned char c_as_utf8[MAX_MULTIBYTE_CHAR_LEN + 1];
                                930                 :                :     int         c_as_utf8_len;
                                931                 :                :     int         converted_len;
                                932                 :                :     int         server_encoding;
                                933                 :                : 
                                934                 :                :     /* Fail if invalid Unicode code point */
                                935         [ -  + ]:             42 :     if (!is_valid_unicode_codepoint(c))
 1000 tgl@sss.pgh.pa.us         936                 :UBC           0 :         return false;
                                937                 :                : 
                                938                 :                :     /* Otherwise, if it's in ASCII range, conversion is trivial */
 1000 tgl@sss.pgh.pa.us         939         [ +  + ]:CBC          42 :     if (c <= 0x7F)
                                940                 :                :     {
                                941                 :             12 :         s[0] = (unsigned char) c;
                                942                 :             12 :         s[1] = '\0';
                                943                 :             12 :         return true;
                                944                 :                :     }
                                945                 :                : 
                                946                 :                :     /* If the server encoding is UTF-8, we just need to reformat the code */
                                947                 :             30 :     server_encoding = GetDatabaseEncoding();
                                948         [ +  - ]:             30 :     if (server_encoding == PG_UTF8)
                                949                 :                :     {
                                950                 :             30 :         unicode_to_utf8(c, s);
                                951                 :             30 :         s[pg_utf_mblen(s)] = '\0';
                                952                 :             30 :         return true;
                                953                 :                :     }
                                954                 :                : 
                                955                 :                :     /* For all other cases, we must have a conversion function available */
 1000 tgl@sss.pgh.pa.us         956         [ #  # ]:UBC           0 :     if (Utf8ToServerConvProc == NULL)
                                957                 :              0 :         return false;
                                958                 :                : 
                                959                 :                :     /* Construct UTF-8 source string */
                                960                 :              0 :     unicode_to_utf8(c, c_as_utf8);
                                961                 :              0 :     c_as_utf8_len = pg_utf_mblen(c_as_utf8);
                                962                 :              0 :     c_as_utf8[c_as_utf8_len] = '\0';
                                963                 :                : 
                                964                 :                :     /* Convert, but without throwing error if we can't */
                                965                 :              0 :     converted_len = DatumGetInt32(FunctionCall6(Utf8ToServerConvProc,
                                966                 :                :                                                 Int32GetDatum(PG_UTF8),
                                967                 :                :                                                 Int32GetDatum(server_encoding),
                                968                 :                :                                                 CStringGetDatum((char *) c_as_utf8),
                                969                 :                :                                                 CStringGetDatum((char *) s),
                                970                 :                :                                                 Int32GetDatum(c_as_utf8_len),
                                971                 :                :                                                 BoolGetDatum(true)));
                                972                 :                : 
                                973                 :                :     /* Conversion was successful iff it consumed the whole input */
                                974                 :              0 :     return (converted_len == c_as_utf8_len);
                                975                 :                : }
                                976                 :                : 
                                977                 :                : 
                                978                 :                : /* convert a multibyte string to a wchar */
                                979                 :                : int
 7287                           980                 :              0 : pg_mb2wchar(const char *from, pg_wchar *to)
                                981                 :                : {
 2921 peter_e@gmx.net           982                 :              0 :     return pg_wchar_table[DatabaseEncoding->encoding].mb2wchar_with_len((const unsigned char *) from, to, strlen(from));
                                983                 :                : }
                                984                 :                : 
                                985                 :                : /* convert a multibyte string to a wchar with a limited length */
                                986                 :                : int
 7287 tgl@sss.pgh.pa.us         987                 :CBC     3593109 : pg_mb2wchar_with_len(const char *from, pg_wchar *to, int len)
                                988                 :                : {
 2921 peter_e@gmx.net           989                 :        3593109 :     return pg_wchar_table[DatabaseEncoding->encoding].mb2wchar_with_len((const unsigned char *) from, to, len);
                                990                 :                : }
                                991                 :                : 
                                992                 :                : /* same, with any encoding */
                                993                 :                : int
 6831 tgl@sss.pgh.pa.us         994                 :           9140 : pg_encoding_mb2wchar_with_len(int encoding,
                                995                 :                :                               const char *from, pg_wchar *to, int len)
                                996                 :                : {
 2921 peter_e@gmx.net           997                 :           9140 :     return pg_wchar_table[encoding].mb2wchar_with_len((const unsigned char *) from, to, len);
                                998                 :                : }
                                999                 :                : 
                               1000                 :                : /* convert a wchar string to a multibyte */
                               1001                 :                : int
 4812 rhaas@postgresql.org     1002                 :UBC           0 : pg_wchar2mb(const pg_wchar *from, char *to)
                               1003                 :                : {
 2921 peter_e@gmx.net          1004                 :              0 :     return pg_wchar_table[DatabaseEncoding->encoding].wchar2mb_with_len(from, (unsigned char *) to, pg_wchar_strlen(from));
                               1005                 :                : }
                               1006                 :                : 
                               1007                 :                : /* convert a wchar string to a multibyte with a limited length */
                               1008                 :                : int
 4812 rhaas@postgresql.org     1009                 :CBC      557949 : pg_wchar2mb_with_len(const pg_wchar *from, char *to, int len)
                               1010                 :                : {
 2921 peter_e@gmx.net          1011                 :         557949 :     return pg_wchar_table[DatabaseEncoding->encoding].wchar2mb_with_len(from, (unsigned char *) to, len);
                               1012                 :                : }
                               1013                 :                : 
                               1014                 :                : /* same, with any encoding */
                               1015                 :                : int
 4812 rhaas@postgresql.org     1016                 :UBC           0 : pg_encoding_wchar2mb_with_len(int encoding,
                               1017                 :                :                               const pg_wchar *from, char *to, int len)
                               1018                 :                : {
 2921 peter_e@gmx.net          1019                 :              0 :     return pg_wchar_table[encoding].wchar2mb_with_len(from, (unsigned char *) to, len);
                               1020                 :                : }
                               1021                 :                : 
                               1022                 :                : /* returns the byte length of a multibyte character */
                               1023                 :                : int
 7287 tgl@sss.pgh.pa.us        1024                 :CBC   126616470 : pg_mblen(const char *mbstr)
                               1025                 :                : {
 2921 peter_e@gmx.net          1026                 :      126616470 :     return pg_wchar_table[DatabaseEncoding->encoding].mblen((const unsigned char *) mbstr);
                               1027                 :                : }
                               1028                 :                : 
                               1029                 :                : /* returns the display length of a multibyte character */
                               1030                 :                : int
 7287 tgl@sss.pgh.pa.us        1031                 :           4362 : pg_dsplen(const char *mbstr)
                               1032                 :                : {
 2921 peter_e@gmx.net          1033                 :           4362 :     return pg_wchar_table[DatabaseEncoding->encoding].dsplen((const unsigned char *) mbstr);
                               1034                 :                : }
                               1035                 :                : 
                               1036                 :                : /* returns the length (counted in wchars) of a multibyte string */
                               1037                 :                : int
 7287 tgl@sss.pgh.pa.us        1038                 :            351 : pg_mbstrlen(const char *mbstr)
                               1039                 :                : {
 9867 bruce@momjian.us         1040                 :            351 :     int         len = 0;
                               1041                 :                : 
                               1042                 :                :     /* optimization for single byte encoding */
 8409 ishii@postgresql.org     1043         [ -  + ]:            351 :     if (pg_database_encoding_max_length() == 1)
 7287 tgl@sss.pgh.pa.us        1044                 :UBC           0 :         return strlen(mbstr);
                               1045                 :                : 
 9867 bruce@momjian.us         1046         [ +  + ]:CBC         813 :     while (*mbstr)
                               1047                 :                :     {
                               1048                 :            462 :         mbstr += pg_mblen(mbstr);
                               1049                 :            462 :         len++;
                               1050                 :                :     }
 7178 neilc@samurai.com        1051                 :            351 :     return len;
                               1052                 :                : }
                               1053                 :                : 
                               1054                 :                : /* returns the length (counted in wchars) of a multibyte string
                               1055                 :                :  * (not necessarily NULL terminated)
                               1056                 :                :  */
                               1057                 :                : int
 7287 tgl@sss.pgh.pa.us        1058                 :         802823 : pg_mbstrlen_with_len(const char *mbstr, int limit)
                               1059                 :                : {
 9867 bruce@momjian.us         1060                 :         802823 :     int         len = 0;
                               1061                 :                : 
                               1062                 :                :     /* optimization for single byte encoding */
 7363 tgl@sss.pgh.pa.us        1063         [ +  + ]:         802823 :     if (pg_database_encoding_max_length() == 1)
                               1064                 :         200007 :         return limit;
                               1065                 :                : 
 8948                          1066   [ +  +  +  - ]:      110657425 :     while (limit > 0 && *mbstr)
                               1067                 :                :     {
 7266 bruce@momjian.us         1068                 :      110054609 :         int         l = pg_mblen(mbstr);
                               1069                 :                : 
 9867                          1070                 :      110054609 :         limit -= l;
                               1071                 :      110054609 :         mbstr += l;
                               1072                 :      110054609 :         len++;
                               1073                 :                :     }
 7178 neilc@samurai.com        1074                 :         602816 :     return len;
                               1075                 :                : }
                               1076                 :                : 
                               1077                 :                : /*
                               1078                 :                :  * returns the byte length of a multibyte string
                               1079                 :                :  * (not necessarily NULL terminated)
                               1080                 :                :  * that is no longer than limit.
                               1081                 :                :  * this function does not break multibyte character boundary.
                               1082                 :                :  */
                               1083                 :                : int
 7287 tgl@sss.pgh.pa.us        1084                 :         146265 : pg_mbcliplen(const char *mbstr, int len, int limit)
                               1085                 :                : {
 6089                          1086                 :         146265 :     return pg_encoding_mbcliplen(DatabaseEncoding->encoding, mbstr,
                               1087                 :                :                                  len, limit);
                               1088                 :                : }
                               1089                 :                : 
                               1090                 :                : /*
                               1091                 :                :  * pg_mbcliplen with specified encoding; string must be valid in encoding
                               1092                 :                :  */
                               1093                 :                : int
                               1094                 :         146265 : pg_encoding_mbcliplen(int encoding, const char *mbstr,
                               1095                 :                :                       int len, int limit)
                               1096                 :                : {
                               1097                 :                :     mblen_converter mblen_fn;
 9843 bruce@momjian.us         1098                 :         146265 :     int         clen = 0;
                               1099                 :                :     int         l;
                               1100                 :                : 
                               1101                 :                :     /* optimization for single byte encoding */
 6089 tgl@sss.pgh.pa.us        1102         [ +  + ]:         146265 :     if (pg_encoding_max_length(encoding) == 1)
 8409 ishii@postgresql.org     1103                 :          18275 :         return cliplen(mbstr, len, limit);
                               1104                 :                : 
 6089 tgl@sss.pgh.pa.us        1105                 :         127990 :     mblen_fn = pg_wchar_table[encoding].mblen;
                               1106                 :                : 
 8948                          1107   [ +  +  +  - ]:        1388750 :     while (len > 0 && *mbstr)
                               1108                 :                :     {
 6089                          1109                 :        1325489 :         l = (*mblen_fn) ((const unsigned char *) mbstr);
 9601 bruce@momjian.us         1110         [ +  + ]:        1325489 :         if ((clen + l) > limit)
 9843                          1111                 :             47 :             break;
                               1112                 :        1325442 :         clen += l;
 9601                          1113         [ +  + ]:        1325442 :         if (clen == limit)
 9843                          1114                 :          64682 :             break;
                               1115                 :        1260760 :         len -= l;
                               1116                 :        1260760 :         mbstr += l;
                               1117                 :                :     }
 7178 neilc@samurai.com        1118                 :         127990 :     return clen;
                               1119                 :                : }
                               1120                 :                : 
                               1121                 :                : /*
                               1122                 :                :  * Similar to pg_mbcliplen except the limit parameter specifies the
                               1123                 :                :  * character length, not the byte length.
                               1124                 :                :  */
                               1125                 :                : int
 7287 tgl@sss.pgh.pa.us        1126                 :            264 : pg_mbcharcliplen(const char *mbstr, int len, int limit)
                               1127                 :                : {
 8819 ishii@postgresql.org     1128                 :            264 :     int         clen = 0;
                               1129                 :            264 :     int         nch = 0;
                               1130                 :                :     int         l;
                               1131                 :                : 
                               1132                 :                :     /* optimization for single byte encoding */
 8409                          1133         [ -  + ]:            264 :     if (pg_database_encoding_max_length() == 1)
 8409 ishii@postgresql.org     1134                 :UBC           0 :         return cliplen(mbstr, len, limit);
                               1135                 :                : 
 8819 ishii@postgresql.org     1136   [ +  +  +  - ]:CBC        1164 :     while (len > 0 && *mbstr)
                               1137                 :                :     {
                               1138                 :           1155 :         l = pg_mblen(mbstr);
                               1139                 :           1155 :         nch++;
                               1140         [ +  + ]:           1155 :         if (nch > limit)
                               1141                 :            255 :             break;
                               1142                 :            900 :         clen += l;
                               1143                 :            900 :         len -= l;
                               1144                 :            900 :         mbstr += l;
                               1145                 :                :     }
 7178 neilc@samurai.com        1146                 :            264 :     return clen;
                               1147                 :                : }
                               1148                 :                : 
                               1149                 :                : /* mbcliplen for any single-byte encoding */
                               1150                 :                : static int
 6089 tgl@sss.pgh.pa.us        1151                 :          18275 : cliplen(const char *str, int len, int limit)
                               1152                 :                : {
                               1153                 :          18275 :     int         l = 0;
                               1154                 :                : 
                               1155                 :          18275 :     len = Min(len, limit);
                               1156   [ +  +  +  - ]:         144010 :     while (l < len && str[l])
                               1157                 :         125735 :         l++;
                               1158                 :          18275 :     return l;
                               1159                 :                : }
                               1160                 :                : 
                               1161                 :                : void
 9906 scrappy@hub.org          1162                 :          13473 : SetDatabaseEncoding(int encoding)
                               1163                 :                : {
 8766 ishii@postgresql.org     1164   [ +  -  -  + ]:          13473 :     if (!PG_VALID_BE_ENCODING(encoding))
 6834 peter_e@gmx.net          1165         [ #  # ]:UBC           0 :         elog(ERROR, "invalid database encoding: %d", encoding);
                               1166                 :                : 
 8717 bruce@momjian.us         1167                 :CBC       13473 :     DatabaseEncoding = &pg_enc2name_tbl[encoding];
 8766 ishii@postgresql.org     1168         [ -  + ]:          13473 :     Assert(DatabaseEncoding->encoding == encoding);
 6026 alvherre@alvh.no-ip.     1169                 :          13473 : }
                               1170                 :                : 
                               1171                 :                : void
 4455 noah@leadboat.com        1172                 :          15280 : SetMessageEncoding(int encoding)
                               1173                 :                : {
                               1174                 :                :     /* Some calls happen before we can elog()! */
                               1175   [ +  -  -  + ]:          15280 :     Assert(PG_VALID_ENCODING(encoding));
                               1176                 :                : 
                               1177                 :          15280 :     MessageEncoding = &pg_enc2name_tbl[encoding];
                               1178         [ -  + ]:          15280 :     Assert(MessageEncoding->encoding == encoding);
                               1179                 :          15280 : }
                               1180                 :                : 
                               1181                 :                : #ifdef ENABLE_NLS
                               1182                 :                : /*
                               1183                 :                :  * Make one bind_textdomain_codeset() call, translating a pg_enc to a gettext
                               1184                 :                :  * codeset.  Fails for MULE_INTERNAL, an encoding unknown to gettext; can also
                               1185                 :                :  * fail for gettext-internal causes like out-of-memory.
                               1186                 :                :  */
                               1187                 :                : static bool
                               1188                 :           1579 : raw_pg_bind_textdomain_codeset(const char *domainname, int encoding)
                               1189                 :                : {
                               1190                 :           1579 :     bool        elog_ok = (CurrentMemoryContext != NULL);
                               1191                 :                : 
  554 michael@paquier.xyz      1192   [ +  -  +  -  :           1579 :     if (!PG_VALID_ENCODING(encoding) || pg_enc2gettext_tbl[encoding] == NULL)
                                              -  + ]
  554 michael@paquier.xyz      1193                 :UBC           0 :         return false;
                               1194                 :                : 
  554 michael@paquier.xyz      1195         [ +  - ]:CBC        1579 :     if (bind_textdomain_codeset(domainname,
                               1196                 :                :                                 pg_enc2gettext_tbl[encoding]) != NULL)
                               1197                 :           1579 :         return true;
                               1198                 :                : 
  554 michael@paquier.xyz      1199         [ #  # ]:UBC           0 :     if (elog_ok)
                               1200         [ #  # ]:              0 :         elog(LOG, "bind_textdomain_codeset failed");
                               1201                 :                :     else
                               1202                 :              0 :         write_stderr("bind_textdomain_codeset failed");
                               1203                 :                : 
 4455 noah@leadboat.com        1204                 :              0 :     return false;
                               1205                 :                : }
                               1206                 :                : 
                               1207                 :                : /*
                               1208                 :                :  * Bind a gettext message domain to the codeset corresponding to the database
                               1209                 :                :  * encoding.  For SQL_ASCII, instead bind to the codeset implied by LC_CTYPE.
                               1210                 :                :  * Return the MessageEncoding implied by the new settings.
                               1211                 :                :  *
                               1212                 :                :  * On most platforms, gettext defaults to the codeset implied by LC_CTYPE.
                               1213                 :                :  * When that matches the database encoding, we don't need to do anything.  In
                               1214                 :                :  * CREATE DATABASE, we enforce or trust that the locale's codeset matches the
                               1215                 :                :  * database encoding, except for the C locale.  (On Windows, we also permit a
                               1216                 :                :  * discrepancy under the UTF8 encoding.)  For the C locale, explicitly bind
                               1217                 :                :  * gettext to the right codeset.
                               1218                 :                :  *
                               1219                 :                :  * On Windows, gettext defaults to the Windows ANSI code page.  This is a
                               1220                 :                :  * convenient departure for software that passes the strings to Windows ANSI
                               1221                 :                :  * APIs, but we don't do that.  Compel gettext to use database encoding or,
                               1222                 :                :  * failing that, the LC_CTYPE encoding as it would on other platforms.
                               1223                 :                :  *
                               1224                 :                :  * This function is called before elog() and palloc() are usable.
                               1225                 :                :  */
                               1226                 :                : int
 4455 noah@leadboat.com        1227                 :CBC       17189 : pg_bind_textdomain_codeset(const char *domainname)
                               1228                 :                : {
                               1229                 :          17189 :     bool        elog_ok = (CurrentMemoryContext != NULL);
                               1230                 :          17189 :     int         encoding = GetDatabaseEncoding();
                               1231                 :                :     int         new_msgenc;
                               1232                 :                : 
                               1233                 :                : #ifndef WIN32
                               1234                 :          17189 :     const char *ctype = setlocale(LC_CTYPE, NULL);
                               1235                 :                : 
                               1236   [ +  +  -  + ]:          17189 :     if (pg_strcasecmp(ctype, "C") == 0 || pg_strcasecmp(ctype, "POSIX") == 0)
                               1237                 :                : #endif
                               1238   [ +  +  +  - ]:           3547 :         if (encoding != PG_SQL_ASCII &&
                               1239                 :           1579 :             raw_pg_bind_textdomain_codeset(domainname, encoding))
                               1240                 :           1579 :             return encoding;
                               1241                 :                : 
                               1242                 :          15610 :     new_msgenc = pg_get_encoding_from_locale(NULL, elog_ok);
                               1243         [ -  + ]:          15610 :     if (new_msgenc < 0)
 4455 noah@leadboat.com        1244                 :UBC           0 :         new_msgenc = PG_SQL_ASCII;
                               1245                 :                : 
                               1246                 :                : #ifdef WIN32
                               1247                 :                :     if (!raw_pg_bind_textdomain_codeset(domainname, new_msgenc))
                               1248                 :                :         /* On failure, the old message encoding remains valid. */
                               1249                 :                :         return GetMessageEncoding();
                               1250                 :                : #endif
                               1251                 :                : 
 4455 noah@leadboat.com        1252                 :CBC       15610 :     return new_msgenc;
                               1253                 :                : }
                               1254                 :                : #endif
                               1255                 :                : 
                               1256                 :                : /*
                               1257                 :                :  * The database encoding, also called the server encoding, represents the
                               1258                 :                :  * encoding of data stored in text-like data types.  Affected types include
                               1259                 :                :  * cstring, text, varchar, name, xml, and json.
                               1260                 :                :  */
                               1261                 :                : int
 8751 tgl@sss.pgh.pa.us        1262                 :        7602478 : GetDatabaseEncoding(void)
                               1263                 :                : {
 7178 neilc@samurai.com        1264                 :        7602478 :     return DatabaseEncoding->encoding;
                               1265                 :                : }
                               1266                 :                : 
                               1267                 :                : const char *
 8751 tgl@sss.pgh.pa.us        1268                 :          28417 : GetDatabaseEncodingName(void)
                               1269                 :                : {
 7178 neilc@samurai.com        1270                 :          28417 :     return DatabaseEncoding->name;
                               1271                 :                : }
                               1272                 :                : 
                               1273                 :                : Datum
 9216 tgl@sss.pgh.pa.us        1274                 :             44 : getdatabaseencoding(PG_FUNCTION_ARGS)
                               1275                 :                : {
 8766 ishii@postgresql.org     1276                 :             44 :     return DirectFunctionCall1(namein, CStringGetDatum(DatabaseEncoding->name));
                               1277                 :                : }
                               1278                 :                : 
                               1279                 :                : Datum
 8730 ishii@postgresql.org     1280                 :UBC           0 : pg_client_encoding(PG_FUNCTION_ARGS)
                               1281                 :                : {
                               1282                 :              0 :     return DirectFunctionCall1(namein, CStringGetDatum(ClientEncoding->name));
                               1283                 :                : }
                               1284                 :                : 
                               1285                 :                : Datum
 2060 tgl@sss.pgh.pa.us        1286                 :CBC          18 : PG_char_to_encoding(PG_FUNCTION_ARGS)
                               1287                 :                : {
                               1288                 :             18 :     Name        s = PG_GETARG_NAME(0);
                               1289                 :                : 
                               1290                 :             18 :     PG_RETURN_INT32(pg_char_to_encoding(NameStr(*s)));
                               1291                 :                : }
                               1292                 :                : 
                               1293                 :                : Datum
                               1294                 :           2464 : PG_encoding_to_char(PG_FUNCTION_ARGS)
                               1295                 :                : {
                               1296                 :           2464 :     int32       encoding = PG_GETARG_INT32(0);
                               1297                 :           2464 :     const char *encoding_name = pg_encoding_to_char(encoding);
                               1298                 :                : 
                               1299                 :           2464 :     return DirectFunctionCall1(namein, CStringGetDatum(encoding_name));
                               1300                 :                : }
                               1301                 :                : 
                               1302                 :                : /*
                               1303                 :                :  * gettext() returns messages in this encoding.  This often matches the
                               1304                 :                :  * database encoding, but it differs for SQL_ASCII databases, for processes
                               1305                 :                :  * not attached to a database, and under a database encoding lacking iconv
                               1306                 :                :  * support (MULE_INTERNAL).
                               1307                 :                :  */
                               1308                 :                : int
 4455 noah@leadboat.com        1309                 :UBC           0 : GetMessageEncoding(void)
                               1310                 :                : {
                               1311                 :              0 :     return MessageEncoding->encoding;
                               1312                 :                : }
                               1313                 :                : 
                               1314                 :                : 
                               1315                 :                : /*
                               1316                 :                :  * Generic character incrementer function.
                               1317                 :                :  *
                               1318                 :                :  * Not knowing anything about the properties of the encoding in use, we just
                               1319                 :                :  * keep incrementing the last byte until we get a validly-encoded result,
                               1320                 :                :  * or we run out of values to try.  We don't bother to try incrementing
                               1321                 :                :  * higher-order bytes, so there's no growth in runtime for wider characters.
                               1322                 :                :  * (If we did try to do that, we'd need to consider the likelihood that 255
                               1323                 :                :  * is not a valid final byte in the encoding.)
                               1324                 :                :  */
                               1325                 :                : static bool
 2060 tgl@sss.pgh.pa.us        1326                 :CBC          52 : pg_generic_charinc(unsigned char *charptr, int len)
                               1327                 :                : {
                               1328                 :             52 :     unsigned char *lastbyte = charptr + len - 1;
                               1329                 :                :     mbchar_verifier mbverify;
                               1330                 :                : 
                               1331                 :                :     /* We can just invoke the character verifier directly. */
 1682 heikki.linnakangas@i     1332                 :             52 :     mbverify = pg_wchar_table[GetDatabaseEncoding()].mbverifychar;
                               1333                 :                : 
 2060 tgl@sss.pgh.pa.us        1334         [ +  - ]:             52 :     while (*lastbyte < (unsigned char) 255)
                               1335                 :                :     {
                               1336                 :             52 :         (*lastbyte)++;
                               1337         [ +  - ]:             52 :         if ((*mbverify) (charptr, len) == len)
                               1338                 :             52 :             return true;
                               1339                 :                :     }
                               1340                 :                : 
 2060 tgl@sss.pgh.pa.us        1341                 :UBC           0 :     return false;
                               1342                 :                : }
                               1343                 :                : 
                               1344                 :                : /*
                               1345                 :                :  * UTF-8 character incrementer function.
                               1346                 :                :  *
                               1347                 :                :  * For a one-byte character less than 0x7F, we just increment the byte.
                               1348                 :                :  *
                               1349                 :                :  * For a multibyte character, every byte but the first must fall between 0x80
                               1350                 :                :  * and 0xBF; and the first byte must be between 0xC0 and 0xF4.  We increment
                               1351                 :                :  * the last byte that's not already at its maximum value.  If we can't find a
                               1352                 :                :  * byte that's less than the maximum allowable value, we simply fail.  We also
                               1353                 :                :  * need some special-case logic to skip regions used for surrogate pair
                               1354                 :                :  * handling, as those should not occur in valid UTF-8.
                               1355                 :                :  *
                               1356                 :                :  * Note that we don't reset lower-order bytes back to their minimums, since
                               1357                 :                :  * we can't afford to make an exhaustive search (see make_greater_string).
                               1358                 :                :  */
                               1359                 :                : static bool
 2060 tgl@sss.pgh.pa.us        1360                 :CBC        1687 : pg_utf8_increment(unsigned char *charptr, int length)
                               1361                 :                : {
                               1362                 :                :     unsigned char a;
                               1363                 :                :     unsigned char limit;
                               1364                 :                : 
                               1365   [ -  -  -  -  :           1687 :     switch (length)
                                                 + ]
                               1366                 :                :     {
 2060 tgl@sss.pgh.pa.us        1367                 :UBC           0 :         default:
                               1368                 :                :             /* reject lengths 5 and 6 for now */
                               1369                 :              0 :             return false;
                               1370                 :              0 :         case 4:
                               1371                 :              0 :             a = charptr[3];
                               1372         [ #  # ]:              0 :             if (a < 0xBF)
                               1373                 :                :             {
                               1374                 :              0 :                 charptr[3]++;
                               1375                 :              0 :                 break;
                               1376                 :                :             }
                               1377                 :                :             /* FALL THRU */
                               1378                 :                :         case 3:
                               1379                 :              0 :             a = charptr[2];
                               1380         [ #  # ]:              0 :             if (a < 0xBF)
                               1381                 :                :             {
                               1382                 :              0 :                 charptr[2]++;
                               1383                 :              0 :                 break;
                               1384                 :                :             }
                               1385                 :                :             /* FALL THRU */
                               1386                 :                :         case 2:
                               1387                 :              0 :             a = charptr[1];
                               1388      [ #  #  # ]:              0 :             switch (*charptr)
                               1389                 :                :             {
                               1390                 :              0 :                 case 0xED:
                               1391                 :              0 :                     limit = 0x9F;
                               1392                 :              0 :                     break;
                               1393                 :              0 :                 case 0xF4:
                               1394                 :              0 :                     limit = 0x8F;
                               1395                 :              0 :                     break;
                               1396                 :              0 :                 default:
                               1397                 :              0 :                     limit = 0xBF;
                               1398                 :              0 :                     break;
                               1399                 :                :             }
                               1400         [ #  # ]:              0 :             if (a < limit)
                               1401                 :                :             {
                               1402                 :              0 :                 charptr[1]++;
                               1403                 :              0 :                 break;
                               1404                 :                :             }
                               1405                 :                :             /* FALL THRU */
                               1406                 :                :         case 1:
 2060 tgl@sss.pgh.pa.us        1407                 :CBC        1687 :             a = *charptr;
                               1408   [ +  -  +  -  :           1687 :             if (a == 0x7F || a == 0xDF || a == 0xEF || a == 0xF4)
                                        +  -  -  + ]
 2060 tgl@sss.pgh.pa.us        1409                 :UBC           0 :                 return false;
 2060 tgl@sss.pgh.pa.us        1410                 :CBC        1687 :             charptr[0]++;
                               1411                 :           1687 :             break;
                               1412                 :                :     }
                               1413                 :                : 
                               1414                 :           1687 :     return true;
                               1415                 :                : }
                               1416                 :                : 
                               1417                 :                : /*
                               1418                 :                :  * EUC-JP character incrementer function.
                               1419                 :                :  *
                               1420                 :                :  * If the sequence starts with SS2 (0x8e), it must be a two-byte sequence
                               1421                 :                :  * representing JIS X 0201 characters with the second byte ranging between
                               1422                 :                :  * 0xa1 and 0xdf.  We just increment the last byte if it's less than 0xdf,
                               1423                 :                :  * and otherwise rewrite the whole sequence to 0xa1 0xa1.
                               1424                 :                :  *
                               1425                 :                :  * If the sequence starts with SS3 (0x8f), it must be a three-byte sequence
                               1426                 :                :  * in which the last two bytes range between 0xa1 and 0xfe.  The last byte
                               1427                 :                :  * is incremented if possible, otherwise the second-to-last byte.
                               1428                 :                :  *
                               1429                 :                :  * If the sequence starts with a value other than the above and its MSB
                               1430                 :                :  * is set, it must be a two-byte sequence representing JIS X 0208 characters
                               1431                 :                :  * with both bytes ranging between 0xa1 and 0xfe.  The last byte is
                               1432                 :                :  * incremented if possible, otherwise the second-to-last byte.
                               1433                 :                :  *
                               1434                 :                :  * Otherwise, the sequence is a single-byte ASCII character. It is
                               1435                 :                :  * incremented up to 0x7f.
                               1436                 :                :  */
                               1437                 :                : static bool
 2060 tgl@sss.pgh.pa.us        1438                 :UBC           0 : pg_eucjp_increment(unsigned char *charptr, int length)
                               1439                 :                : {
                               1440                 :                :     unsigned char c1,
                               1441                 :                :                 c2;
                               1442                 :                :     int         i;
                               1443                 :                : 
                               1444                 :              0 :     c1 = *charptr;
                               1445                 :                : 
                               1446      [ #  #  # ]:              0 :     switch (c1)
                               1447                 :                :     {
                               1448                 :              0 :         case SS2:               /* JIS X 0201 */
                               1449         [ #  # ]:              0 :             if (length != 2)
                               1450                 :              0 :                 return false;
                               1451                 :                : 
                               1452                 :              0 :             c2 = charptr[1];
                               1453                 :                : 
                               1454         [ #  # ]:              0 :             if (c2 >= 0xdf)
                               1455                 :              0 :                 charptr[0] = charptr[1] = 0xa1;
                               1456         [ #  # ]:              0 :             else if (c2 < 0xa1)
                               1457                 :              0 :                 charptr[1] = 0xa1;
                               1458                 :                :             else
                               1459                 :              0 :                 charptr[1]++;
                               1460                 :              0 :             break;
                               1461                 :                : 
                               1462                 :              0 :         case SS3:               /* JIS X 0212 */
                               1463         [ #  # ]:              0 :             if (length != 3)
                               1464                 :              0 :                 return false;
                               1465                 :                : 
                               1466         [ #  # ]:              0 :             for (i = 2; i > 0; i--)
                               1467                 :                :             {
                               1468                 :              0 :                 c2 = charptr[i];
                               1469         [ #  # ]:              0 :                 if (c2 < 0xa1)
                               1470                 :                :                 {
                               1471                 :              0 :                     charptr[i] = 0xa1;
                               1472                 :              0 :                     return true;
                               1473                 :                :                 }
                               1474         [ #  # ]:              0 :                 else if (c2 < 0xfe)
                               1475                 :                :                 {
                               1476                 :              0 :                     charptr[i]++;
                               1477                 :              0 :                     return true;
                               1478                 :                :                 }
                               1479                 :                :             }
                               1480                 :                : 
                               1481                 :                :             /* Out of 3-byte code region */
                               1482                 :              0 :             return false;
                               1483                 :                : 
                               1484                 :              0 :         default:
                               1485         [ #  # ]:              0 :             if (IS_HIGHBIT_SET(c1)) /* JIS X 0208? */
                               1486                 :                :             {
                               1487         [ #  # ]:              0 :                 if (length != 2)
                               1488                 :              0 :                     return false;
                               1489                 :                : 
                               1490         [ #  # ]:              0 :                 for (i = 1; i >= 0; i--)
                               1491                 :                :                 {
                               1492                 :              0 :                     c2 = charptr[i];
                               1493         [ #  # ]:              0 :                     if (c2 < 0xa1)
                               1494                 :                :                     {
                               1495                 :              0 :                         charptr[i] = 0xa1;
                               1496                 :              0 :                         return true;
                               1497                 :                :                     }
                               1498         [ #  # ]:              0 :                     else if (c2 < 0xfe)
                               1499                 :                :                     {
                               1500                 :              0 :                         charptr[i]++;
                               1501                 :              0 :                         return true;
                               1502                 :                :                     }
                               1503                 :                :                 }
                               1504                 :                : 
                               1505                 :                :                 /* Out of 2 byte code region */
                               1506                 :              0 :                 return false;
                               1507                 :                :             }
                               1508                 :                :             else
                               1509                 :                :             {                   /* ASCII, single byte */
                               1510         [ #  # ]:              0 :                 if (c1 > 0x7e)
                               1511                 :              0 :                     return false;
                               1512                 :              0 :                 (*charptr)++;
                               1513                 :                :             }
                               1514                 :              0 :             break;
                               1515                 :                :     }
                               1516                 :                : 
                               1517                 :              0 :     return true;
                               1518                 :                : }
                               1519                 :                : 
                               1520                 :                : /*
                               1521                 :                :  * get the character incrementer for the encoding for the current database
                               1522                 :                :  */
                               1523                 :                : mbcharacter_incrementer
 2060 tgl@sss.pgh.pa.us        1524                 :CBC        1739 : pg_database_encoding_character_incrementer(void)
                               1525                 :                : {
                               1526                 :                :     /*
                               1527                 :                :      * Eventually it might be best to add a field to pg_wchar_table[], but for
                               1528                 :                :      * now we just use a switch.
                               1529                 :                :      */
                               1530      [ +  -  + ]:           1739 :     switch (GetDatabaseEncoding())
                               1531                 :                :     {
                               1532                 :           1687 :         case PG_UTF8:
                               1533                 :           1687 :             return pg_utf8_increment;
                               1534                 :                : 
 2060 tgl@sss.pgh.pa.us        1535                 :UBC           0 :         case PG_EUC_JP:
                               1536                 :              0 :             return pg_eucjp_increment;
                               1537                 :                : 
 2060 tgl@sss.pgh.pa.us        1538                 :CBC          52 :         default:
                               1539                 :             52 :             return pg_generic_charinc;
                               1540                 :                :     }
                               1541                 :                : }
                               1542                 :                : 
                               1543                 :                : /*
                               1544                 :                :  * fetch maximum length of the encoding for the current database
                               1545                 :                :  */
                               1546                 :                : int
                               1547                 :        6236968 : pg_database_encoding_max_length(void)
                               1548                 :                : {
                               1549                 :        6236968 :     return pg_wchar_table[GetDatabaseEncoding()].maxmblen;
                               1550                 :                : }
                               1551                 :                : 
                               1552                 :                : /*
                               1553                 :                :  * Verify mbstr to make sure that it is validly encoded in the current
                               1554                 :                :  * database encoding.  Otherwise same as pg_verify_mbstr().
                               1555                 :                :  */
                               1556                 :                : bool
                               1557                 :         103594 : pg_verifymbstr(const char *mbstr, int len, bool noError)
                               1558                 :                : {
 1682 heikki.linnakangas@i     1559                 :         103594 :     return pg_verify_mbstr(GetDatabaseEncoding(), mbstr, len, noError);
                               1560                 :                : }
                               1561                 :                : 
                               1562                 :                : /*
                               1563                 :                :  * Verify mbstr to make sure that it is validly encoded in the specified
                               1564                 :                :  * encoding.
                               1565                 :                :  */
                               1566                 :                : bool
 2060 tgl@sss.pgh.pa.us        1567                 :         815519 : pg_verify_mbstr(int encoding, const char *mbstr, int len, bool noError)
                               1568                 :                : {
                               1569                 :                :     int         oklen;
                               1570                 :                : 
 1682 heikki.linnakangas@i     1571   [ +  -  -  + ]:         815519 :     Assert(PG_VALID_ENCODING(encoding));
                               1572                 :                : 
                               1573                 :         815519 :     oklen = pg_wchar_table[encoding].mbverifystr((const unsigned char *) mbstr, len);
                               1574         [ +  + ]:         815519 :     if (oklen != len)
                               1575                 :                :     {
                               1576         [ -  + ]:              4 :         if (noError)
 1682 heikki.linnakangas@i     1577                 :UBC           0 :             return false;
 1682 heikki.linnakangas@i     1578                 :CBC           4 :         report_invalid_encoding(encoding, mbstr + oklen, len - oklen);
                               1579                 :                :     }
                               1580                 :         815515 :     return true;
                               1581                 :                : }
                               1582                 :                : 
                               1583                 :                : /*
                               1584                 :                :  * Verify mbstr to make sure that it is validly encoded in the specified
                               1585                 :                :  * encoding.
                               1586                 :                :  *
                               1587                 :                :  * mbstr is not necessarily zero terminated; length of mbstr is
                               1588                 :                :  * specified by len.
                               1589                 :                :  *
                               1590                 :                :  * If OK, return length of string in the encoding.
                               1591                 :                :  * If a problem is found, return -1 when noError is
                               1592                 :                :  * true; when noError is false, ereport() a descriptive message.
                               1593                 :                :  *
                               1594                 :                :  * Note: We cannot use the faster encoding-specific mbverifystr() function
                               1595                 :                :  * here, because we need to count the number of characters in the string.
                               1596                 :                :  */
                               1597                 :                : int
 2060 tgl@sss.pgh.pa.us        1598                 :UBC           0 : pg_verify_mbstr_len(int encoding, const char *mbstr, int len, bool noError)
                               1599                 :                : {
                               1600                 :                :     mbchar_verifier mbverifychar;
                               1601                 :                :     int         mb_len;
                               1602                 :                : 
                               1603   [ #  #  #  # ]:              0 :     Assert(PG_VALID_ENCODING(encoding));
                               1604                 :                : 
                               1605                 :                :     /*
                               1606                 :                :      * In single-byte encodings, we need only reject nulls (\0).
                               1607                 :                :      */
                               1608         [ #  # ]:              0 :     if (pg_encoding_max_length(encoding) <= 1)
                               1609                 :                :     {
                               1610                 :              0 :         const char *nullpos = memchr(mbstr, 0, len);
                               1611                 :                : 
                               1612         [ #  # ]:              0 :         if (nullpos == NULL)
                               1613                 :              0 :             return len;
                               1614         [ #  # ]:              0 :         if (noError)
                               1615                 :              0 :             return -1;
                               1616                 :              0 :         report_invalid_encoding(encoding, nullpos, 1);
                               1617                 :                :     }
                               1618                 :                : 
                               1619                 :                :     /* fetch function pointer just once */
 1682 heikki.linnakangas@i     1620                 :              0 :     mbverifychar = pg_wchar_table[encoding].mbverifychar;
                               1621                 :                : 
 2060 tgl@sss.pgh.pa.us        1622                 :              0 :     mb_len = 0;
                               1623                 :                : 
                               1624         [ #  # ]:              0 :     while (len > 0)
                               1625                 :                :     {
                               1626                 :                :         int         l;
                               1627                 :                : 
                               1628                 :                :         /* fast path for ASCII-subset characters */
                               1629         [ #  # ]:              0 :         if (!IS_HIGHBIT_SET(*mbstr))
                               1630                 :                :         {
                               1631         [ #  # ]:              0 :             if (*mbstr != '\0')
                               1632                 :                :             {
                               1633                 :              0 :                 mb_len++;
                               1634                 :              0 :                 mbstr++;
                               1635                 :              0 :                 len--;
                               1636                 :              0 :                 continue;
                               1637                 :                :             }
                               1638         [ #  # ]:              0 :             if (noError)
                               1639                 :              0 :                 return -1;
                               1640                 :              0 :             report_invalid_encoding(encoding, mbstr, len);
                               1641                 :                :         }
                               1642                 :                : 
 1682 heikki.linnakangas@i     1643                 :              0 :         l = (*mbverifychar) ((const unsigned char *) mbstr, len);
                               1644                 :                : 
 2060 tgl@sss.pgh.pa.us        1645         [ #  # ]:              0 :         if (l < 0)
                               1646                 :                :         {
                               1647         [ #  # ]:              0 :             if (noError)
                               1648                 :              0 :                 return -1;
                               1649                 :              0 :             report_invalid_encoding(encoding, mbstr, len);
                               1650                 :                :         }
                               1651                 :                : 
                               1652                 :              0 :         mbstr += l;
                               1653                 :              0 :         len -= l;
                               1654                 :              0 :         mb_len++;
                               1655                 :                :     }
                               1656                 :              0 :     return mb_len;
                               1657                 :                : }
                               1658                 :                : 
                               1659                 :                : /*
                               1660                 :                :  * check_encoding_conversion_args: check arguments of a conversion function
                               1661                 :                :  *
                               1662                 :                :  * "expected" arguments can be either an encoding ID or -1 to indicate that
                               1663                 :                :  * the caller will check whether it accepts the ID.
                               1664                 :                :  *
                               1665                 :                :  * Note: the errors here are not really user-facing, so elog instead of
                               1666                 :                :  * ereport seems sufficient.  Also, we trust that the "expected" encoding
                               1667                 :                :  * arguments are valid encoding IDs, but we don't trust the actuals.
                               1668                 :                :  */
                               1669                 :                : void
 2060 tgl@sss.pgh.pa.us        1670                 :CBC        3533 : check_encoding_conversion_args(int src_encoding,
                               1671                 :                :                                int dest_encoding,
                               1672                 :                :                                int len,
                               1673                 :                :                                int expected_src_encoding,
                               1674                 :                :                                int expected_dest_encoding)
                               1675                 :                : {
                               1676   [ +  -  -  + ]:           3533 :     if (!PG_VALID_ENCODING(src_encoding))
 2060 tgl@sss.pgh.pa.us        1677         [ #  # ]:UBC           0 :         elog(ERROR, "invalid source encoding ID: %d", src_encoding);
 2060 tgl@sss.pgh.pa.us        1678   [ +  +  -  + ]:CBC        3533 :     if (src_encoding != expected_src_encoding && expected_src_encoding >= 0)
 2060 tgl@sss.pgh.pa.us        1679         [ #  # ]:UBC           0 :         elog(ERROR, "expected source encoding \"%s\", but got \"%s\"",
                               1680                 :                :              pg_enc2name_tbl[expected_src_encoding].name,
                               1681                 :                :              pg_enc2name_tbl[src_encoding].name);
 2060 tgl@sss.pgh.pa.us        1682   [ +  -  -  + ]:CBC        3533 :     if (!PG_VALID_ENCODING(dest_encoding))
 2060 tgl@sss.pgh.pa.us        1683         [ #  # ]:UBC           0 :         elog(ERROR, "invalid destination encoding ID: %d", dest_encoding);
 2060 tgl@sss.pgh.pa.us        1684   [ +  +  -  + ]:CBC        3533 :     if (dest_encoding != expected_dest_encoding && expected_dest_encoding >= 0)
 2060 tgl@sss.pgh.pa.us        1685         [ #  # ]:UBC           0 :         elog(ERROR, "expected destination encoding \"%s\", but got \"%s\"",
                               1686                 :                :              pg_enc2name_tbl[expected_dest_encoding].name,
                               1687                 :                :              pg_enc2name_tbl[dest_encoding].name);
 2060 tgl@sss.pgh.pa.us        1688         [ -  + ]:CBC        3533 :     if (len < 0)
 2060 tgl@sss.pgh.pa.us        1689         [ #  # ]:UBC           0 :         elog(ERROR, "encoding conversion length must not be negative");
 2060 tgl@sss.pgh.pa.us        1690                 :CBC        3533 : }
                               1691                 :                : 
                               1692                 :                : /*
                               1693                 :                :  * report_invalid_encoding: complain about invalid multibyte character
                               1694                 :                :  *
                               1695                 :                :  * note: len is remaining length of string, not length of character;
                               1696                 :                :  * len must be greater than zero (or we'd neglect initializing "buf").
                               1697                 :                :  */
                               1698                 :                : void
                               1699                 :           1495 : report_invalid_encoding(int encoding, const char *mbstr, int len)
                               1700                 :                : {
  124 noah@leadboat.com        1701                 :           1495 :     int         l = pg_encoding_mblen_or_incomplete(encoding, mbstr, len);
                               1702                 :                :     char        buf[8 * 5 + 1];
 2060 tgl@sss.pgh.pa.us        1703                 :           1495 :     char       *p = buf;
                               1704                 :                :     int         j,
                               1705                 :                :                 jlimit;
                               1706                 :                : 
                               1707                 :           1495 :     jlimit = Min(l, len);
                               1708                 :           1495 :     jlimit = Min(jlimit, 8);    /* prevent buffer overrun */
                               1709                 :                : 
                               1710         [ +  + ]:           4613 :     for (j = 0; j < jlimit; j++)
                               1711                 :                :     {
                               1712                 :           3118 :         p += sprintf(p, "0x%02x", (unsigned char) mbstr[j]);
                               1713         [ +  + ]:           3118 :         if (j < jlimit - 1)
                               1714                 :           1623 :             p += sprintf(p, " ");
                               1715                 :                :     }
                               1716                 :                : 
                               1717         [ +  - ]:           1495 :     ereport(ERROR,
                               1718                 :                :             (errcode(ERRCODE_CHARACTER_NOT_IN_REPERTOIRE),
                               1719                 :                :              errmsg("invalid byte sequence for encoding \"%s\": %s",
                               1720                 :                :                     pg_enc2name_tbl[encoding].name,
                               1721                 :                :                     buf)));
                               1722                 :                : }
                               1723                 :                : 
                               1724                 :                : /*
                               1725                 :                :  * report_untranslatable_char: complain about untranslatable character
                               1726                 :                :  *
                               1727                 :                :  * note: len is remaining length of string, not length of character;
                               1728                 :                :  * len must be greater than zero (or we'd neglect initializing "buf").
                               1729                 :                :  */
                               1730                 :                : void
                               1731                 :            468 : report_untranslatable_char(int src_encoding, int dest_encoding,
                               1732                 :                :                            const char *mbstr, int len)
                               1733                 :                : {
                               1734                 :                :     int         l;
                               1735                 :                :     char        buf[8 * 5 + 1];
                               1736                 :            468 :     char       *p = buf;
                               1737                 :                :     int         j,
                               1738                 :                :                 jlimit;
                               1739                 :                : 
                               1740                 :                :     /*
                               1741                 :                :      * We probably could use plain pg_encoding_mblen(), because
                               1742                 :                :      * gb18030_to_utf8() verifies before it converts.  All conversions should.
                               1743                 :                :      * For src_encoding!=GB18030, len>0 meets pg_encoding_mblen() needs.  Even
                               1744                 :                :      * so, be defensive, since a buggy conversion might pass invalid data.
                               1745                 :                :      * This is not a performance-critical path.
                               1746                 :                :      */
  124 noah@leadboat.com        1747                 :            468 :     l = pg_encoding_mblen_or_incomplete(src_encoding, mbstr, len);
 2060 tgl@sss.pgh.pa.us        1748                 :            468 :     jlimit = Min(l, len);
                               1749                 :            468 :     jlimit = Min(jlimit, 8);    /* prevent buffer overrun */
                               1750                 :                : 
                               1751         [ +  + ]:           1764 :     for (j = 0; j < jlimit; j++)
                               1752                 :                :     {
                               1753                 :           1296 :         p += sprintf(p, "0x%02x", (unsigned char) mbstr[j]);
                               1754         [ +  + ]:           1296 :         if (j < jlimit - 1)
                               1755                 :            828 :             p += sprintf(p, " ");
                               1756                 :                :     }
                               1757                 :                : 
                               1758         [ +  - ]:            468 :     ereport(ERROR,
                               1759                 :                :             (errcode(ERRCODE_UNTRANSLATABLE_CHARACTER),
                               1760                 :                :              errmsg("character with byte sequence %s in encoding \"%s\" has no equivalent in encoding \"%s\"",
                               1761                 :                :                     buf,
                               1762                 :                :                     pg_enc2name_tbl[src_encoding].name,
                               1763                 :                :                     pg_enc2name_tbl[dest_encoding].name)));
                               1764                 :                : }
                               1765                 :                : 
                               1766                 :                : 
                               1767                 :                : #ifdef WIN32
                               1768                 :                : /*
                               1769                 :                :  * Convert from MessageEncoding to a palloc'ed, null-terminated utf16
                               1770                 :                :  * string. The character length is also passed to utf16len if not
                               1771                 :                :  * null. Returns NULL iff failed. Before MessageEncoding initialization, "str"
                               1772                 :                :  * should be ASCII-only; this will function as though MessageEncoding is UTF8.
                               1773                 :                :  */
                               1774                 :                : WCHAR *
                               1775                 :                : pgwin32_message_to_UTF16(const char *str, int len, int *utf16len)
                               1776                 :                : {
                               1777                 :                :     int         msgenc = GetMessageEncoding();
                               1778                 :                :     WCHAR      *utf16;
                               1779                 :                :     int         dstlen;
                               1780                 :                :     UINT        codepage;
                               1781                 :                : 
                               1782                 :                :     if (msgenc == PG_SQL_ASCII)
                               1783                 :                :         /* No conversion is possible, and SQL_ASCII is never utf16. */
                               1784                 :                :         return NULL;
                               1785                 :                : 
                               1786                 :                :     codepage = pg_enc2name_tbl[msgenc].codepage;
                               1787                 :                : 
                               1788                 :                :     /*
                               1789                 :                :      * Use MultiByteToWideChar directly if there is a corresponding codepage,
                               1790                 :                :      * or double conversion through UTF8 if not.  Double conversion is needed,
                               1791                 :                :      * for example, in an ENCODING=LATIN8, LC_CTYPE=C database.
                               1792                 :                :      */
                               1793                 :                :     if (codepage != 0)
                               1794                 :                :     {
                               1795                 :                :         utf16 = (WCHAR *) palloc(sizeof(WCHAR) * (len + 1));
                               1796                 :                :         dstlen = MultiByteToWideChar(codepage, 0, str, len, utf16, len);
                               1797                 :                :         utf16[dstlen] = (WCHAR) 0;
                               1798                 :                :     }
                               1799                 :                :     else
                               1800                 :                :     {
                               1801                 :                :         char       *utf8;
                               1802                 :                : 
                               1803                 :                :         /*
                               1804                 :                :          * XXX pg_do_encoding_conversion() requires a transaction.  In the
                               1805                 :                :          * absence of one, hope for the input to be valid UTF8.
                               1806                 :                :          */
                               1807                 :                :         if (IsTransactionState())
                               1808                 :                :         {
                               1809                 :                :             utf8 = (char *) pg_do_encoding_conversion((unsigned char *) str,
                               1810                 :                :                                                       len,
                               1811                 :                :                                                       msgenc,
                               1812                 :                :                                                       PG_UTF8);
                               1813                 :                :             if (utf8 != str)
                               1814                 :                :                 len = strlen(utf8);
                               1815                 :                :         }
                               1816                 :                :         else
                               1817                 :                :             utf8 = (char *) str;
                               1818                 :                : 
                               1819                 :                :         utf16 = (WCHAR *) palloc(sizeof(WCHAR) * (len + 1));
                               1820                 :                :         dstlen = MultiByteToWideChar(CP_UTF8, 0, utf8, len, utf16, len);
                               1821                 :                :         utf16[dstlen] = (WCHAR) 0;
                               1822                 :                : 
                               1823                 :                :         if (utf8 != str)
                               1824                 :                :             pfree(utf8);
                               1825                 :                :     }
                               1826                 :                : 
                               1827                 :                :     if (dstlen == 0 && len > 0)
                               1828                 :                :     {
                               1829                 :                :         pfree(utf16);
                               1830                 :                :         return NULL;            /* error */
                               1831                 :                :     }
                               1832                 :                : 
                               1833                 :                :     if (utf16len)
                               1834                 :                :         *utf16len = dstlen;
                               1835                 :                :     return utf16;
                               1836                 :                : }
                               1837                 :                : 
                               1838                 :                : #endif                          /* WIN32 */
        

Generated by: LCOV version 2.4-beta