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