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