Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / third_party / icu / source / common / ucnv_bld.cpp
1 /*
2  ********************************************************************
3  * COPYRIGHT:
4  * Copyright (c) 1996-2013, International Business Machines Corporation and
5  * others. All Rights Reserved.
6  ********************************************************************
7  *
8  *  uconv_bld.cpp:
9  *
10  *  Defines functions that are used in the creation/initialization/deletion
11  *  of converters and related structures.
12  *  uses uconv_io.h routines to access disk information
13  *  is used by ucnv.h to implement public API create/delete/flushCache routines
14  * Modification History:
15  *
16  *   Date        Name        Description
17  *
18  *   06/20/2000  helena      OS/400 port changes; mostly typecast.
19  *   06/29/2000  helena      Major rewrite of the callback interface.
20 */
21
22 #include "unicode/utypes.h"
23
24 #if !UCONFIG_NO_CONVERSION
25
26 #include "unicode/putil.h"
27 #include "unicode/udata.h"
28 #include "unicode/ucnv.h"
29 #include "unicode/uloc.h"
30 #include "mutex.h"
31 #include "putilimp.h"
32 #include "uassert.h"
33 #include "utracimp.h"
34 #include "ucnv_io.h"
35 #include "ucnv_bld.h"
36 #include "ucnvmbcs.h"
37 #include "ucnv_ext.h"
38 #include "ucnv_cnv.h"
39 #include "ucnv_imp.h"
40 #include "uhash.h"
41 #include "umutex.h"
42 #include "cstring.h"
43 #include "cmemory.h"
44 #include "ucln_cmn.h"
45 #include "ustr_cnv.h"
46
47
48 #if 0
49 #include <stdio.h>
50 extern void UCNV_DEBUG_LOG(char *what, char *who, void *p, int l);
51 #define UCNV_DEBUG_LOG(x,y,z) UCNV_DEBUG_LOG(x,y,z,__LINE__)
52 #else
53 # define UCNV_DEBUG_LOG(x,y,z)
54 #endif
55
56 static const UConverterSharedData * const
57 converterData[UCNV_NUMBER_OF_SUPPORTED_CONVERTER_TYPES]={
58     NULL, NULL,
59
60 #if UCONFIG_NO_LEGACY_CONVERSION
61     NULL,
62 #else
63     &_MBCSData,
64 #endif
65
66     &_Latin1Data,
67     &_UTF8Data, &_UTF16BEData, &_UTF16LEData, &_UTF32BEData, &_UTF32LEData,
68     NULL,
69
70 #if UCONFIG_NO_LEGACY_CONVERSION
71     NULL,
72     NULL, NULL, NULL, NULL, NULL, NULL,
73     NULL, NULL, NULL, NULL, NULL, NULL,
74     NULL,
75 #else
76     &_ISO2022Data,
77     &_LMBCSData1,&_LMBCSData2, &_LMBCSData3, &_LMBCSData4, &_LMBCSData5, &_LMBCSData6,
78     &_LMBCSData8,&_LMBCSData11,&_LMBCSData16,&_LMBCSData17,&_LMBCSData18,&_LMBCSData19,
79     &_HZData,
80 #endif
81
82 #if UCONFIG_NO_NON_HTML5_CONVERSION
83     NULL,
84 #else
85     &_SCSUData,
86 #endif
87
88
89 #if UCONFIG_NO_LEGACY_CONVERSION || UCONFIG_NO_NON_HTML5_CONVERSION
90     NULL,
91 #else
92     &_ISCIIData,
93 #endif
94
95     &_ASCIIData,
96 #if UCONFIG_NO_NON_HTML5_CONVERSION
97     NULL, NULL, &_UTF16Data, &_UTF32Data, NULL, NULL,
98 #else
99     &_UTF7Data, &_Bocu1Data, &_UTF16Data, &_UTF32Data, &_CESU8Data, &_IMAPData,
100 #endif
101
102 #if UCONFIG_NO_LEGACY_CONVERSION
103     NULL,
104 #else
105     &_CompoundTextData
106 #endif
107 };
108
109 /* Please keep this in binary sorted order for getAlgorithmicTypeFromName.
110    Also the name should be in lower case and all spaces, dashes and underscores
111    removed
112 */
113 static struct {
114   const char *name;
115   const UConverterType type;
116 } const cnvNameType[] = {
117   { "bocu1", UCNV_BOCU1 },
118   { "cesu8", UCNV_CESU8 },
119 #if !UCONFIG_NO_LEGACY_CONVERSION
120   { "hz",UCNV_HZ },
121 #endif
122   { "imapmailboxname", UCNV_IMAP_MAILBOX },
123 #if !UCONFIG_NO_LEGACY_CONVERSION
124   { "iscii", UCNV_ISCII },
125   { "iso2022", UCNV_ISO_2022 },
126 #endif
127   { "iso88591", UCNV_LATIN_1 },
128 #if !UCONFIG_NO_LEGACY_CONVERSION
129   { "lmbcs1", UCNV_LMBCS_1 },
130   { "lmbcs11",UCNV_LMBCS_11 },
131   { "lmbcs16",UCNV_LMBCS_16 },
132   { "lmbcs17",UCNV_LMBCS_17 },
133   { "lmbcs18",UCNV_LMBCS_18 },
134   { "lmbcs19",UCNV_LMBCS_19 },
135   { "lmbcs2", UCNV_LMBCS_2 },
136   { "lmbcs3", UCNV_LMBCS_3 },
137   { "lmbcs4", UCNV_LMBCS_4 },
138   { "lmbcs5", UCNV_LMBCS_5 },
139   { "lmbcs6", UCNV_LMBCS_6 },
140   { "lmbcs8", UCNV_LMBCS_8 },
141 #endif
142   { "scsu", UCNV_SCSU },
143   { "usascii", UCNV_US_ASCII },
144   { "utf16", UCNV_UTF16 },
145   { "utf16be", UCNV_UTF16_BigEndian },
146   { "utf16le", UCNV_UTF16_LittleEndian },
147 #if U_IS_BIG_ENDIAN
148   { "utf16oppositeendian", UCNV_UTF16_LittleEndian },
149   { "utf16platformendian", UCNV_UTF16_BigEndian },
150 #else
151   { "utf16oppositeendian", UCNV_UTF16_BigEndian},
152   { "utf16platformendian", UCNV_UTF16_LittleEndian },
153 #endif
154   { "utf32", UCNV_UTF32 },
155   { "utf32be", UCNV_UTF32_BigEndian },
156   { "utf32le", UCNV_UTF32_LittleEndian },
157 #if U_IS_BIG_ENDIAN
158   { "utf32oppositeendian", UCNV_UTF32_LittleEndian },
159   { "utf32platformendian", UCNV_UTF32_BigEndian },
160 #else
161   { "utf32oppositeendian", UCNV_UTF32_BigEndian },
162   { "utf32platformendian", UCNV_UTF32_LittleEndian },
163 #endif
164   { "utf7", UCNV_UTF7 },
165   { "utf8", UCNV_UTF8 },
166   { "x11compoundtext", UCNV_COMPOUND_TEXT}
167 };
168
169
170 /*initializes some global variables */
171 static UHashtable *SHARED_DATA_HASHTABLE = NULL;
172 static UMutex cnvCacheMutex = U_MUTEX_INITIALIZER;  /* Mutex for synchronizing cnv cache access. */
173                                                     /*  Note:  the global mutex is used for      */
174                                                     /*         reference count updates.          */
175
176 static const char **gAvailableConverters = NULL;
177 static uint16_t gAvailableConverterCount = 0;
178 static icu::UInitOnce gAvailableConvertersInitOnce = U_INITONCE_INITIALIZER;
179
180 #if !U_CHARSET_IS_UTF8
181
182 /* This contains the resolved converter name. So no further alias lookup is needed again. */
183 static char gDefaultConverterNameBuffer[UCNV_MAX_CONVERTER_NAME_LENGTH + 1]; /* +1 for NULL */
184 static const char *gDefaultConverterName = NULL;
185
186 /*
187 If the default converter is an algorithmic converter, this is the cached value.
188 We don't cache a full UConverter and clone it because ucnv_clone doesn't have
189 less overhead than an algorithmic open. We don't cache non-algorithmic converters
190 because ucnv_flushCache must be able to unload the default converter and its table.
191 */
192 static const UConverterSharedData *gDefaultAlgorithmicSharedData = NULL;
193
194 /* Does gDefaultConverterName have a converter option and require extra parsing? */
195 static UBool gDefaultConverterContainsOption;
196
197 #endif  /* !U_CHARSET_IS_UTF8 */
198
199 static const char DATA_TYPE[] = "cnv";
200
201 /* ucnv_flushAvailableConverterCache. This is only called from ucnv_cleanup().
202  *                       If it is ever to be called from elsewhere, synchronization 
203  *                       will need to be considered.
204  */
205 static void
206 ucnv_flushAvailableConverterCache() {
207     gAvailableConverterCount = 0;
208     if (gAvailableConverters) {
209         uprv_free((char **)gAvailableConverters);
210         gAvailableConverters = NULL;
211     }
212     gAvailableConvertersInitOnce.reset();
213 }
214
215 /* ucnv_cleanup - delete all storage held by the converter cache, except any  */
216 /*                in use by open converters.                                  */
217 /*                Not thread safe.                                            */
218 /*                Not supported API.                                          */
219 static UBool U_CALLCONV ucnv_cleanup(void) {
220     ucnv_flushCache();
221     if (SHARED_DATA_HASHTABLE != NULL && uhash_count(SHARED_DATA_HASHTABLE) == 0) {
222         uhash_close(SHARED_DATA_HASHTABLE);
223         SHARED_DATA_HASHTABLE = NULL;
224     }
225
226     /* Isn't called from flushCache because other threads may have preexisting references to the table. */
227     ucnv_flushAvailableConverterCache();
228
229 #if !U_CHARSET_IS_UTF8
230     gDefaultConverterName = NULL;
231     gDefaultConverterNameBuffer[0] = 0;
232     gDefaultConverterContainsOption = FALSE;
233     gDefaultAlgorithmicSharedData = NULL;
234 #endif
235
236     return (SHARED_DATA_HASHTABLE == NULL);
237 }
238
239 static UBool U_CALLCONV
240 isCnvAcceptable(void * /*context*/,
241                 const char * /*type*/, const char * /*name*/,
242                 const UDataInfo *pInfo) {
243     return (UBool)(
244         pInfo->size>=20 &&
245         pInfo->isBigEndian==U_IS_BIG_ENDIAN &&
246         pInfo->charsetFamily==U_CHARSET_FAMILY &&
247         pInfo->sizeofUChar==U_SIZEOF_UCHAR &&
248         pInfo->dataFormat[0]==0x63 &&   /* dataFormat="cnvt" */
249         pInfo->dataFormat[1]==0x6e &&
250         pInfo->dataFormat[2]==0x76 &&
251         pInfo->dataFormat[3]==0x74 &&
252         pInfo->formatVersion[0]==6);  /* Everything will be version 6 */
253 }
254
255 /**
256  * Un flatten shared data from a UDATA..
257  */
258 static UConverterSharedData*
259 ucnv_data_unFlattenClone(UConverterLoadArgs *pArgs, UDataMemory *pData, UErrorCode *status)
260 {
261     /* UDataInfo info; -- necessary only if some converters have different formatVersion */
262     const uint8_t *raw = (const uint8_t *)udata_getMemory(pData);
263     const UConverterStaticData *source = (const UConverterStaticData *) raw;
264     UConverterSharedData *data;
265     UConverterType type = (UConverterType)source->conversionType;
266
267     if(U_FAILURE(*status))
268         return NULL;
269
270     if( (uint16_t)type >= UCNV_NUMBER_OF_SUPPORTED_CONVERTER_TYPES ||
271         converterData[type] == NULL ||
272         converterData[type]->referenceCounter != 1 ||
273         source->structSize != sizeof(UConverterStaticData))
274     {
275         *status = U_INVALID_TABLE_FORMAT;
276         return NULL;
277     }
278
279     data = (UConverterSharedData *)uprv_malloc(sizeof(UConverterSharedData));
280     if(data == NULL) {
281         *status = U_MEMORY_ALLOCATION_ERROR;
282         return NULL;
283     }
284
285     /* copy initial values from the static structure for this type */
286     uprv_memcpy(data, converterData[type], sizeof(UConverterSharedData));
287
288 #if 0 /* made UConverterMBCSTable part of UConverterSharedData -- markus 20031107 */
289     /*
290      * It would be much more efficient if the table were a direct member, not a pointer.
291      * However, that would add to the size of all UConverterSharedData objects
292      * even if they do not use this table (especially algorithmic ones).
293      * If this changes, then the static templates from converterData[type]
294      * need more entries.
295      *
296      * In principle, it would be cleaner if the load() function below
297      * allocated the table.
298      */
299     data->table = (UConverterTable *)uprv_malloc(sizeof(UConverterTable));
300     if(data->table == NULL) {
301         uprv_free(data);
302         *status = U_MEMORY_ALLOCATION_ERROR;
303         return NULL;
304     }
305     uprv_memset(data->table, 0, sizeof(UConverterTable));
306 #endif
307
308     data->staticData = source;
309
310     data->sharedDataCached = FALSE;
311
312     /* fill in fields from the loaded data */
313     data->dataMemory = (void*)pData; /* for future use */
314
315     if(data->impl->load != NULL) {
316         data->impl->load(data, pArgs, raw + source->structSize, status);
317         if(U_FAILURE(*status)) {
318             uprv_free(data->table);
319             uprv_free(data);
320             return NULL;
321         }
322     }
323     return data;
324 }
325
326 /*Takes an alias name gets an actual converter file name
327  *goes to disk and opens it.
328  *allocates the memory and returns a new UConverter object
329  */
330 static UConverterSharedData *createConverterFromFile(UConverterLoadArgs *pArgs, UErrorCode * err)
331 {
332     UDataMemory *data;
333     UConverterSharedData *sharedData;
334
335     UTRACE_ENTRY_OC(UTRACE_UCNV_LOAD);
336
337     if (U_FAILURE (*err)) {
338         UTRACE_EXIT_STATUS(*err);
339         return NULL;
340     }
341
342     UTRACE_DATA2(UTRACE_OPEN_CLOSE, "load converter %s from package %s", pArgs->name, pArgs->pkg);
343
344     data = udata_openChoice(pArgs->pkg, DATA_TYPE, pArgs->name, isCnvAcceptable, NULL, err);
345     if(U_FAILURE(*err))
346     {
347         UTRACE_EXIT_STATUS(*err);
348         return NULL;
349     }
350
351     sharedData = ucnv_data_unFlattenClone(pArgs, data, err);
352     if(U_FAILURE(*err))
353     {
354         udata_close(data);
355         UTRACE_EXIT_STATUS(*err);
356         return NULL;
357     }
358
359     /*
360      * TODO Store pkg in a field in the shared data so that delta-only converters
361      * can load base converters from the same package.
362      * If the pkg name is longer than the field, then either do not load the converter
363      * in the first place, or just set the pkg field to "".
364      */
365
366     UTRACE_EXIT_PTR_STATUS(sharedData, *err);
367     return sharedData;
368 }
369
370 /*returns a converter type from a string
371  */
372 static const UConverterSharedData *
373 getAlgorithmicTypeFromName(const char *realName)
374 {
375     uint32_t mid, start, limit;
376     uint32_t lastMid;
377     int result;
378     char strippedName[UCNV_MAX_CONVERTER_NAME_LENGTH];
379
380     /* Lower case and remove ignoreable characters. */
381     ucnv_io_stripForCompare(strippedName, realName);
382
383     /* do a binary search for the alias */
384     start = 0;
385     limit = sizeof(cnvNameType)/sizeof(cnvNameType[0]);
386     mid = limit;
387     lastMid = UINT32_MAX;
388
389     for (;;) {
390         mid = (uint32_t)((start + limit) / 2);
391         if (lastMid == mid) {   /* Have we moved? */
392             break;  /* We haven't moved, and it wasn't found. */
393         }
394         lastMid = mid;
395         result = uprv_strcmp(strippedName, cnvNameType[mid].name);
396
397         if (result < 0) {
398             limit = mid;
399         } else if (result > 0) {
400             start = mid;
401         } else {
402             return converterData[cnvNameType[mid].type];
403         }
404     }
405
406     return NULL;
407 }
408
409 /*
410 * Based on the number of known converters, this determines how many times larger
411 * the shared data hash table should be. When on small platforms, or just a couple
412 * of converters are used, this number should be 2. When memory is plentiful, or
413 * when ucnv_countAvailable is ever used with a lot of available converters,
414 * this should be 4.
415 * Larger numbers reduce the number of hash collisions, but use more memory.
416 */
417 #define UCNV_CACHE_LOAD_FACTOR 2
418
419 /* Puts the shared data in the static hashtable SHARED_DATA_HASHTABLE */
420 /*   Will always be called with the cnvCacheMutex alrady being held   */
421 /*     by the calling function.                                       */
422 /* Stores the shared data in the SHARED_DATA_HASHTABLE
423  * @param data The shared data
424  */
425 static void
426 ucnv_shareConverterData(UConverterSharedData * data)
427 {
428     UErrorCode err = U_ZERO_ERROR;
429     /*Lazy evaluates the Hashtable itself */
430     /*void *sanity = NULL;*/
431
432     if (SHARED_DATA_HASHTABLE == NULL)
433     {
434         SHARED_DATA_HASHTABLE = uhash_openSize(uhash_hashChars, uhash_compareChars, NULL,
435                             ucnv_io_countKnownConverters(&err)*UCNV_CACHE_LOAD_FACTOR,
436                             &err);
437         ucln_common_registerCleanup(UCLN_COMMON_UCNV, ucnv_cleanup);
438
439         if (U_FAILURE(err))
440             return;
441     }
442
443     /* ### check to see if the element is not already there! */
444
445     /*
446     sanity =   ucnv_getSharedConverterData (data->staticData->name);
447     if(sanity != NULL)
448     {
449     UCNV_DEBUG_LOG("put:overwrite!",data->staticData->name,sanity);
450     }
451     UCNV_DEBUG_LOG("put:chk",data->staticData->name,sanity);
452     */
453
454     /* Mark it shared */
455     data->sharedDataCached = TRUE;
456
457     uhash_put(SHARED_DATA_HASHTABLE,
458             (void*) data->staticData->name, /* Okay to cast away const as long as
459             keyDeleter == NULL */
460             data,
461             &err);
462     UCNV_DEBUG_LOG("put", data->staticData->name,data);
463
464 }
465
466 /*  Look up a converter name in the shared data cache.                    */
467 /*    cnvCacheMutex must be held by the caller to protect the hash table. */
468 /* gets the shared data from the SHARED_DATA_HASHTABLE (might return NULL if it isn't there)
469  * @param name The name of the shared data
470  * @return the shared data from the SHARED_DATA_HASHTABLE
471  */
472 static UConverterSharedData *
473 ucnv_getSharedConverterData(const char *name)
474 {
475     /*special case when no Table has yet been created we return NULL */
476     if (SHARED_DATA_HASHTABLE == NULL)
477     {
478         return NULL;
479     }
480     else
481     {
482         UConverterSharedData *rc;
483
484         rc = (UConverterSharedData*)uhash_get(SHARED_DATA_HASHTABLE, name);
485         UCNV_DEBUG_LOG("get",name,rc);
486         return rc;
487     }
488 }
489
490 /*frees the string of memory blocks associates with a sharedConverter
491  *if and only if the referenceCounter == 0
492  */
493 /* Deletes (frees) the Shared data it's passed. first it checks the referenceCounter to
494  * see if anyone is using it, if not it frees all the memory stemming from sharedConverterData and
495  * returns TRUE,
496  * otherwise returns FALSE
497  * @param sharedConverterData The shared data
498  * @return if not it frees all the memory stemming from sharedConverterData and
499  * returns TRUE, otherwise returns FALSE
500  */
501 static UBool
502 ucnv_deleteSharedConverterData(UConverterSharedData * deadSharedData)
503 {
504     UTRACE_ENTRY_OC(UTRACE_UCNV_UNLOAD);
505     UTRACE_DATA2(UTRACE_OPEN_CLOSE, "unload converter %s shared data %p", deadSharedData->staticData->name, deadSharedData);
506
507     if (deadSharedData->referenceCounter > 0) {
508         UTRACE_EXIT_VALUE((int32_t)FALSE);
509         return FALSE;
510     }
511
512     if (deadSharedData->impl->unload != NULL) {
513         deadSharedData->impl->unload(deadSharedData);
514     }
515
516     if(deadSharedData->dataMemory != NULL)
517     {
518         UDataMemory *data = (UDataMemory*)deadSharedData->dataMemory;
519         udata_close(data);
520     }
521
522     if(deadSharedData->table != NULL)
523     {
524         uprv_free(deadSharedData->table);
525     }
526
527 #if 0
528     /* if the static data is actually owned by the shared data */
529     /* enable if we ever have this situation. */
530     if(deadSharedData->staticDataOwned == TRUE) /* see ucnv_bld.h */
531     {
532         uprv_free((void*)deadSharedData->staticData);
533     }
534 #endif
535
536 #if 0
537     /* Zap it ! */
538     uprv_memset(deadSharedData->0, sizeof(*deadSharedData));
539 #endif
540
541     uprv_free(deadSharedData);
542
543     UTRACE_EXIT_VALUE((int32_t)TRUE);
544     return TRUE;
545 }
546
547 /**
548  * Load a non-algorithmic converter.
549  * If pkg==NULL, then this function must be called inside umtx_lock(&cnvCacheMutex).
550  */
551 UConverterSharedData *
552 ucnv_load(UConverterLoadArgs *pArgs, UErrorCode *err) {
553     UConverterSharedData *mySharedConverterData;
554
555     if(err == NULL || U_FAILURE(*err)) {
556         return NULL;
557     }
558
559     if(pArgs->pkg != NULL && *pArgs->pkg != 0) {
560         /* application-provided converters are not currently cached */
561         return createConverterFromFile(pArgs, err);
562     }
563
564     mySharedConverterData = ucnv_getSharedConverterData(pArgs->name);
565     if (mySharedConverterData == NULL)
566     {
567         /*Not cached, we need to stream it in from file */
568         mySharedConverterData = createConverterFromFile(pArgs, err);
569         if (U_FAILURE (*err) || (mySharedConverterData == NULL))
570         {
571             return NULL;
572         }
573         else if (!pArgs->onlyTestIsLoadable)
574         {
575             /* share it with other library clients */
576             ucnv_shareConverterData(mySharedConverterData);
577         }
578     }
579     else
580     {
581         /* The data for this converter was already in the cache.            */
582         /* Update the reference counter on the shared data: one more client */
583         mySharedConverterData->referenceCounter++;
584     }
585
586     return mySharedConverterData;
587 }
588
589 /**
590  * Unload a non-algorithmic converter.
591  * It must be sharedData->referenceCounter != ~0
592  * and this function must be called inside umtx_lock(&cnvCacheMutex).
593  */
594 U_CAPI void
595 ucnv_unload(UConverterSharedData *sharedData) {
596     if(sharedData != NULL) {
597         if (sharedData->referenceCounter > 0) {
598             sharedData->referenceCounter--;
599         }
600
601         if((sharedData->referenceCounter <= 0)&&(sharedData->sharedDataCached == FALSE)) {
602             ucnv_deleteSharedConverterData(sharedData);
603         }
604     }
605 }
606
607 U_CFUNC void
608 ucnv_unloadSharedDataIfReady(UConverterSharedData *sharedData)
609 {
610     /*
611     Checking whether it's an algorithic converter is okay
612     in multithreaded applications because the value never changes.
613     Don't check referenceCounter for any other value.
614     */
615     if(sharedData != NULL && sharedData->referenceCounter != (uint32_t)~0) {
616         umtx_lock(&cnvCacheMutex);
617         ucnv_unload(sharedData);
618         umtx_unlock(&cnvCacheMutex);
619     }
620 }
621
622 U_CFUNC void
623 ucnv_incrementRefCount(UConverterSharedData *sharedData)
624 {
625     /*
626     Checking whether it's an algorithic converter is okay
627     in multithreaded applications because the value never changes.
628     Don't check referenceCounter for any other value.
629     */
630     if(sharedData != NULL && sharedData->referenceCounter != (uint32_t)~0) {
631         umtx_lock(&cnvCacheMutex);
632         sharedData->referenceCounter++;
633         umtx_unlock(&cnvCacheMutex);
634     }
635 }
636
637 /*
638  * *pPieces must be initialized.
639  * The name without options will be copied to pPieces->cnvName.
640  * The locale and options will be copied to pPieces only if present in inName,
641  * otherwise the existing values in pPieces remain.
642  * *pArgs will be set to the pPieces values.
643  */
644 static void
645 parseConverterOptions(const char *inName,
646                       UConverterNamePieces *pPieces,
647                       UConverterLoadArgs *pArgs,
648                       UErrorCode *err)
649 {
650     char *cnvName = pPieces->cnvName;
651     char c;
652     int32_t len = 0;
653
654     pArgs->name=inName;
655     pArgs->locale=pPieces->locale;
656     pArgs->options=pPieces->options;
657
658     /* copy the converter name itself to cnvName */
659     while((c=*inName)!=0 && c!=UCNV_OPTION_SEP_CHAR) {
660         if (++len>=UCNV_MAX_CONVERTER_NAME_LENGTH) {
661             *err = U_ILLEGAL_ARGUMENT_ERROR;    /* bad name */
662             pPieces->cnvName[0]=0;
663             return;
664         }
665         *cnvName++=c;
666         inName++;
667     }
668     *cnvName=0;
669     pArgs->name=pPieces->cnvName;
670
671     /* parse options. No more name copying should occur. */
672     while((c=*inName)!=0) {
673         if(c==UCNV_OPTION_SEP_CHAR) {
674             ++inName;
675         }
676
677         /* inName is behind an option separator */
678         if(uprv_strncmp(inName, "locale=", 7)==0) {
679             /* do not modify locale itself in case we have multiple locale options */
680             char *dest=pPieces->locale;
681
682             /* copy the locale option value */
683             inName+=7;
684             len=0;
685             while((c=*inName)!=0 && c!=UCNV_OPTION_SEP_CHAR) {
686                 ++inName;
687
688                 if(++len>=ULOC_FULLNAME_CAPACITY) {
689                     *err=U_ILLEGAL_ARGUMENT_ERROR;    /* bad name */
690                     pPieces->locale[0]=0;
691                     return;
692                 }
693
694                 *dest++=c;
695             }
696             *dest=0;
697         } else if(uprv_strncmp(inName, "version=", 8)==0) {
698             /* copy the version option value into bits 3..0 of pPieces->options */
699             inName+=8;
700             c=*inName;
701             if(c==0) {
702                 pArgs->options=(pPieces->options&=~UCNV_OPTION_VERSION);
703                 return;
704             } else if((uint8_t)(c-'0')<10) {
705                 pArgs->options=pPieces->options=(pPieces->options&~UCNV_OPTION_VERSION)|(uint32_t)(c-'0');
706                 ++inName;
707             }
708         } else if(uprv_strncmp(inName, "swaplfnl", 8)==0) {
709             inName+=8;
710             pArgs->options=(pPieces->options|=UCNV_OPTION_SWAP_LFNL);
711         /* add processing for new options here with another } else if(uprv_strncmp(inName, "option-name=", XX)==0) { */
712         } else {
713             /* ignore any other options until we define some */
714             while(((c = *inName++) != 0) && (c != UCNV_OPTION_SEP_CHAR)) {
715             }
716             if(c==0) {
717                 return;
718             }
719         }
720     }
721 }
722
723 /*Logic determines if the converter is Algorithmic AND/OR cached
724  *depending on that:
725  * -we either go to get data from disk and cache it (Data=TRUE, Cached=False)
726  * -Get it from a Hashtable (Data=X, Cached=TRUE)
727  * -Call dataConverter initializer (Data=TRUE, Cached=TRUE)
728  * -Call AlgorithmicConverter initializer (Data=FALSE, Cached=TRUE)
729  */
730 U_CFUNC UConverterSharedData *
731 ucnv_loadSharedData(const char *converterName,
732                     UConverterNamePieces *pPieces,
733                     UConverterLoadArgs *pArgs,
734                     UErrorCode * err) {
735     UConverterNamePieces stackPieces;
736     UConverterLoadArgs stackArgs;
737     UConverterSharedData *mySharedConverterData = NULL;
738     UErrorCode internalErrorCode = U_ZERO_ERROR;
739     UBool mayContainOption = TRUE;
740     UBool checkForAlgorithmic = TRUE;
741
742     if (U_FAILURE (*err)) {
743         return NULL;
744     }
745
746     if(pPieces == NULL) {
747         if(pArgs != NULL) {
748             /*
749              * Bad: We may set pArgs pointers to stackPieces fields
750              * which will be invalid after this function returns.
751              */
752             *err = U_INTERNAL_PROGRAM_ERROR;
753             return NULL;
754         }
755         pPieces = &stackPieces;
756     }
757     if(pArgs == NULL) {
758         uprv_memset(&stackArgs, 0, sizeof(stackArgs));
759         stackArgs.size = (int32_t)sizeof(stackArgs);
760         pArgs = &stackArgs;
761     }
762
763     pPieces->cnvName[0] = 0;
764     pPieces->locale[0] = 0;
765     pPieces->options = 0;
766
767     pArgs->name = converterName;
768     pArgs->locale = pPieces->locale;
769     pArgs->options = pPieces->options;
770
771     /* In case "name" is NULL we want to open the default converter. */
772     if (converterName == NULL) {
773 #if U_CHARSET_IS_UTF8
774         pArgs->name = "UTF-8";
775         return (UConverterSharedData *)converterData[UCNV_UTF8];
776 #else
777         /* Call ucnv_getDefaultName first to query the name from the OS. */
778         pArgs->name = ucnv_getDefaultName();
779         if (pArgs->name == NULL) {
780             *err = U_MISSING_RESOURCE_ERROR;
781             return NULL;
782         }
783         mySharedConverterData = (UConverterSharedData *)gDefaultAlgorithmicSharedData;
784         checkForAlgorithmic = FALSE;
785         mayContainOption = gDefaultConverterContainsOption;
786         /* the default converter name is already canonical */
787 #endif
788     }
789     else if(UCNV_FAST_IS_UTF8(converterName)) {
790         /* fastpath for UTF-8 */
791         pArgs->name = "UTF-8";
792         return (UConverterSharedData *)converterData[UCNV_UTF8];
793     }
794     else {
795         /* separate the converter name from the options */
796         parseConverterOptions(converterName, pPieces, pArgs, err);
797         if (U_FAILURE(*err)) {
798             /* Very bad name used. */
799             return NULL;
800         }
801
802         /* get the canonical converter name */
803         pArgs->name = ucnv_io_getConverterName(pArgs->name, &mayContainOption, &internalErrorCode);
804         if (U_FAILURE(internalErrorCode) || pArgs->name == NULL) {
805             /*
806             * set the input name in case the converter was added
807             * without updating the alias table, or when there is no alias table
808             */
809             pArgs->name = pPieces->cnvName;
810         } else if (internalErrorCode == U_AMBIGUOUS_ALIAS_WARNING) {
811             *err = U_AMBIGUOUS_ALIAS_WARNING;
812         }
813     }
814
815     /* separate the converter name from the options */
816     if(mayContainOption && pArgs->name != pPieces->cnvName) {
817         parseConverterOptions(pArgs->name, pPieces, pArgs, err);
818     }
819
820     /* get the shared data for an algorithmic converter, if it is one */
821     if (checkForAlgorithmic) {
822         mySharedConverterData = (UConverterSharedData *)getAlgorithmicTypeFromName(pArgs->name);
823     }
824     if (mySharedConverterData == NULL)
825     {
826         /* it is a data-based converter, get its shared data.               */
827         /* Hold the cnvCacheMutex through the whole process of checking the */
828         /*   converter data cache, and adding new entries to the cache      */
829         /*   to prevent other threads from modifying the cache during the   */
830         /*   process.                                                       */
831         pArgs->nestedLoads=1;
832         pArgs->pkg=NULL;
833
834         umtx_lock(&cnvCacheMutex);
835         mySharedConverterData = ucnv_load(pArgs, err);
836         umtx_unlock(&cnvCacheMutex);
837         if (U_FAILURE (*err) || (mySharedConverterData == NULL))
838         {
839             return NULL;
840         }
841     }
842
843     return mySharedConverterData;
844 }
845
846 U_CAPI UConverter *
847 ucnv_createConverter(UConverter *myUConverter, const char *converterName, UErrorCode * err)
848 {
849     UConverterNamePieces stackPieces;
850     UConverterLoadArgs stackArgs=UCNV_LOAD_ARGS_INITIALIZER;
851     UConverterSharedData *mySharedConverterData;
852
853     UTRACE_ENTRY_OC(UTRACE_UCNV_OPEN);
854
855     if(U_SUCCESS(*err)) {
856         UTRACE_DATA1(UTRACE_OPEN_CLOSE, "open converter %s", converterName);
857
858         mySharedConverterData = ucnv_loadSharedData(converterName, &stackPieces, &stackArgs, err);
859
860         myUConverter = ucnv_createConverterFromSharedData(
861             myUConverter, mySharedConverterData,
862             &stackArgs,
863             err);
864
865         if(U_SUCCESS(*err)) {
866             UTRACE_EXIT_PTR_STATUS(myUConverter, *err);
867             return myUConverter;
868         }
869     }
870
871     /* exit with error */
872     UTRACE_EXIT_STATUS(*err);
873     return NULL;
874 }
875
876 U_CFUNC UBool
877 ucnv_canCreateConverter(const char *converterName, UErrorCode *err) {
878     UConverter myUConverter;
879     UConverterNamePieces stackPieces;
880     UConverterLoadArgs stackArgs=UCNV_LOAD_ARGS_INITIALIZER;
881     UConverterSharedData *mySharedConverterData;
882
883     UTRACE_ENTRY_OC(UTRACE_UCNV_OPEN);
884
885     if(U_SUCCESS(*err)) {
886         UTRACE_DATA1(UTRACE_OPEN_CLOSE, "test if can open converter %s", converterName);
887
888         stackArgs.onlyTestIsLoadable=TRUE;
889         mySharedConverterData = ucnv_loadSharedData(converterName, &stackPieces, &stackArgs, err);
890         ucnv_createConverterFromSharedData(
891             &myUConverter, mySharedConverterData,
892             &stackArgs,
893             err);
894         ucnv_unloadSharedDataIfReady(mySharedConverterData);
895     }
896
897     UTRACE_EXIT_STATUS(*err);
898     return U_SUCCESS(*err);
899 }
900
901 UConverter *
902 ucnv_createAlgorithmicConverter(UConverter *myUConverter,
903                                 UConverterType type,
904                                 const char *locale, uint32_t options,
905                                 UErrorCode *err) {
906     UConverter *cnv;
907     const UConverterSharedData *sharedData;
908     UConverterLoadArgs stackArgs=UCNV_LOAD_ARGS_INITIALIZER;
909
910     UTRACE_ENTRY_OC(UTRACE_UCNV_OPEN_ALGORITHMIC);
911     UTRACE_DATA1(UTRACE_OPEN_CLOSE, "open algorithmic converter type %d", (int32_t)type);
912
913     if(type<0 || UCNV_NUMBER_OF_SUPPORTED_CONVERTER_TYPES<=type) {
914         *err = U_ILLEGAL_ARGUMENT_ERROR;
915         UTRACE_EXIT_STATUS(U_ILLEGAL_ARGUMENT_ERROR);
916         return NULL;
917     }
918
919     sharedData = converterData[type];
920     /*
921     Checking whether it's an algorithic converter is okay
922     in multithreaded applications because the value never changes.
923     Don't check referenceCounter for any other value.
924     */
925     if(sharedData == NULL || sharedData->referenceCounter != (uint32_t)~0) {
926         /* not a valid type, or not an algorithmic converter */
927         *err = U_ILLEGAL_ARGUMENT_ERROR;
928         UTRACE_EXIT_STATUS(U_ILLEGAL_ARGUMENT_ERROR);
929         return NULL;
930     }
931
932     stackArgs.name = "";
933     stackArgs.options = options;
934     stackArgs.locale=locale;
935     cnv = ucnv_createConverterFromSharedData(
936             myUConverter, (UConverterSharedData *)sharedData,
937             &stackArgs, err);
938
939     UTRACE_EXIT_PTR_STATUS(cnv, *err);
940     return cnv;
941 }
942
943 U_CFUNC UConverter*
944 ucnv_createConverterFromPackage(const char *packageName, const char *converterName, UErrorCode * err)
945 {
946     UConverter *myUConverter;
947     UConverterSharedData *mySharedConverterData;
948     UConverterNamePieces stackPieces;
949     UConverterLoadArgs stackArgs=UCNV_LOAD_ARGS_INITIALIZER;
950
951     UTRACE_ENTRY_OC(UTRACE_UCNV_OPEN_PACKAGE);
952
953     if(U_FAILURE(*err)) {
954         UTRACE_EXIT_STATUS(*err);
955         return NULL;
956     }
957
958     UTRACE_DATA2(UTRACE_OPEN_CLOSE, "open converter %s from package %s", converterName, packageName);
959
960     /* first, get the options out of the converterName string */
961     stackPieces.cnvName[0] = 0;
962     stackPieces.locale[0] = 0;
963     stackPieces.options = 0;
964     parseConverterOptions(converterName, &stackPieces, &stackArgs, err);
965     if (U_FAILURE(*err)) {
966         /* Very bad name used. */
967         UTRACE_EXIT_STATUS(*err);
968         return NULL;
969     }
970     stackArgs.nestedLoads=1;
971     stackArgs.pkg=packageName;
972
973     /* open the data, unflatten the shared structure */
974     mySharedConverterData = createConverterFromFile(&stackArgs, err);
975
976     if (U_FAILURE(*err)) {
977         UTRACE_EXIT_STATUS(*err);
978         return NULL;
979     }
980
981     /* create the actual converter */
982     myUConverter = ucnv_createConverterFromSharedData(NULL, mySharedConverterData, &stackArgs, err);
983
984     if (U_FAILURE(*err)) {
985         ucnv_close(myUConverter);
986         UTRACE_EXIT_STATUS(*err);
987         return NULL;
988     }
989
990     UTRACE_EXIT_PTR_STATUS(myUConverter, *err);
991     return myUConverter;
992 }
993
994
995 U_CFUNC UConverter*
996 ucnv_createConverterFromSharedData(UConverter *myUConverter,
997                                    UConverterSharedData *mySharedConverterData,
998                                    UConverterLoadArgs *pArgs,
999                                    UErrorCode *err)
1000 {
1001     UBool isCopyLocal;
1002
1003     if(U_FAILURE(*err)) {
1004         ucnv_unloadSharedDataIfReady(mySharedConverterData);
1005         return myUConverter;
1006     }
1007     if(myUConverter == NULL)
1008     {
1009         myUConverter = (UConverter *) uprv_malloc (sizeof (UConverter));
1010         if(myUConverter == NULL)
1011         {
1012             *err = U_MEMORY_ALLOCATION_ERROR;
1013             ucnv_unloadSharedDataIfReady(mySharedConverterData);
1014             return NULL;
1015         }
1016         isCopyLocal = FALSE;
1017     } else {
1018         isCopyLocal = TRUE;
1019     }
1020
1021     /* initialize the converter */
1022     uprv_memset(myUConverter, 0, sizeof(UConverter));
1023     myUConverter->isCopyLocal = isCopyLocal;
1024     /*myUConverter->isExtraLocal = FALSE;*/ /* Set by the memset call */
1025     myUConverter->sharedData = mySharedConverterData;
1026     myUConverter->options = pArgs->options;
1027     if(!pArgs->onlyTestIsLoadable) {
1028         myUConverter->preFromUFirstCP = U_SENTINEL;
1029         myUConverter->fromCharErrorBehaviour = UCNV_TO_U_DEFAULT_CALLBACK;
1030         myUConverter->fromUCharErrorBehaviour = UCNV_FROM_U_DEFAULT_CALLBACK;
1031         myUConverter->toUnicodeStatus = mySharedConverterData->toUnicodeStatus;
1032         myUConverter->maxBytesPerUChar = mySharedConverterData->staticData->maxBytesPerChar;
1033         myUConverter->subChar1 = mySharedConverterData->staticData->subChar1;
1034         myUConverter->subCharLen = mySharedConverterData->staticData->subCharLen;
1035         myUConverter->subChars = (uint8_t *)myUConverter->subUChars;
1036         uprv_memcpy(myUConverter->subChars, mySharedConverterData->staticData->subChar, myUConverter->subCharLen);
1037         myUConverter->toUCallbackReason = UCNV_ILLEGAL; /* default reason to invoke (*fromCharErrorBehaviour) */
1038     }
1039
1040     if(mySharedConverterData->impl->open != NULL) {
1041         mySharedConverterData->impl->open(myUConverter, pArgs, err);
1042         if(U_FAILURE(*err) && !pArgs->onlyTestIsLoadable) {
1043             /* don't ucnv_close() if onlyTestIsLoadable because not fully initialized */
1044             ucnv_close(myUConverter);
1045             return NULL;
1046         }
1047     }
1048
1049     return myUConverter;
1050 }
1051
1052 /*Frees all shared immutable objects that aren't referred to (reference count = 0)
1053  */
1054 U_CAPI int32_t U_EXPORT2
1055 ucnv_flushCache ()
1056 {
1057     UConverterSharedData *mySharedData = NULL;
1058     int32_t pos;
1059     int32_t tableDeletedNum = 0;
1060     const UHashElement *e;
1061     /*UErrorCode status = U_ILLEGAL_ARGUMENT_ERROR;*/
1062     int32_t i, remaining;
1063
1064     UTRACE_ENTRY_OC(UTRACE_UCNV_FLUSH_CACHE);
1065
1066     /* Close the default converter without creating a new one so that everything will be flushed. */
1067     u_flushDefaultConverter();
1068
1069     /*if shared data hasn't even been lazy evaluated yet
1070     * return 0
1071     */
1072     if (SHARED_DATA_HASHTABLE == NULL) {
1073         UTRACE_EXIT_VALUE((int32_t)0);
1074         return 0;
1075     }
1076
1077     /*creates an enumeration to iterate through every element in the
1078     * table
1079     *
1080     * Synchronization:  holding cnvCacheMutex will prevent any other thread from
1081     *                   accessing or modifying the hash table during the iteration.
1082     *                   The reference count of an entry may be decremented by
1083     *                   ucnv_close while the iteration is in process, but this is
1084     *                   benign.  It can't be incremented (in ucnv_createConverter())
1085     *                   because the sequence of looking up in the cache + incrementing
1086     *                   is protected by cnvCacheMutex.
1087     */
1088     umtx_lock(&cnvCacheMutex);
1089     /*
1090      * double loop: A delta/extension-only converter has a pointer to its base table's
1091      * shared data; the first iteration of the outer loop may see the delta converter
1092      * before the base converter, and unloading the delta converter may get the base
1093      * converter's reference counter down to 0.
1094      */
1095     i = 0;
1096     do {
1097         remaining = 0;
1098         pos = -1;
1099         while ((e = uhash_nextElement (SHARED_DATA_HASHTABLE, &pos)) != NULL)
1100         {
1101             mySharedData = (UConverterSharedData *) e->value.pointer;
1102             /*deletes only if reference counter == 0 */
1103             if (mySharedData->referenceCounter == 0)
1104             {
1105                 tableDeletedNum++;
1106
1107                 UCNV_DEBUG_LOG("del",mySharedData->staticData->name,mySharedData);
1108
1109                 uhash_removeElement(SHARED_DATA_HASHTABLE, e);
1110                 mySharedData->sharedDataCached = FALSE;
1111                 ucnv_deleteSharedConverterData (mySharedData);
1112             } else {
1113                 ++remaining;
1114             }
1115         }
1116     } while(++i == 1 && remaining > 0);
1117     umtx_unlock(&cnvCacheMutex);
1118
1119     UTRACE_DATA1(UTRACE_INFO, "ucnv_flushCache() exits with %d converters remaining", remaining);
1120
1121     UTRACE_EXIT_VALUE(tableDeletedNum);
1122     return tableDeletedNum;
1123 }
1124
1125 /* available converters list --------------------------------------------------- */
1126
1127 static void U_CALLCONV initAvailableConvertersList(UErrorCode &errCode) {
1128     U_ASSERT(gAvailableConverterCount == 0);
1129     U_ASSERT(gAvailableConverters == NULL);
1130
1131     ucln_common_registerCleanup(UCLN_COMMON_UCNV, ucnv_cleanup);
1132     UEnumeration *allConvEnum = ucnv_openAllNames(&errCode);
1133     int32_t allConverterCount = uenum_count(allConvEnum, &errCode);
1134     if (U_FAILURE(errCode)) {
1135         return;
1136     }
1137
1138     /* We can't have more than "*converterTable" converters to open */
1139     gAvailableConverters = (const char **) uprv_malloc(allConverterCount * sizeof(char*));
1140     if (!gAvailableConverters) {
1141         errCode = U_MEMORY_ALLOCATION_ERROR;
1142         return;
1143     }
1144
1145     /* Open the default converter to make sure that it has first dibs in the hash table. */
1146     UErrorCode localStatus = U_ZERO_ERROR;
1147     UConverter tempConverter;
1148     ucnv_close(ucnv_createConverter(&tempConverter, NULL, &localStatus));
1149
1150     gAvailableConverterCount = 0;
1151
1152     for (int32_t idx = 0; idx < allConverterCount; idx++) {
1153         localStatus = U_ZERO_ERROR;
1154         const char *converterName = uenum_next(allConvEnum, NULL, &localStatus);
1155         if (ucnv_canCreateConverter(converterName, &localStatus)) {
1156             gAvailableConverters[gAvailableConverterCount++] = converterName;
1157         }
1158     }
1159
1160     uenum_close(allConvEnum);
1161 }
1162
1163
1164 static UBool haveAvailableConverterList(UErrorCode *pErrorCode) {
1165     umtx_initOnce(gAvailableConvertersInitOnce, &initAvailableConvertersList, *pErrorCode);
1166     return U_SUCCESS(*pErrorCode);
1167 }
1168
1169 U_CFUNC uint16_t
1170 ucnv_bld_countAvailableConverters(UErrorCode *pErrorCode) {
1171     if (haveAvailableConverterList(pErrorCode)) {
1172         return gAvailableConverterCount;
1173     }
1174     return 0;
1175 }
1176
1177 U_CFUNC const char *
1178 ucnv_bld_getAvailableConverter(uint16_t n, UErrorCode *pErrorCode) {
1179     if (haveAvailableConverterList(pErrorCode)) {
1180         if (n < gAvailableConverterCount) {
1181             return gAvailableConverters[n];
1182         }
1183         *pErrorCode = U_INDEX_OUTOFBOUNDS_ERROR;
1184     }
1185     return NULL;
1186 }
1187
1188 /* default converter name --------------------------------------------------- */
1189
1190 #if !U_CHARSET_IS_UTF8
1191 /*
1192 Copy the canonical converter name.
1193 ucnv_getDefaultName must be thread safe, which can call this function.
1194
1195 ucnv_setDefaultName calls this function and it doesn't have to be
1196 thread safe because there is no reliable/safe way to reset the
1197 converter in use in all threads. If you did reset the converter, you
1198 would not be sure that retrieving a default converter for one string
1199 would be the same type of default converter for a successive string.
1200 Since the name is a returned via ucnv_getDefaultName without copying,
1201 you shouldn't be modifying or deleting the string from a separate thread.
1202 */
1203 static inline void
1204 internalSetName(const char *name, UErrorCode *status) {
1205     UConverterNamePieces stackPieces;
1206     UConverterLoadArgs stackArgs=UCNV_LOAD_ARGS_INITIALIZER;
1207     int32_t length=(int32_t)(uprv_strlen(name));
1208     UBool containsOption = (UBool)(uprv_strchr(name, UCNV_OPTION_SEP_CHAR) != NULL);
1209     const UConverterSharedData *algorithmicSharedData;
1210
1211     stackArgs.name = name;
1212     if(containsOption) {
1213         stackPieces.cnvName[0] = 0;
1214         stackPieces.locale[0] = 0;
1215         stackPieces.options = 0;
1216         parseConverterOptions(name, &stackPieces, &stackArgs, status);
1217         if(U_FAILURE(*status)) {
1218             return;
1219         }
1220     }
1221     algorithmicSharedData = getAlgorithmicTypeFromName(stackArgs.name);
1222
1223     umtx_lock(&cnvCacheMutex);
1224
1225     gDefaultAlgorithmicSharedData = algorithmicSharedData;
1226     gDefaultConverterContainsOption = containsOption;
1227     uprv_memcpy(gDefaultConverterNameBuffer, name, length);
1228     gDefaultConverterNameBuffer[length]=0;
1229
1230     /* gDefaultConverterName MUST be the last global var set by this function.  */
1231     /*    It is the variable checked in ucnv_getDefaultName() to see if initialization is required. */
1232     //    But there is nothing here preventing that from being reordered, either by the compiler
1233     //             or hardware. I'm adding the mutex to ucnv_getDefaultName for now. UMTX_CHECK is not enough.
1234     //             -- Andy
1235     gDefaultConverterName = gDefaultConverterNameBuffer;
1236
1237     ucln_common_registerCleanup(UCLN_COMMON_UCNV, ucnv_cleanup);
1238
1239     umtx_unlock(&cnvCacheMutex);
1240 }
1241 #endif
1242
1243 /*
1244  * In order to be really thread-safe, the get function would have to take
1245  * a buffer parameter and copy the current string inside a mutex block.
1246  * This implementation only tries to be really thread-safe while
1247  * setting the name.
1248  * It assumes that setting a pointer is atomic.
1249  */
1250
1251 U_CAPI const char*  U_EXPORT2
1252 ucnv_getDefaultName() {
1253 #if U_CHARSET_IS_UTF8
1254     return "UTF-8";
1255 #else
1256     /* local variable to be thread-safe */
1257     const char *name;
1258
1259     /*
1260     Concurrent calls to ucnv_getDefaultName must be thread safe,
1261     but ucnv_setDefaultName is not thread safe.
1262     */
1263     {
1264         icu::Mutex lock(&cnvCacheMutex);
1265         name = gDefaultConverterName;
1266     }
1267     if(name==NULL) {
1268         UErrorCode errorCode = U_ZERO_ERROR;
1269         UConverter *cnv = NULL;
1270
1271         name = uprv_getDefaultCodepage();
1272
1273         /* if the name is there, test it out and get the canonical name with options */
1274         if(name != NULL) {
1275             cnv = ucnv_open(name, &errorCode);
1276             if(U_SUCCESS(errorCode) && cnv != NULL) {
1277                 name = ucnv_getName(cnv, &errorCode);
1278             }
1279         }
1280
1281         if(name == NULL || name[0] == 0
1282             || U_FAILURE(errorCode) || cnv == NULL
1283             || uprv_strlen(name)>=sizeof(gDefaultConverterNameBuffer))
1284         {
1285             /* Panic time, let's use a fallback. */
1286 #if (U_CHARSET_FAMILY == U_ASCII_FAMILY)
1287             name = "US-ASCII";
1288             /* there is no 'algorithmic' converter for EBCDIC */
1289 #elif U_PLATFORM == U_PF_OS390
1290             name = "ibm-1047_P100-1995" UCNV_SWAP_LFNL_OPTION_STRING;
1291 #else
1292             name = "ibm-37_P100-1995";
1293 #endif
1294         }
1295
1296         internalSetName(name, &errorCode);
1297
1298         /* The close may make the current name go away. */
1299         ucnv_close(cnv);
1300     }
1301
1302     return name;
1303 #endif
1304 }
1305
1306 #if U_CHARSET_IS_UTF8
1307 U_CAPI void U_EXPORT2 ucnv_setDefaultName(const char *) {}
1308 #else
1309 /*
1310 This function is not thread safe, and it can't be thread safe.
1311 See internalSetName or the API reference for details.
1312 */
1313 U_CAPI void U_EXPORT2
1314 ucnv_setDefaultName(const char *converterName) {
1315     if(converterName==NULL) {
1316         /* reset to the default codepage */
1317         gDefaultConverterName=NULL;
1318     } else {
1319         UErrorCode errorCode = U_ZERO_ERROR;
1320         UConverter *cnv = NULL;
1321         const char *name = NULL;
1322
1323         /* if the name is there, test it out and get the canonical name with options */
1324         cnv = ucnv_open(converterName, &errorCode);
1325         if(U_SUCCESS(errorCode) && cnv != NULL) {
1326             name = ucnv_getName(cnv, &errorCode);
1327         }
1328
1329         if(U_SUCCESS(errorCode) && name!=NULL) {
1330             internalSetName(name, &errorCode);
1331         }
1332         /* else this converter is bad to use. Don't change it to a bad value. */
1333
1334         /* The close may make the current name go away. */
1335         ucnv_close(cnv);
1336   
1337         /* reset the converter cache */
1338         u_flushDefaultConverter();
1339     }
1340 }
1341 #endif
1342
1343 /* data swapping ------------------------------------------------------------ */
1344
1345 /* most of this might belong more properly into ucnvmbcs.c, but that is so large */
1346
1347 #if !UCONFIG_NO_LEGACY_CONVERSION
1348
1349 U_CAPI int32_t U_EXPORT2
1350 ucnv_swap(const UDataSwapper *ds,
1351           const void *inData, int32_t length, void *outData,
1352           UErrorCode *pErrorCode) {
1353     const UDataInfo *pInfo;
1354     int32_t headerSize;
1355
1356     const uint8_t *inBytes;
1357     uint8_t *outBytes;
1358
1359     uint32_t offset, count, staticDataSize;
1360     int32_t size;
1361
1362     const UConverterStaticData *inStaticData;
1363     UConverterStaticData *outStaticData;
1364
1365     const _MBCSHeader *inMBCSHeader;
1366     _MBCSHeader *outMBCSHeader;
1367     _MBCSHeader mbcsHeader;
1368     uint32_t mbcsHeaderLength;
1369     UBool noFromU=FALSE;
1370
1371     uint8_t outputType;
1372
1373     int32_t maxFastUChar, mbcsIndexLength;
1374
1375     const int32_t *inExtIndexes;
1376     int32_t extOffset;
1377
1378     /* udata_swapDataHeader checks the arguments */
1379     headerSize=udata_swapDataHeader(ds, inData, length, outData, pErrorCode);
1380     if(pErrorCode==NULL || U_FAILURE(*pErrorCode)) {
1381         return 0;
1382     }
1383
1384     /* check data format and format version */
1385     pInfo=(const UDataInfo *)((const char *)inData+4);
1386     if(!(
1387         pInfo->dataFormat[0]==0x63 &&   /* dataFormat="cnvt" */
1388         pInfo->dataFormat[1]==0x6e &&
1389         pInfo->dataFormat[2]==0x76 &&
1390         pInfo->dataFormat[3]==0x74 &&
1391         pInfo->formatVersion[0]==6 &&
1392         pInfo->formatVersion[1]>=2
1393     )) {
1394         udata_printError(ds, "ucnv_swap(): data format %02x.%02x.%02x.%02x (format version %02x.%02x) is not recognized as an ICU .cnv conversion table\n",
1395                          pInfo->dataFormat[0], pInfo->dataFormat[1],
1396                          pInfo->dataFormat[2], pInfo->dataFormat[3],
1397                          pInfo->formatVersion[0], pInfo->formatVersion[1]);
1398         *pErrorCode=U_UNSUPPORTED_ERROR;
1399         return 0;
1400     }
1401
1402     inBytes=(const uint8_t *)inData+headerSize;
1403     outBytes=(uint8_t *)outData+headerSize;
1404
1405     /* read the initial UConverterStaticData structure after the UDataInfo header */
1406     inStaticData=(const UConverterStaticData *)inBytes;
1407     outStaticData=(UConverterStaticData *)outBytes;
1408
1409     if(length<0) {
1410         staticDataSize=ds->readUInt32(inStaticData->structSize);
1411     } else {
1412         length-=headerSize;
1413         if( length<(int32_t)sizeof(UConverterStaticData) ||
1414             (uint32_t)length<(staticDataSize=ds->readUInt32(inStaticData->structSize))
1415         ) {
1416             udata_printError(ds, "ucnv_swap(): too few bytes (%d after header) for an ICU .cnv conversion table\n",
1417                              length);
1418             *pErrorCode=U_INDEX_OUTOFBOUNDS_ERROR;
1419             return 0;
1420         }
1421     }
1422
1423     if(length>=0) {
1424         /* swap the static data */
1425         if(inStaticData!=outStaticData) {
1426             uprv_memcpy(outStaticData, inStaticData, staticDataSize);
1427         }
1428
1429         ds->swapArray32(ds, &inStaticData->structSize, 4,
1430                            &outStaticData->structSize, pErrorCode);
1431         ds->swapArray32(ds, &inStaticData->codepage, 4,
1432                            &outStaticData->codepage, pErrorCode);
1433
1434         ds->swapInvChars(ds, inStaticData->name, (int32_t)uprv_strlen(inStaticData->name),
1435                             outStaticData->name, pErrorCode);
1436         if(U_FAILURE(*pErrorCode)) {
1437             udata_printError(ds, "ucnv_swap(): error swapping converter name\n");
1438             return 0;
1439         }
1440     }
1441
1442     inBytes+=staticDataSize;
1443     outBytes+=staticDataSize;
1444     if(length>=0) {
1445         length-=(int32_t)staticDataSize;
1446     }
1447
1448     /* check for supported conversionType values */
1449     if(inStaticData->conversionType==UCNV_MBCS) {
1450         /* swap MBCS data */
1451         inMBCSHeader=(const _MBCSHeader *)inBytes;
1452         outMBCSHeader=(_MBCSHeader *)outBytes;
1453
1454         if(0<=length && length<(int32_t)sizeof(_MBCSHeader)) {
1455             udata_printError(ds, "ucnv_swap(): too few bytes (%d after headers) for an ICU MBCS .cnv conversion table\n",
1456                                 length);
1457             *pErrorCode=U_INDEX_OUTOFBOUNDS_ERROR;
1458             return 0;
1459         }
1460         if(inMBCSHeader->version[0]==4 && inMBCSHeader->version[1]>=1) {
1461             mbcsHeaderLength=MBCS_HEADER_V4_LENGTH;
1462         } else if(inMBCSHeader->version[0]==5 && inMBCSHeader->version[1]>=3 &&
1463                   ((mbcsHeader.options=ds->readUInt32(inMBCSHeader->options))&
1464                    MBCS_OPT_UNKNOWN_INCOMPATIBLE_MASK)==0
1465         ) {
1466             mbcsHeaderLength=mbcsHeader.options&MBCS_OPT_LENGTH_MASK;
1467             noFromU=(UBool)((mbcsHeader.options&MBCS_OPT_NO_FROM_U)!=0);
1468         } else {
1469             udata_printError(ds, "ucnv_swap(): unsupported _MBCSHeader.version %d.%d\n",
1470                              inMBCSHeader->version[0], inMBCSHeader->version[1]);
1471             *pErrorCode=U_UNSUPPORTED_ERROR;
1472             return 0;
1473         }
1474
1475         uprv_memcpy(mbcsHeader.version, inMBCSHeader->version, 4);
1476         mbcsHeader.countStates=         ds->readUInt32(inMBCSHeader->countStates);
1477         mbcsHeader.countToUFallbacks=   ds->readUInt32(inMBCSHeader->countToUFallbacks);
1478         mbcsHeader.offsetToUCodeUnits=  ds->readUInt32(inMBCSHeader->offsetToUCodeUnits);
1479         mbcsHeader.offsetFromUTable=    ds->readUInt32(inMBCSHeader->offsetFromUTable);
1480         mbcsHeader.offsetFromUBytes=    ds->readUInt32(inMBCSHeader->offsetFromUBytes);
1481         mbcsHeader.flags=               ds->readUInt32(inMBCSHeader->flags);
1482         mbcsHeader.fromUBytesLength=    ds->readUInt32(inMBCSHeader->fromUBytesLength);
1483         /* mbcsHeader.options have been read above */
1484
1485         extOffset=(int32_t)(mbcsHeader.flags>>8);
1486         outputType=(uint8_t)mbcsHeader.flags;
1487         if(noFromU && outputType==MBCS_OUTPUT_1) {
1488             udata_printError(ds, "ucnv_swap(): unsupported combination of makeconv --small with SBCS\n");
1489             *pErrorCode=U_UNSUPPORTED_ERROR;
1490             return 0;
1491         }
1492
1493         /* make sure that the output type is known */
1494         switch(outputType) {
1495         case MBCS_OUTPUT_1:
1496         case MBCS_OUTPUT_2:
1497         case MBCS_OUTPUT_3:
1498         case MBCS_OUTPUT_4:
1499         case MBCS_OUTPUT_3_EUC:
1500         case MBCS_OUTPUT_4_EUC:
1501         case MBCS_OUTPUT_2_SISO:
1502         case MBCS_OUTPUT_EXT_ONLY:
1503             /* OK */
1504             break;
1505         default:
1506             udata_printError(ds, "ucnv_swap(): unsupported MBCS output type 0x%x\n",
1507                              outputType);
1508             *pErrorCode=U_UNSUPPORTED_ERROR;
1509             return 0;
1510         }
1511
1512         /* calculate the length of the MBCS data */
1513
1514         /*
1515          * utf8Friendly MBCS files (mbcsHeader.version 4.3)
1516          * contain an additional mbcsIndex table:
1517          *   uint16_t[(maxFastUChar+1)>>6];
1518          * where maxFastUChar=((mbcsHeader.version[2]<<8)|0xff).
1519          */
1520         maxFastUChar=0;
1521         mbcsIndexLength=0;
1522         if( outputType!=MBCS_OUTPUT_EXT_ONLY && outputType!=MBCS_OUTPUT_1 &&
1523             mbcsHeader.version[1]>=3 && (maxFastUChar=mbcsHeader.version[2])!=0
1524         ) {
1525             maxFastUChar=(maxFastUChar<<8)|0xff;
1526             mbcsIndexLength=((maxFastUChar+1)>>6)*2;  /* number of bytes */
1527         }
1528
1529         if(extOffset==0) {
1530             size=(int32_t)(mbcsHeader.offsetFromUBytes+mbcsIndexLength);
1531             if(!noFromU) {
1532                 size+=(int32_t)mbcsHeader.fromUBytesLength;
1533             }
1534
1535             /* avoid compiler warnings - not otherwise necessary, and the value does not matter */
1536             inExtIndexes=NULL;
1537         } else {
1538             /* there is extension data after the base data, see ucnv_ext.h */
1539             if(length>=0 && length<(extOffset+UCNV_EXT_INDEXES_MIN_LENGTH*4)) {
1540                 udata_printError(ds, "ucnv_swap(): too few bytes (%d after headers) for an ICU MBCS .cnv conversion table with extension data\n",
1541                                  length);
1542                 *pErrorCode=U_INDEX_OUTOFBOUNDS_ERROR;
1543                 return 0;
1544             }
1545
1546             inExtIndexes=(const int32_t *)(inBytes+extOffset);
1547             size=extOffset+udata_readInt32(ds, inExtIndexes[UCNV_EXT_SIZE]);
1548         }
1549
1550         if(length>=0) {
1551             if(length<size) {
1552                 udata_printError(ds, "ucnv_swap(): too few bytes (%d after headers) for an ICU MBCS .cnv conversion table\n",
1553                                  length);
1554                 *pErrorCode=U_INDEX_OUTOFBOUNDS_ERROR;
1555                 return 0;
1556             }
1557
1558             /* copy the data for inaccessible bytes */
1559             if(inBytes!=outBytes) {
1560                 uprv_memcpy(outBytes, inBytes, size);
1561             }
1562
1563             /* swap the MBCSHeader, except for the version field */
1564             count=mbcsHeaderLength*4;
1565             ds->swapArray32(ds, &inMBCSHeader->countStates, count-4,
1566                                &outMBCSHeader->countStates, pErrorCode);
1567
1568             if(outputType==MBCS_OUTPUT_EXT_ONLY) {
1569                 /*
1570                  * extension-only file,
1571                  * contains a base name instead of normal base table data
1572                  */
1573
1574                 /* swap the base name, between the header and the extension data */
1575                 const char *inBaseName=(const char *)inBytes+count;
1576                 char *outBaseName=(char *)outBytes+count;
1577                 ds->swapInvChars(ds, inBaseName, (int32_t)uprv_strlen(inBaseName),
1578                                     outBaseName, pErrorCode);
1579             } else {
1580                 /* normal file with base table data */
1581
1582                 /* swap the state table, 1kB per state */
1583                 offset=count;
1584                 count=mbcsHeader.countStates*1024;
1585                 ds->swapArray32(ds, inBytes+offset, (int32_t)count,
1586                                    outBytes+offset, pErrorCode);
1587
1588                 /* swap the toUFallbacks[] */
1589                 offset+=count;
1590                 count=mbcsHeader.countToUFallbacks*8;
1591                 ds->swapArray32(ds, inBytes+offset, (int32_t)count,
1592                                    outBytes+offset, pErrorCode);
1593
1594                 /* swap the unicodeCodeUnits[] */
1595                 offset=mbcsHeader.offsetToUCodeUnits;
1596                 count=mbcsHeader.offsetFromUTable-offset;
1597                 ds->swapArray16(ds, inBytes+offset, (int32_t)count,
1598                                    outBytes+offset, pErrorCode);
1599
1600                 /* offset to the stage 1 table, independent of the outputType */
1601                 offset=mbcsHeader.offsetFromUTable;
1602
1603                 if(outputType==MBCS_OUTPUT_1) {
1604                     /* SBCS: swap the fromU tables, all 16 bits wide */
1605                     count=(mbcsHeader.offsetFromUBytes-offset)+mbcsHeader.fromUBytesLength;
1606                     ds->swapArray16(ds, inBytes+offset, (int32_t)count,
1607                                        outBytes+offset, pErrorCode);
1608                 } else {
1609                     /* otherwise: swap the stage tables separately */
1610
1611                     /* stage 1 table: uint16_t[0x440 or 0x40] */
1612                     if(inStaticData->unicodeMask&UCNV_HAS_SUPPLEMENTARY) {
1613                         count=0x440*2; /* for all of Unicode */
1614                     } else {
1615                         count=0x40*2; /* only BMP */
1616                     }
1617                     ds->swapArray16(ds, inBytes+offset, (int32_t)count,
1618                                        outBytes+offset, pErrorCode);
1619
1620                     /* stage 2 table: uint32_t[] */
1621                     offset+=count;
1622                     count=mbcsHeader.offsetFromUBytes-offset;
1623                     ds->swapArray32(ds, inBytes+offset, (int32_t)count,
1624                                        outBytes+offset, pErrorCode);
1625
1626                     /* stage 3/result bytes: sometimes uint16_t[] or uint32_t[] */
1627                     offset=mbcsHeader.offsetFromUBytes;
1628                     count= noFromU ? 0 : mbcsHeader.fromUBytesLength;
1629                     switch(outputType) {
1630                     case MBCS_OUTPUT_2:
1631                     case MBCS_OUTPUT_3_EUC:
1632                     case MBCS_OUTPUT_2_SISO:
1633                         ds->swapArray16(ds, inBytes+offset, (int32_t)count,
1634                                            outBytes+offset, pErrorCode);
1635                         break;
1636                     case MBCS_OUTPUT_4:
1637                         ds->swapArray32(ds, inBytes+offset, (int32_t)count,
1638                                            outBytes+offset, pErrorCode);
1639                         break;
1640                     default:
1641                         /* just uint8_t[], nothing to swap */
1642                         break;
1643                     }
1644
1645                     if(mbcsIndexLength!=0) {
1646                         offset+=count;
1647                         count=mbcsIndexLength;
1648                         ds->swapArray16(ds, inBytes+offset, (int32_t)count,
1649                                            outBytes+offset, pErrorCode);
1650                     }
1651                 }
1652             }
1653
1654             if(extOffset!=0) {
1655                 /* swap the extension data */
1656                 inBytes+=extOffset;
1657                 outBytes+=extOffset;
1658
1659                 /* swap toUTable[] */
1660                 offset=udata_readInt32(ds, inExtIndexes[UCNV_EXT_TO_U_INDEX]);
1661                 length=udata_readInt32(ds, inExtIndexes[UCNV_EXT_TO_U_LENGTH]);
1662                 ds->swapArray32(ds, inBytes+offset, length*4, outBytes+offset, pErrorCode);
1663
1664                 /* swap toUUChars[] */
1665                 offset=udata_readInt32(ds, inExtIndexes[UCNV_EXT_TO_U_UCHARS_INDEX]);
1666                 length=udata_readInt32(ds, inExtIndexes[UCNV_EXT_TO_U_UCHARS_LENGTH]);
1667                 ds->swapArray16(ds, inBytes+offset, length*2, outBytes+offset, pErrorCode);
1668
1669                 /* swap fromUTableUChars[] */
1670                 offset=udata_readInt32(ds, inExtIndexes[UCNV_EXT_FROM_U_UCHARS_INDEX]);
1671                 length=udata_readInt32(ds, inExtIndexes[UCNV_EXT_FROM_U_LENGTH]);
1672                 ds->swapArray16(ds, inBytes+offset, length*2, outBytes+offset, pErrorCode);
1673
1674                 /* swap fromUTableValues[] */
1675                 offset=udata_readInt32(ds, inExtIndexes[UCNV_EXT_FROM_U_VALUES_INDEX]);
1676                 /* same length as for fromUTableUChars[] */
1677                 ds->swapArray32(ds, inBytes+offset, length*4, outBytes+offset, pErrorCode);
1678
1679                 /* no need to swap fromUBytes[] */
1680
1681                 /* swap fromUStage12[] */
1682                 offset=udata_readInt32(ds, inExtIndexes[UCNV_EXT_FROM_U_STAGE_12_INDEX]);
1683                 length=udata_readInt32(ds, inExtIndexes[UCNV_EXT_FROM_U_STAGE_12_LENGTH]);
1684                 ds->swapArray16(ds, inBytes+offset, length*2, outBytes+offset, pErrorCode);
1685
1686                 /* swap fromUStage3[] */
1687                 offset=udata_readInt32(ds, inExtIndexes[UCNV_EXT_FROM_U_STAGE_3_INDEX]);
1688                 length=udata_readInt32(ds, inExtIndexes[UCNV_EXT_FROM_U_STAGE_3_LENGTH]);
1689                 ds->swapArray16(ds, inBytes+offset, length*2, outBytes+offset, pErrorCode);
1690
1691                 /* swap fromUStage3b[] */
1692                 offset=udata_readInt32(ds, inExtIndexes[UCNV_EXT_FROM_U_STAGE_3B_INDEX]);
1693                 length=udata_readInt32(ds, inExtIndexes[UCNV_EXT_FROM_U_STAGE_3B_LENGTH]);
1694                 ds->swapArray32(ds, inBytes+offset, length*4, outBytes+offset, pErrorCode);
1695
1696                 /* swap indexes[] */
1697                 length=udata_readInt32(ds, inExtIndexes[UCNV_EXT_INDEXES_LENGTH]);
1698                 ds->swapArray32(ds, inBytes, length*4, outBytes, pErrorCode);
1699             }
1700         }
1701     } else {
1702         udata_printError(ds, "ucnv_swap(): unknown conversionType=%d!=UCNV_MBCS\n",
1703                          inStaticData->conversionType);
1704         *pErrorCode=U_UNSUPPORTED_ERROR;
1705         return 0;
1706     }
1707
1708     return headerSize+(int32_t)staticDataSize+size;
1709 }
1710
1711 #endif /* #if !UCONFIG_NO_LEGACY_CONVERSION */
1712
1713 #endif