]> git.saurik.com Git - apple/icu.git/blame - icuSources/common/udata.cpp
ICU-64260.0.1.tar.gz
[apple/icu.git] / icuSources / common / udata.cpp
CommitLineData
f3c0d7a5
A
1// © 2016 and later: Unicode, Inc. and others.
2// License & terms of use: http://www.unicode.org/copyright.html
b75a7d8f
A
3/*
4******************************************************************************
5*
2ca993e8 6* Copyright (C) 1999-2016, International Business Machines
b75a7d8f
A
7* Corporation and others. All Rights Reserved.
8*
9******************************************************************************
729e4ab9 10* file name: udata.cpp
f3c0d7a5 11* encoding: UTF-8
b75a7d8f
A
12* tab size: 8 (not used)
13* indentation:4
14*
15* created on: 1999oct25
16* created by: Markus W. Scherer
17*/
18
4388f060 19#include "unicode/utypes.h" /* U_PLATFORM etc. */
729e4ab9 20
4388f060 21#ifdef __GNUC__
729e4ab9
A
22/* if gcc
23#define ATTRIBUTE_WEAK __attribute__ ((weak))
24might have to #include some other header
25*/
26#endif
27
b75a7d8f 28#include "unicode/putil.h"
b75a7d8f
A
29#include "unicode/udata.h"
30#include "unicode/uversion.h"
729e4ab9
A
31#include "charstr.h"
32#include "cmemory.h"
33#include "cstring.h"
2ca993e8 34#include "mutex.h"
374ca955 35#include "putilimp.h"
57a6839d 36#include "uassert.h"
729e4ab9
A
37#include "ucln_cmn.h"
38#include "ucmndata.h"
b75a7d8f 39#include "udatamem.h"
729e4ab9 40#include "uhash.h"
b75a7d8f 41#include "umapfile.h"
729e4ab9 42#include "umutex.h"
b75a7d8f
A
43
44/***********************************************************************
45*
46* Notes on the organization of the ICU data implementation
47*
48* All of the public API is defined in udata.h
49*
50* The implementation is split into several files...
51*
52* - udata.c (this file) contains higher level code that knows about
53* the search paths for locating data, caching opened data, etc.
54*
55* - umapfile.c contains the low level platform-specific code for actually loading
56* (memory mapping, file reading, whatever) data into memory.
57*
58* - ucmndata.c deals with the tables of contents of ICU data items within
59* an ICU common format data file. The implementation includes
60* an abstract interface and support for multiple TOC formats.
61* All knowledge of any specific TOC format is encapsulated here.
62*
63* - udatamem.c has code for managing UDataMemory structs. These are little
64* descriptor objects for blocks of memory holding ICU data of
65* various types.
66*/
67
68/* configuration ---------------------------------------------------------- */
69
70/* If you are excruciatingly bored turn this on .. */
71/* #define UDATA_DEBUG 1 */
2ca993e8
A
72/* For debugging use of timezone data in a separate file */
73/* #define UDATA_TZFILES_DEBUG 1 */
b75a7d8f 74
2ca993e8 75#if defined(UDATA_DEBUG) || defined(UDATA_TZFILES_DEBUG)
b75a7d8f
A
76# include <stdio.h>
77#endif
78
729e4ab9
A
79U_NAMESPACE_USE
80
81/*
4388f060 82 * Forward declarations
729e4ab9 83 */
f3c0d7a5 84static UDataMemory *udata_findCachedData(const char *path, UErrorCode &err);
b75a7d8f
A
85
86/***********************************************************************
87*
88* static (Global) data
89*
90************************************************************************/
b75a7d8f 91
729e4ab9
A
92/*
93 * Pointers to the common ICU data.
94 *
95 * We store multiple pointers to ICU data packages and iterate through them
96 * when looking for a data item.
97 *
98 * It is possible to combine this with dependency inversion:
99 * One or more data package libraries may export
100 * functions that each return a pointer to their piece of the ICU data,
101 * and this file would import them as weak functions, without a
102 * strong linker dependency from the common library on the data library.
103 *
104 * Then we can have applications depend on only that part of ICU's data
105 * that they really need, reducing the size of binaries that take advantage
106 * of this.
107 */
2ca993e8 108static UDataMemory *gCommonICUDataArray[10] = { NULL }; // Access protected by icu global mutex.
729e4ab9 109
2ca993e8 110static u_atomic_int32_t gHaveTriedToLoadCommonData = ATOMIC_INT32_T_INITIALIZER(0); // See extendICUData().
b75a7d8f
A
111
112static UHashtable *gCommonDataCache = NULL; /* Global hash table of opened ICU data files. */
57a6839d 113static icu::UInitOnce gCommonDataCacheInitOnce = U_INITONCE_INITIALIZER;
b75a7d8f 114
f3c0d7a5 115#if U_PLATFORM_HAS_WINUWP_API == 0
2ca993e8
A
116static UDataFileAccess gDataFileAccess = UDATA_DEFAULT_ACCESS; // Access not synchronized.
117 // Modifying is documented as thread-unsafe.
f3c0d7a5
A
118#else
119static UDataFileAccess gDataFileAccess = UDATA_NO_FILES; // Windows UWP looks in one spot explicitly
120#endif
b75a7d8f 121
374ca955
A
122static UBool U_CALLCONV
123udata_cleanup(void)
b75a7d8f 124{
729e4ab9
A
125 int32_t i;
126
b75a7d8f
A
127 if (gCommonDataCache) { /* Delete the cache of user data mappings. */
128 uhash_close(gCommonDataCache); /* Table owns the contents, and will delete them. */
129 gCommonDataCache = NULL; /* Cleanup is not thread safe. */
130 }
57a6839d 131 gCommonDataCacheInitOnce.reset();
b75a7d8f 132
b331163b 133 for (i = 0; i < UPRV_LENGTHOF(gCommonICUDataArray) && gCommonICUDataArray[i] != NULL; ++i) {
729e4ab9
A
134 udata_close(gCommonICUDataArray[i]);
135 gCommonICUDataArray[i] = NULL;
b75a7d8f 136 }
2ca993e8 137 gHaveTriedToLoadCommonData = 0;
b75a7d8f
A
138
139 return TRUE; /* Everything was cleaned up */
140}
141
729e4ab9 142static UBool U_CALLCONV
f3c0d7a5 143findCommonICUDataByName(const char *inBasename, UErrorCode &err)
729e4ab9
A
144{
145 UBool found = FALSE;
146 int32_t i;
147
f3c0d7a5
A
148 UDataMemory *pData = udata_findCachedData(inBasename, err);
149 if (U_FAILURE(err) || pData == NULL)
729e4ab9
A
150 return FALSE;
151
2ca993e8
A
152 {
153 Mutex lock;
154 for (i = 0; i < UPRV_LENGTHOF(gCommonICUDataArray); ++i) {
155 if ((gCommonICUDataArray[i] != NULL) && (gCommonICUDataArray[i]->pHeader == pData->pHeader)) {
156 /* The data pointer is already in the array. */
157 found = TRUE;
158 break;
159 }
729e4ab9
A
160 }
161 }
729e4ab9
A
162 return found;
163}
b75a7d8f
A
164
165
166/*
167 * setCommonICUData. Set a UDataMemory to be the global ICU Data
168 */
729e4ab9 169static UBool
b75a7d8f 170setCommonICUData(UDataMemory *pData, /* The new common data. Belongs to caller, we copy it. */
b75a7d8f
A
171 UBool warn, /* If true, set USING_DEFAULT warning if ICUData was */
172 /* changed by another thread before we got to it. */
173 UErrorCode *pErr)
174{
175 UDataMemory *newCommonData = UDataMemory_createNewInstance(pErr);
729e4ab9
A
176 int32_t i;
177 UBool didUpdate = FALSE;
b75a7d8f 178 if (U_FAILURE(*pErr)) {
729e4ab9 179 return FALSE;
b75a7d8f
A
180 }
181
182 /* For the assignment, other threads must cleanly see either the old */
183 /* or the new, not some partially initialized new. The old can not be */
184 /* deleted - someone may still have a pointer to it lying around in */
185 /* their locals. */
186 UDatamemory_assign(newCommonData, pData);
187 umtx_lock(NULL);
b331163b 188 for (i = 0; i < UPRV_LENGTHOF(gCommonICUDataArray); ++i) {
729e4ab9
A
189 if (gCommonICUDataArray[i] == NULL) {
190 gCommonICUDataArray[i] = newCommonData;
729e4ab9
A
191 didUpdate = TRUE;
192 break;
193 } else if (gCommonICUDataArray[i]->pHeader == pData->pHeader) {
194 /* The same data pointer is already in the array. */
195 break;
b75a7d8f 196 }
b75a7d8f
A
197 }
198 umtx_unlock(NULL);
729e4ab9 199
b331163b 200 if (i == UPRV_LENGTHOF(gCommonICUDataArray) && warn) {
729e4ab9
A
201 *pErr = U_USING_DEFAULT_WARNING;
202 }
b331163b
A
203 if (didUpdate) {
204 ucln_common_registerCleanup(UCLN_COMMON_UDATA, udata_cleanup);
205 } else {
729e4ab9
A
206 uprv_free(newCommonData);
207 }
208 return didUpdate;
209}
210
0f5d89e8
A
211#if U_PLATFORM_HAS_WINUWP_API == 0
212
729e4ab9
A
213static UBool
214setCommonICUDataPointer(const void *pData, UBool /*warn*/, UErrorCode *pErrorCode) {
215 UDataMemory tData;
216 UDataMemory_init(&tData);
57a6839d 217 UDataMemory_setData(&tData, pData);
729e4ab9
A
218 udata_checkCommonData(&tData, pErrorCode);
219 return setCommonICUData(&tData, FALSE, pErrorCode);
b75a7d8f
A
220}
221
0f5d89e8
A
222#endif
223
b75a7d8f
A
224static const char *
225findBasename(const char *path) {
226 const char *basename=uprv_strrchr(path, U_FILE_SEP_CHAR);
227 if(basename==NULL) {
228 return path;
229 } else {
230 return basename+1;
231 }
232}
233
374ca955 234#ifdef UDATA_DEBUG
b75a7d8f
A
235static const char *
236packageNameFromPath(const char *path)
237{
238 if((path == NULL) || (*path == 0)) {
239 return U_ICUDATA_NAME;
240 }
241
242 path = findBasename(path);
243
244 if((path == NULL) || (*path == 0)) {
245 return U_ICUDATA_NAME;
246 }
247
248 return path;
249}
374ca955 250#endif
b75a7d8f
A
251
252/*----------------------------------------------------------------------*
253 * *
254 * Cache for common data *
255 * Functions for looking up or adding entries to a cache of *
256 * data that has been previously opened. Avoids a potentially *
257 * expensive operation of re-opening the data for subsequent *
258 * uses. *
259 * *
260 * Data remains cached for the duration of the process. *
261 * *
262 *----------------------------------------------------------------------*/
263
264typedef struct DataCacheElement {
265 char *name;
266 UDataMemory *item;
267} DataCacheElement;
268
269
270
271/*
272 * Deleter function for DataCacheElements.
273 * udata cleanup function closes the hash table; hash table in turn calls back to
274 * here for each entry.
275 */
73c04bcf 276static void U_CALLCONV DataCacheElement_deleter(void *pDCEl) {
b75a7d8f
A
277 DataCacheElement *p = (DataCacheElement *)pDCEl;
278 udata_close(p->item); /* unmaps storage */
279 uprv_free(p->name); /* delete the hash key string. */
280 uprv_free(pDCEl); /* delete 'this' */
281}
282
f3c0d7a5 283static void U_CALLCONV udata_initHashTable(UErrorCode &err) {
57a6839d
A
284 U_ASSERT(gCommonDataCache == NULL);
285 gCommonDataCache = uhash_open(uhash_hashChars, uhash_compareChars, NULL, &err);
286 if (U_FAILURE(err)) {
f3c0d7a5 287 return;
b75a7d8f 288 }
f3c0d7a5
A
289 U_ASSERT(gCommonDataCache != NULL);
290 uhash_setValueDeleter(gCommonDataCache, DataCacheElement_deleter);
291 ucln_common_registerCleanup(UCLN_COMMON_UDATA, udata_cleanup);
57a6839d 292}
b75a7d8f 293
57a6839d
A
294 /* udata_getCacheHashTable()
295 * Get the hash table used to store the data cache entries.
296 * Lazy create it if it doesn't yet exist.
297 */
f3c0d7a5
A
298static UHashtable *udata_getHashTable(UErrorCode &err) {
299 umtx_initOnce(gCommonDataCacheInitOnce, &udata_initHashTable, err);
b75a7d8f
A
300 return gCommonDataCache;
301}
302
303
304
f3c0d7a5 305static UDataMemory *udata_findCachedData(const char *path, UErrorCode &err)
b75a7d8f
A
306{
307 UHashtable *htable;
308 UDataMemory *retVal = NULL;
309 DataCacheElement *el;
310 const char *baseName;
311
f3c0d7a5
A
312 htable = udata_getHashTable(err);
313 if (U_FAILURE(err)) {
314 return NULL;
315 }
316
b75a7d8f 317 baseName = findBasename(path); /* Cache remembers only the base name, not the full path. */
b75a7d8f
A
318 umtx_lock(NULL);
319 el = (DataCacheElement *)uhash_get(htable, baseName);
320 umtx_unlock(NULL);
321 if (el != NULL) {
322 retVal = el->item;
323 }
324#ifdef UDATA_DEBUG
325 fprintf(stderr, "Cache: [%s] -> %p\n", baseName, retVal);
326#endif
327 return retVal;
328}
329
330
331static UDataMemory *udata_cacheDataItem(const char *path, UDataMemory *item, UErrorCode *pErr) {
332 DataCacheElement *newElement;
333 const char *baseName;
334 int32_t nameLen;
335 UHashtable *htable;
729e4ab9 336 DataCacheElement *oldValue = NULL;
374ca955 337 UErrorCode subErr = U_ZERO_ERROR;
b75a7d8f 338
f3c0d7a5 339 htable = udata_getHashTable(*pErr);
b75a7d8f
A
340 if (U_FAILURE(*pErr)) {
341 return NULL;
342 }
343
344 /* Create a new DataCacheElement - the thingy we store in the hash table -
345 * and copy the supplied path and UDataMemoryItems into it.
346 */
729e4ab9 347 newElement = (DataCacheElement *)uprv_malloc(sizeof(DataCacheElement));
b75a7d8f
A
348 if (newElement == NULL) {
349 *pErr = U_MEMORY_ALLOCATION_ERROR;
350 return NULL;
351 }
352 newElement->item = UDataMemory_createNewInstance(pErr);
353 if (U_FAILURE(*pErr)) {
73c04bcf 354 uprv_free(newElement);
b75a7d8f
A
355 return NULL;
356 }
357 UDatamemory_assign(newElement->item, item);
358
359 baseName = findBasename(path);
360 nameLen = (int32_t)uprv_strlen(baseName);
729e4ab9 361 newElement->name = (char *)uprv_malloc(nameLen+1);
b75a7d8f
A
362 if (newElement->name == NULL) {
363 *pErr = U_MEMORY_ALLOCATION_ERROR;
73c04bcf
A
364 uprv_free(newElement->item);
365 uprv_free(newElement);
b75a7d8f
A
366 return NULL;
367 }
368 uprv_strcpy(newElement->name, baseName);
369
370 /* Stick the new DataCacheElement into the hash table.
371 */
b75a7d8f 372 umtx_lock(NULL);
729e4ab9 373 oldValue = (DataCacheElement *)uhash_get(htable, path);
b75a7d8f 374 if (oldValue != NULL) {
374ca955
A
375 subErr = U_USING_DEFAULT_WARNING;
376 }
b75a7d8f
A
377 else {
378 uhash_put(
379 htable,
380 newElement->name, /* Key */
381 newElement, /* Value */
374ca955 382 &subErr);
b75a7d8f
A
383 }
384 umtx_unlock(NULL);
385
386#ifdef UDATA_DEBUG
374ca955
A
387 fprintf(stderr, "Cache: [%s] <<< %p : %s. vFunc=%p\n", newElement->name,
388 newElement->item, u_errorName(subErr), newElement->item->vFuncs);
b75a7d8f
A
389#endif
390
374ca955
A
391 if (subErr == U_USING_DEFAULT_WARNING || U_FAILURE(subErr)) {
392 *pErr = subErr; /* copy sub err unto fillin ONLY if something happens. */
b75a7d8f
A
393 uprv_free(newElement->name);
394 uprv_free(newElement->item);
395 uprv_free(newElement);
729e4ab9 396 return oldValue ? oldValue->item : NULL;
b75a7d8f
A
397 }
398
399 return newElement->item;
400}
401
b75a7d8f
A
402/*----------------------------------------------------------------------*==============
403 * *
404 * Path management. Could be shared with other tools/etc if need be *
405 * later on. *
406 * *
407 *----------------------------------------------------------------------*/
408
729e4ab9
A
409U_NAMESPACE_BEGIN
410
411class UDataPathIterator
b75a7d8f 412{
729e4ab9
A
413public:
414 UDataPathIterator(const char *path, const char *pkg,
415 const char *item, const char *suffix, UBool doCheckLastFour,
416 UErrorCode *pErrorCode);
417 const char *next(UErrorCode *pErrorCode);
418
419private:
b75a7d8f
A
420 const char *path; /* working path (u_icudata_Dir) */
421 const char *nextPath; /* path following this one */
422 const char *basename; /* item's basename (icudt22e_mt.res)*/
3d1f044b
A
423
424 StringPiece suffix; /* item suffix (can be null) */
b75a7d8f 425
374ca955
A
426 uint32_t basenameLen; /* length of basename */
427
729e4ab9
A
428 CharString itemPath; /* path passed in with item name */
429 CharString pathBuffer; /* output path for this it'ion */
430 CharString packageStub; /* example: "/icudt28b". Will ignore that leaf in set paths. */
b75a7d8f 431
374ca955
A
432 UBool checkLastFour; /* if TRUE then allow paths such as '/foo/myapp.dat'
433 * to match, checks last 4 chars of suffix with
434 * last 4 of path, then previous chars. */
729e4ab9 435};
b75a7d8f 436
729e4ab9 437/**
3d1f044b
A
438 * @param iter The iterator to be initialized. Its current state does not matter.
439 * @param inPath The full pathname to be iterated over. If NULL, defaults to U_ICUDATA_NAME
440 * @param pkg Package which is being searched for, ex "icudt28l". Will ignore leaf directories such as /icudt28l
441 * @param item Item to be searched for. Can include full path, such as /a/b/foo.dat
442 * @param inSuffix Optional item suffix, if not-null (ex. ".dat") then 'path' can contain 'item' explicitly.
443 * Ex: 'stuff.dat' would be found in '/a/foo:/tmp/stuff.dat:/bar/baz' as item #2.
444 * '/blarg/stuff.dat' would also be found.
445 * Note: inSuffix may also be the 'item' being searched for as well, (ex: "ibm-5348_P100-1997.cnv"), in which case
446 * the 'item' parameter is often the same as pkg. (Though sometimes might have a tree part as well, ex: "icudt62l-curr").
b75a7d8f 447 */
729e4ab9
A
448UDataPathIterator::UDataPathIterator(const char *inPath, const char *pkg,
449 const char *item, const char *inSuffix, UBool doCheckLastFour,
450 UErrorCode *pErrorCode)
b75a7d8f
A
451{
452#ifdef UDATA_DEBUG
729e4ab9 453 fprintf(stderr, "SUFFIX1=%s PATH=%s\n", inSuffix, inPath);
b75a7d8f
A
454#endif
455 /** Path **/
729e4ab9
A
456 if(inPath == NULL) {
457 path = u_getDataDirectory();
b75a7d8f 458 } else {
729e4ab9 459 path = inPath;
b75a7d8f
A
460 }
461
374ca955 462 /** Package **/
729e4ab9
A
463 if(pkg != NULL) {
464 packageStub.append(U_FILE_SEP_CHAR, *pErrorCode).append(pkg, *pErrorCode);
374ca955 465#ifdef UDATA_DEBUG
729e4ab9 466 fprintf(stderr, "STUB=%s [%d]\n", packageStub.data(), packageStub.length());
374ca955
A
467#endif
468 }
469
b75a7d8f 470 /** Item **/
729e4ab9
A
471 basename = findBasename(item);
472 basenameLen = (int32_t)uprv_strlen(basename);
b75a7d8f 473
b75a7d8f 474 /** Item path **/
729e4ab9
A
475 if(basename == item) {
476 nextPath = path;
477 } else {
478 itemPath.append(item, (int32_t)(basename-item), *pErrorCode);
479 nextPath = itemPath.data();
b75a7d8f
A
480 }
481#ifdef UDATA_DEBUG
729e4ab9 482 fprintf(stderr, "SUFFIX=%s [%p]\n", inSuffix, inSuffix);
b75a7d8f 483#endif
729e4ab9 484
374ca955 485 /** Suffix **/
729e4ab9
A
486 if(inSuffix != NULL) {
487 suffix = inSuffix;
b75a7d8f 488 } else {
729e4ab9 489 suffix = "";
374ca955
A
490 }
491
729e4ab9
A
492 checkLastFour = doCheckLastFour;
493
494 /* pathBuffer will hold the output path strings returned by this iterator */
495
b75a7d8f
A
496#ifdef UDATA_DEBUG
497 fprintf(stderr, "%p: init %s -> [path=%s], [base=%s], [suff=%s], [itempath=%s], [nextpath=%s], [checklast4=%s]\n",
498 iter,
499 item,
729e4ab9
A
500 path,
501 basename,
502 suffix,
503 itemPath.data(),
504 nextPath,
505 checkLastFour?"TRUE":"false");
b75a7d8f 506#endif
b75a7d8f
A
507}
508
509/**
510 * Get the next path on the list.
511 *
512 * @param iter The Iter to be used
513 * @param len If set, pointer to the length of the returned path, for convenience.
514 * @return Pointer to the next path segment, or NULL if there are no more.
515 */
729e4ab9 516const char *UDataPathIterator::next(UErrorCode *pErrorCode)
b75a7d8f 517{
729e4ab9
A
518 if(U_FAILURE(*pErrorCode)) {
519 return NULL;
520 }
521
522 const char *currentPath = NULL;
523 int32_t pathLen = 0;
b75a7d8f
A
524 const char *pathBasename;
525
b75a7d8f
A
526 do
527 {
729e4ab9 528 if( nextPath == NULL ) {
73c04bcf 529 break;
b75a7d8f 530 }
729e4ab9
A
531 currentPath = nextPath;
532
533 if(nextPath == itemPath.data()) { /* we were processing item's path. */
534 nextPath = path; /* start with regular path next tm. */
535 pathLen = (int32_t)uprv_strlen(currentPath);
b75a7d8f
A
536 } else {
537 /* fix up next for next time */
729e4ab9
A
538 nextPath = uprv_strchr(currentPath, U_PATH_SEP_CHAR);
539 if(nextPath == NULL) {
b75a7d8f 540 /* segment: entire path */
729e4ab9 541 pathLen = (int32_t)uprv_strlen(currentPath);
b75a7d8f
A
542 } else {
543 /* segment: until next segment */
729e4ab9
A
544 pathLen = (int32_t)(nextPath - currentPath);
545 /* skip divider */
546 nextPath ++;
b75a7d8f
A
547 }
548 }
549
550 if(pathLen == 0) {
551 continue;
552 }
553
554#ifdef UDATA_DEBUG
729e4ab9 555 fprintf(stderr, "rest of path (IDD) = %s\n", currentPath);
b75a7d8f
A
556 fprintf(stderr, " ");
557 {
374ca955 558 uint32_t qqq;
b75a7d8f
A
559 for(qqq=0;qqq<pathLen;qqq++)
560 {
561 fprintf(stderr, " ");
562 }
563
564 fprintf(stderr, "^\n");
565 }
566#endif
729e4ab9 567 pathBuffer.clear().append(currentPath, pathLen, *pErrorCode);
b75a7d8f
A
568
569 /* check for .dat files */
729e4ab9 570 pathBasename = findBasename(pathBuffer.data());
b75a7d8f 571
729e4ab9 572 if(checkLastFour == TRUE &&
b75a7d8f 573 (pathLen>=4) &&
3d1f044b 574 uprv_strncmp(pathBuffer.data() +(pathLen-4), suffix.data(), 4)==0 && /* suffix matches */
729e4ab9
A
575 uprv_strncmp(findBasename(pathBuffer.data()), basename, basenameLen)==0 && /* base matches */
576 uprv_strlen(pathBasename)==(basenameLen+4)) { /* base+suffix = full len */
577
b75a7d8f 578#ifdef UDATA_DEBUG
729e4ab9 579 fprintf(stderr, "Have %s file on the path: %s\n", suffix, pathBuffer.data());
b75a7d8f
A
580#endif
581 /* do nothing */
582 }
583 else
584 { /* regular dir path */
729e4ab9 585 if(pathBuffer[pathLen-1] != U_FILE_SEP_CHAR) {
b75a7d8f 586 if((pathLen>=4) &&
729e4ab9 587 uprv_strncmp(pathBuffer.data()+(pathLen-4), ".dat", 4) == 0)
b75a7d8f
A
588 {
589#ifdef UDATA_DEBUG
729e4ab9 590 fprintf(stderr, "skipping non-directory .dat file %s\n", pathBuffer.data());
b75a7d8f
A
591#endif
592 continue;
593 }
374ca955
A
594
595 /* Check if it is a directory with the same name as our package */
729e4ab9
A
596 if(!packageStub.isEmpty() &&
597 (pathLen > packageStub.length()) &&
598 !uprv_strcmp(pathBuffer.data() + pathLen - packageStub.length(), packageStub.data())) {
374ca955 599#ifdef UDATA_DEBUG
729e4ab9 600 fprintf(stderr, "Found stub %s (will add package %s of len %d)\n", packageStub.data(), basename, basenameLen);
374ca955 601#endif
729e4ab9 602 pathBuffer.truncate(pathLen - packageStub.length());
374ca955 603 }
729e4ab9
A
604 pathBuffer.append(U_FILE_SEP_CHAR, *pErrorCode);
605 }
b75a7d8f 606
729e4ab9
A
607 /* + basename */
608 pathBuffer.append(packageStub.data()+1, packageStub.length()-1, *pErrorCode);
b75a7d8f 609
3d1f044b 610 if (!suffix.empty()) /* tack on suffix */
b75a7d8f 611 {
3d1f044b
A
612 if (suffix.length() > 4) {
613 // If the suffix is actually an item ("ibm-5348_P100-1997.cnv") and not an extension (".res")
614 // then we need to ensure that the path ends with a separator.
615 pathBuffer.ensureEndsWithFileSeparator(*pErrorCode);
616 }
729e4ab9 617 pathBuffer.append(suffix, *pErrorCode);
b75a7d8f 618 }
b75a7d8f
A
619 }
620
b75a7d8f 621#ifdef UDATA_DEBUG
729e4ab9 622 fprintf(stderr, " --> %s\n", pathBuffer.data());
b75a7d8f
A
623#endif
624
729e4ab9 625 return pathBuffer.data();
b75a7d8f 626
729e4ab9 627 } while(path);
b75a7d8f
A
628
629 /* fell way off the end */
630 return NULL;
631}
632
729e4ab9 633U_NAMESPACE_END
374ca955 634
b75a7d8f
A
635/* ==================================================================================*/
636
637
638/*----------------------------------------------------------------------*
639 * *
f3c0d7a5 640 * Add a static reference to the common data library *
b75a7d8f
A
641 * Unless overridden by an explicit udata_setCommonData, this will be *
642 * our common data. *
643 * *
644 *----------------------------------------------------------------------*/
f3c0d7a5 645#if U_PLATFORM_HAS_WINUWP_API == 0 // Windows UWP Platform does not support dll icu data at this time
729e4ab9 646extern "C" const DataHeader U_DATA_API U_ICUDATA_ENTRY_POINT;
f3c0d7a5 647#endif
b75a7d8f 648
729e4ab9
A
649/*
650 * This would be a good place for weak-linkage declarations of
651 * partial-data-library access functions where each returns a pointer
652 * to its data package, if it is linked in.
653 */
654/*
655extern const void *uprv_getICUData_collation(void) ATTRIBUTE_WEAK;
656extern const void *uprv_getICUData_conversion(void) ATTRIBUTE_WEAK;
657*/
b75a7d8f
A
658
659/*----------------------------------------------------------------------*
660 * *
661 * openCommonData Attempt to open a common format (.dat) file *
662 * Map it into memory (if it's not there already) *
663 * and return a UDataMemory object for it. *
664 * *
665 * If the requested data is already open and cached *
666 * just return the cached UDataMem object. *
667 * *
668 *----------------------------------------------------------------------*/
669static UDataMemory *
73c04bcf 670openCommonData(const char *path, /* Path from OpenChoice? */
729e4ab9 671 int32_t commonDataIndex, /* ICU Data (index >= 0) if path == NULL */
b75a7d8f
A
672 UErrorCode *pErrorCode)
673{
674 UDataMemory tData;
b75a7d8f 675 const char *pathBuffer;
b75a7d8f
A
676 const char *inBasename;
677
678 if (U_FAILURE(*pErrorCode)) {
679 return NULL;
680 }
681
682 UDataMemory_init(&tData);
683
684 /* ??????? TODO revisit this */
729e4ab9 685 if (commonDataIndex >= 0) {
b75a7d8f 686 /* "mini-cache" for common ICU data */
b331163b 687 if(commonDataIndex >= UPRV_LENGTHOF(gCommonICUDataArray)) {
729e4ab9 688 return NULL;
b75a7d8f 689 }
2ca993e8
A
690 {
691 Mutex lock;
692 if(gCommonICUDataArray[commonDataIndex] != NULL) {
693 return gCommonICUDataArray[commonDataIndex];
694 }
f3c0d7a5 695#if U_PLATFORM_HAS_WINUWP_API == 0 // Windows UWP Platform does not support dll icu data at this time
729e4ab9
A
696 int32_t i;
697 for(i = 0; i < commonDataIndex; ++i) {
698 if(gCommonICUDataArray[i]->pHeader == &U_ICUDATA_ENTRY_POINT) {
699 /* The linked-in data is already in the list. */
700 return NULL;
701 }
702 }
f3c0d7a5 703#endif
2ca993e8 704 }
b75a7d8f 705
2ca993e8
A
706 /* Add the linked-in data to the list. */
707 /*
708 * This is where we would check and call weakly linked partial-data-library
709 * access functions.
710 */
711 /*
712 if (uprv_getICUData_collation) {
713 setCommonICUDataPointer(uprv_getICUData_collation(), FALSE, pErrorCode);
714 }
715 if (uprv_getICUData_conversion) {
716 setCommonICUDataPointer(uprv_getICUData_conversion(), FALSE, pErrorCode);
717 }
718 */
f3c0d7a5 719#if U_PLATFORM_HAS_WINUWP_API == 0 // Windows UWP Platform does not support dll icu data at this time
2ca993e8
A
720 setCommonICUDataPointer(&U_ICUDATA_ENTRY_POINT, FALSE, pErrorCode);
721 {
722 Mutex lock;
723 return gCommonICUDataArray[commonDataIndex];
729e4ab9 724 }
f3c0d7a5 725#endif
b75a7d8f
A
726 }
727
728
729 /* request is NOT for ICU Data. */
730
731 /* Find the base name portion of the supplied path. */
732 /* inBasename will be left pointing somewhere within the original path string. */
733 inBasename = findBasename(path);
734#ifdef UDATA_DEBUG
735 fprintf(stderr, "inBasename = %s\n", inBasename);
736#endif
737
738 if(*inBasename==0) {
739 /* no basename. This will happen if the original path was a directory name, */
740 /* like "a/b/c/". (Fallback to separate files will still work.) */
741#ifdef UDATA_DEBUG
742 fprintf(stderr, "ocd: no basename in %s, bailing.\n", path);
743#endif
f3c0d7a5
A
744 if (U_SUCCESS(*pErrorCode)) {
745 *pErrorCode=U_FILE_ACCESS_ERROR;
746 }
b75a7d8f
A
747 return NULL;
748 }
749
750 /* Is the requested common data file already open and cached? */
751 /* Note that the cache is keyed by the base name only. The rest of the path, */
752 /* if any, is not considered. */
f3c0d7a5
A
753 UDataMemory *dataToReturn = udata_findCachedData(inBasename, *pErrorCode);
754 if (dataToReturn != NULL || U_FAILURE(*pErrorCode)) {
755 return dataToReturn;
b75a7d8f
A
756 }
757
758 /* Requested item is not in the cache.
759 * Hunt it down, trying all the path locations
760 */
761
729e4ab9 762 UDataPathIterator iter(u_getDataDirectory(), inBasename, path, ".dat", TRUE, pErrorCode);
b75a7d8f 763
3d1f044b 764 while ((UDataMemory_isLoaded(&tData)==FALSE) && (pathBuffer = iter.next(pErrorCode)) != NULL)
b75a7d8f
A
765 {
766#ifdef UDATA_DEBUG
767 fprintf(stderr, "ocd: trying path %s - ", pathBuffer);
768#endif
3d1f044b 769 uprv_mapFile(&tData, pathBuffer, pErrorCode);
b75a7d8f
A
770#ifdef UDATA_DEBUG
771 fprintf(stderr, "%s\n", UDataMemory_isLoaded(&tData)?"LOADED":"not loaded");
772#endif
773 }
3d1f044b
A
774 if (U_FAILURE(*pErrorCode)) {
775 return NULL;
776 }
b75a7d8f
A
777
778#if defined(OS390_STUBDATA) && defined(OS390BATCH)
779 if (!UDataMemory_isLoaded(&tData)) {
780 char ourPathBuffer[1024];
781 /* One more chance, for extendCommonData() */
782 uprv_strncpy(ourPathBuffer, path, 1019);
783 ourPathBuffer[1019]=0;
784 uprv_strcat(ourPathBuffer, ".dat");
3d1f044b 785 uprv_mapFile(&tData, ourPathBuffer, pErrorCode);
b75a7d8f
A
786 }
787#endif
788
f3c0d7a5
A
789 if (U_FAILURE(*pErrorCode)) {
790 return NULL;
791 }
b75a7d8f
A
792 if (!UDataMemory_isLoaded(&tData)) {
793 /* no common data */
794 *pErrorCode=U_FILE_ACCESS_ERROR;
795 return NULL;
796 }
797
798 /* we have mapped a file, check its header */
799 udata_checkCommonData(&tData, pErrorCode);
800
801
802 /* Cache the UDataMemory struct for this .dat file,
803 * so we won't need to hunt it down and map it again next time
804 * something is needed from it. */
805 return udata_cacheDataItem(inBasename, &tData, pErrorCode);
806}
807
808
b75a7d8f
A
809/*----------------------------------------------------------------------*
810 * *
811 * extendICUData If the full set of ICU data was not loaded at *
812 * program startup, load it now. This function will *
813 * be called when the lookup of an ICU data item in *
814 * the common ICU data fails. *
815 * *
b75a7d8f
A
816 * return true if new data is loaded, false otherwise.*
817 * *
818 *----------------------------------------------------------------------*/
729e4ab9 819static UBool extendICUData(UErrorCode *pErr)
b75a7d8f 820{
b75a7d8f
A
821 UDataMemory *pData;
822 UDataMemory copyPData;
729e4ab9
A
823 UBool didUpdate = FALSE;
824
825 /*
826 * There is a chance for a race condition here.
827 * Normally, ICU data is loaded from a DLL or via mmap() and
828 * setCommonICUData() will detect if the same address is set twice.
829 * If ICU is built with data loading via fread() then the address will
830 * be different each time the common data is loaded and we may add
831 * multiple copies of the data.
832 * In this case, use a mutex to prevent the race.
833 * Use a specific mutex to avoid nested locks of the global mutex.
834 */
835#if MAP_IMPLEMENTATION==MAP_STDIO
3d1f044b
A
836 static UMutex *extendICUDataMutex = STATIC_NEW(UMutex);
837 umtx_lock(extendICUDataMutex);
729e4ab9 838#endif
2ca993e8 839 if(!umtx_loadAcquire(gHaveTriedToLoadCommonData)) {
729e4ab9
A
840 /* See if we can explicitly open a .dat file for the ICUData. */
841 pData = openCommonData(
842 U_ICUDATA_NAME, /* "icudt20l" , for example. */
843 -1, /* Pretend we're not opening ICUData */
844 pErr);
845
846 /* How about if there is no pData, eh... */
847
848 UDataMemory_init(&copyPData);
849 if(pData != NULL) {
850 UDatamemory_assign(&copyPData, pData);
851 copyPData.map = 0; /* The mapping for this data is owned by the hash table */
852 copyPData.mapAddr = 0; /* which will unmap it when ICU is shut down. */
853 /* CommonICUData is also unmapped when ICU is shut down.*/
854 /* To avoid unmapping the data twice, zero out the map */
855 /* fields in the UDataMemory that we're assigning */
856 /* to CommonICUData. */
857
4388f060 858 didUpdate = /* no longer using this result */
729e4ab9
A
859 setCommonICUData(&copyPData,/* The new common data. */
860 FALSE, /* No warnings if write didn't happen */
861 pErr); /* setCommonICUData honors errors; NOP if error set */
862 }
b75a7d8f 863
2ca993e8 864 umtx_storeRelease(gHaveTriedToLoadCommonData, 1);
b75a7d8f
A
865 }
866
f3c0d7a5 867 didUpdate = findCommonICUDataByName(U_ICUDATA_NAME, *pErr); /* Return 'true' when a racing writes out the extended */
729e4ab9
A
868 /* data after another thread has failed to see it (in openCommonData), so */
869 /* extended data can be examined. */
870 /* Also handles a race through here before gHaveTriedToLoadCommonData is set. */
b75a7d8f 871
729e4ab9 872#if MAP_IMPLEMENTATION==MAP_STDIO
3d1f044b 873 umtx_unlock(extendICUDataMutex);
729e4ab9
A
874#endif
875 return didUpdate; /* Return true if ICUData pointer was updated. */
3d1f044b 876 /* (Could potentially have been done by another thread racing */
b75a7d8f
A
877 /* us through here, but that's fine, we still return true */
878 /* so that current thread will also examine extended data. */
879}
880
b75a7d8f
A
881/*----------------------------------------------------------------------*
882 * *
883 * udata_setCommonData *
884 * *
885 *----------------------------------------------------------------------*/
886U_CAPI void U_EXPORT2
887udata_setCommonData(const void *data, UErrorCode *pErrorCode) {
888 UDataMemory dataMemory;
889
890 if(pErrorCode==NULL || U_FAILURE(*pErrorCode)) {
891 return;
892 }
893
894 if(data==NULL) {
895 *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
896 return;
897 }
898
b75a7d8f
A
899 /* set the data pointer and test for validity */
900 UDataMemory_init(&dataMemory);
901 UDataMemory_setData(&dataMemory, data);
902 udata_checkCommonData(&dataMemory, pErrorCode);
903 if (U_FAILURE(*pErrorCode)) {return;}
904
905 /* we have good data */
906 /* Set it up as the ICU Common Data. */
729e4ab9 907 setCommonICUData(&dataMemory, TRUE, pErrorCode);
b75a7d8f
A
908}
909
b75a7d8f
A
910/*---------------------------------------------------------------------------
911 *
912 * udata_setAppData
913 *
914 *---------------------------------------------------------------------------- */
915U_CAPI void U_EXPORT2
916udata_setAppData(const char *path, const void *data, UErrorCode *err)
917{
918 UDataMemory udm;
919
920 if(err==NULL || U_FAILURE(*err)) {
921 return;
922 }
923 if(data==NULL) {
924 *err=U_ILLEGAL_ARGUMENT_ERROR;
925 return;
926 }
927
928 UDataMemory_init(&udm);
729e4ab9 929 UDataMemory_setData(&udm, data);
b75a7d8f
A
930 udata_checkCommonData(&udm, err);
931 udata_cacheDataItem(path, &udm, err);
932}
933
934/*----------------------------------------------------------------------------*
935 * *
936 * checkDataItem Given a freshly located/loaded data item, either *
937 * an entry in a common file or a separately loaded file, *
938 * sanity check its header, and see if the data is *
939 * acceptable to the app. *
940 * If the data is good, create and return a UDataMemory *
941 * object that can be returned to the application. *
942 * Return NULL on any sort of failure. *
943 * *
944 *----------------------------------------------------------------------------*/
945static UDataMemory *
946checkDataItem
947(
948 const DataHeader *pHeader, /* The data item to be checked. */
949 UDataMemoryIsAcceptable *isAcceptable, /* App's call-back function */
950 void *context, /* pass-thru param for above. */
951 const char *type, /* pass-thru param for above. */
952 const char *name, /* pass-thru param for above. */
953 UErrorCode *nonFatalErr, /* Error code if this data was not acceptable */
954 /* but openChoice should continue with */
955 /* trying to get data from fallback path. */
956 UErrorCode *fatalErr /* Bad error, caller should return immediately */
957 )
958{
959 UDataMemory *rDataMem = NULL; /* the new UDataMemory, to be returned. */
960
961 if (U_FAILURE(*fatalErr)) {
962 return NULL;
963 }
964
965 if(pHeader->dataHeader.magic1==0xda &&
966 pHeader->dataHeader.magic2==0x27 &&
b75a7d8f 967 (isAcceptable==NULL || isAcceptable(context, type, name, &pHeader->info))
374ca955 968 ) {
b75a7d8f
A
969 rDataMem=UDataMemory_createNewInstance(fatalErr);
970 if (U_FAILURE(*fatalErr)) {
971 return NULL;
972 }
973 rDataMem->pHeader = pHeader;
974 } else {
975 /* the data is not acceptable, look further */
976 /* If we eventually find something good, this errorcode will be */
977 /* cleared out. */
978 *nonFatalErr=U_INVALID_FORMAT_ERROR;
979 }
980 return rDataMem;
981}
982
73c04bcf
A
983/**
984 * @return 0 if not loaded, 1 if loaded or err
985 */
986static UDataMemory *doLoadFromIndividualFiles(const char *pkgName,
987 const char *dataPath, const char *tocEntryPathSuffix,
988 /* following arguments are the same as doOpenChoice itself */
989 const char *path, const char *type, const char *name,
990 UDataMemoryIsAcceptable *isAcceptable, void *context,
991 UErrorCode *subErrorCode,
992 UErrorCode *pErrorCode)
993{
73c04bcf
A
994 const char *pathBuffer;
995 UDataMemory dataMemory;
996 UDataMemory *pEntryData;
997
73c04bcf
A
998 /* look in ind. files: package\nam.typ ========================= */
999 /* init path iterator for individual files */
729e4ab9 1000 UDataPathIterator iter(dataPath, pkgName, path, tocEntryPathSuffix, FALSE, pErrorCode);
73c04bcf 1001
3d1f044b 1002 while ((pathBuffer = iter.next(pErrorCode)) != NULL)
73c04bcf
A
1003 {
1004#ifdef UDATA_DEBUG
1005 fprintf(stderr, "UDATA: trying individual file %s\n", pathBuffer);
1006#endif
3d1f044b 1007 if (uprv_mapFile(&dataMemory, pathBuffer, pErrorCode))
73c04bcf
A
1008 {
1009 pEntryData = checkDataItem(dataMemory.pHeader, isAcceptable, context, type, name, subErrorCode, pErrorCode);
1010 if (pEntryData != NULL) {
1011 /* Data is good.
1012 * Hand off ownership of the backing memory to the user's UDataMemory.
1013 * and return it. */
1014 pEntryData->mapAddr = dataMemory.mapAddr;
1015 pEntryData->map = dataMemory.map;
1016
1017#ifdef UDATA_DEBUG
1018 fprintf(stderr, "** Mapped file: %s\n", pathBuffer);
1019#endif
729e4ab9 1020 return pEntryData;
73c04bcf
A
1021 }
1022
3d1f044b 1023 /* the data is not acceptable, or some error occurred. Either way, unmap the memory */
73c04bcf
A
1024 udata_close(&dataMemory);
1025
1026 /* If we had a nasty error, bail out completely. */
1027 if (U_FAILURE(*pErrorCode)) {
729e4ab9 1028 return NULL;
73c04bcf
A
1029 }
1030
1031 /* Otherwise remember that we found data but didn't like it for some reason */
1032 *subErrorCode=U_INVALID_FORMAT_ERROR;
1033 }
1034#ifdef UDATA_DEBUG
1035 fprintf(stderr, "%s\n", UDataMemory_isLoaded(&dataMemory)?"LOADED":"not loaded");
1036#endif
1037 }
729e4ab9 1038 return NULL;
73c04bcf
A
1039}
1040
1041/**
1042 * @return 0 if not loaded, 1 if loaded or err
1043 */
729e4ab9
A
1044static UDataMemory *doLoadFromCommonData(UBool isICUData, const char * /*pkgName*/,
1045 const char * /*dataPath*/, const char * /*tocEntryPathSuffix*/, const char *tocEntryName,
73c04bcf
A
1046 /* following arguments are the same as doOpenChoice itself */
1047 const char *path, const char *type, const char *name,
1048 UDataMemoryIsAcceptable *isAcceptable, void *context,
1049 UErrorCode *subErrorCode,
1050 UErrorCode *pErrorCode)
1051{
73c04bcf
A
1052 UDataMemory *pEntryData;
1053 const DataHeader *pHeader;
1054 UDataMemory *pCommonData;
729e4ab9
A
1055 int32_t commonDataIndex;
1056 UBool checkedExtendedICUData = FALSE;
73c04bcf
A
1057 /* try to get common data. The loop is for platforms such as the 390 that do
1058 * not initially load the full set of ICU data. If the lookup of an ICU data item
1059 * fails, the full (but slower to load) set is loaded, the and the loop repeats,
1060 * trying the lookup again. Once the full set of ICU data is loaded, the loop wont
1061 * repeat because the full set will be checked the first time through.
1062 *
1063 * The loop also handles the fallback to a .dat file if the application linked
1064 * to the stub data library rather than a real library.
1065 */
729e4ab9
A
1066 for (commonDataIndex = isICUData ? 0 : -1;;) {
1067 pCommonData=openCommonData(path, commonDataIndex, subErrorCode); /** search for pkg **/
73c04bcf 1068
729e4ab9 1069 if(U_SUCCESS(*subErrorCode) && pCommonData!=NULL) {
73c04bcf
A
1070 int32_t length;
1071
1072 /* look up the data piece in the common data */
1073 pHeader=pCommonData->vFuncs->Lookup(pCommonData, tocEntryName, &length, subErrorCode);
1074#ifdef UDATA_DEBUG
1075 fprintf(stderr, "%s: pHeader=%p - %s\n", tocEntryName, pHeader, u_errorName(*subErrorCode));
1076#endif
b75a7d8f 1077
73c04bcf
A
1078 if(pHeader!=NULL) {
1079 pEntryData = checkDataItem(pHeader, isAcceptable, context, type, name, subErrorCode, pErrorCode);
1080#ifdef UDATA_DEBUG
1081 fprintf(stderr, "pEntryData=%p\n", pEntryData);
1082#endif
1083 if (U_FAILURE(*pErrorCode)) {
729e4ab9 1084 return NULL;
73c04bcf
A
1085 }
1086 if (pEntryData != NULL) {
1087 pEntryData->length = length;
729e4ab9 1088 return pEntryData;
73c04bcf
A
1089 }
1090 }
1091 }
3d1f044b
A
1092 // If we failed due to being out-of-memory, then stop early and report the error.
1093 if (*subErrorCode == U_MEMORY_ALLOCATION_ERROR) {
1094 *pErrorCode = *subErrorCode;
1095 return NULL;
1096 }
73c04bcf
A
1097 /* Data wasn't found. If we were looking for an ICUData item and there is
1098 * more data available, load it and try again,
1099 * otherwise break out of this loop. */
729e4ab9
A
1100 if (!isICUData) {
1101 return NULL;
1102 } else if (pCommonData != NULL) {
1103 ++commonDataIndex; /* try the next data package */
1104 } else if ((!checkedExtendedICUData) && extendICUData(subErrorCode)) {
1105 checkedExtendedICUData = TRUE;
1106 /* try this data package slot again: it changed from NULL to non-NULL */
1107 } else {
1108 return NULL;
73c04bcf
A
1109 }
1110 }
73c04bcf 1111}
b75a7d8f 1112
b331163b
A
1113/*
1114 * Identify the Time Zone resources that are subject to special override data loading.
1115 */
1116static UBool isTimeZoneFile(const char *name, const char *type) {
1117 return ((uprv_strcmp(type, "res") == 0) &&
1118 (uprv_strcmp(name, "zoneinfo64") == 0 ||
1119 uprv_strcmp(name, "timezoneTypes") == 0 ||
1120 uprv_strcmp(name, "windowsZones") == 0 ||
1121 uprv_strcmp(name, "metaZones") == 0));
1122}
1123
b75a7d8f
A
1124/*
1125 * A note on the ownership of Mapped Memory
1126 *
1127 * For common format files, ownership resides with the UDataMemory object
1128 * that lives in the cache of opened common data. These UDataMemorys are private
1129 * to the udata implementation, and are never seen directly by users.
1130 *
1131 * The UDataMemory objects returned to users will have the address of some desired
1132 * data within the mapped region, but they wont have the mapping info itself, and thus
1133 * won't cause anything to be removed from memory when they are closed.
1134 *
1135 * For individual data files, the UDataMemory returned to the user holds the
1136 * information necessary to unmap the data on close. If the user independently
1137 * opens the same data file twice, two completely independent mappings will be made.
1138 * (There is no cache of opened data items from individual files, only a cache of
1139 * opened Common Data files, that is, files containing a collection of data items.)
1140 *
1141 * For common data passed in from the user via udata_setAppData() or
1142 * udata_setCommonData(), ownership remains with the user.
1143 *
1144 * UDataMemory objects themselves, as opposed to the memory they describe,
1145 * can be anywhere - heap, stack/local or global.
1146 * They have a flag to indicate when they're heap allocated and thus
1147 * must be deleted when closed.
1148 */
1149
1150
1151/*----------------------------------------------------------------------------*
1152 * *
1153 * main data loading functions *
1154 * *
1155 *----------------------------------------------------------------------------*/
1156static UDataMemory *
1157doOpenChoice(const char *path, const char *type, const char *name,
1158 UDataMemoryIsAcceptable *isAcceptable, void *context,
1159 UErrorCode *pErrorCode)
1160{
374ca955 1161 UDataMemory *retVal = NULL;
b75a7d8f 1162
b75a7d8f
A
1163 const char *dataPath;
1164
374ca955
A
1165 int32_t tocEntrySuffixIndex;
1166 const char *tocEntryPathSuffix;
73c04bcf 1167 UErrorCode subErrorCode=U_ZERO_ERROR;
374ca955
A
1168 const char *treeChar;
1169
1170 UBool isICUData = FALSE;
1171
73c04bcf
A
1172
1173 /* Is this path ICU data? */
374ca955 1174 if(path == NULL ||
73c04bcf
A
1175 !strcmp(path, U_ICUDATA_ALIAS) || /* "ICUDATA" */
1176 !uprv_strncmp(path, U_ICUDATA_NAME U_TREE_SEPARATOR_STRING, /* "icudt26e-" */
1177 uprv_strlen(U_ICUDATA_NAME U_TREE_SEPARATOR_STRING)) ||
1178 !uprv_strncmp(path, U_ICUDATA_ALIAS U_TREE_SEPARATOR_STRING, /* "ICUDATA-" */
374ca955
A
1179 uprv_strlen(U_ICUDATA_ALIAS U_TREE_SEPARATOR_STRING))) {
1180 isICUData = TRUE;
1181 }
1182
73c04bcf 1183#if (U_FILE_SEP_CHAR != U_FILE_ALT_SEP_CHAR) /* Windows: try "foo\bar" and "foo/bar" */
374ca955 1184 /* remap from alternate path char to the main one */
729e4ab9 1185 CharString altSepPath;
374ca955 1186 if(path) {
729e4ab9
A
1187 if(uprv_strchr(path,U_FILE_ALT_SEP_CHAR) != NULL) {
1188 altSepPath.append(path, *pErrorCode);
1189 char *p;
0f5d89e8 1190 while ((p = uprv_strchr(altSepPath.data(), U_FILE_ALT_SEP_CHAR)) != NULL) {
374ca955
A
1191 *p = U_FILE_SEP_CHAR;
1192 }
1193#if defined (UDATA_DEBUG)
1194 fprintf(stderr, "Changed path from [%s] to [%s]\n", path, altSepPath.s);
1195#endif
729e4ab9 1196 path = altSepPath.data();
374ca955
A
1197 }
1198 }
1199#endif
1200
729e4ab9
A
1201 CharString tocEntryName; /* entry name in tree format. ex: 'icudt28b/coll/ar.res' */
1202 CharString tocEntryPath; /* entry name in path format. ex: 'icudt28b\\coll\\ar.res' */
374ca955 1203
729e4ab9
A
1204 CharString pkgName;
1205 CharString treeName;
374ca955 1206
73c04bcf 1207 /* ======= Set up strings */
374ca955 1208 if(path==NULL) {
729e4ab9 1209 pkgName.append(U_ICUDATA_NAME, *pErrorCode);
374ca955
A
1210 } else {
1211 const char *pkg;
1212 const char *first;
1213 pkg = uprv_strrchr(path, U_FILE_SEP_CHAR);
1214 first = uprv_strchr(path, U_FILE_SEP_CHAR);
1215 if(uprv_pathIsAbsolute(path) || (pkg != first)) { /* more than one slash in the path- not a tree name */
1216 /* see if this is an /absolute/path/to/package path */
1217 if(pkg) {
729e4ab9 1218 pkgName.append(pkg+1, *pErrorCode);
374ca955 1219 } else {
729e4ab9 1220 pkgName.append(path, *pErrorCode);
374ca955
A
1221 }
1222 } else {
1223 treeChar = uprv_strchr(path, U_TREE_SEPARATOR);
1224 if(treeChar) {
729e4ab9 1225 treeName.append(treeChar+1, *pErrorCode); /* following '-' */
73c04bcf 1226 if(isICUData) {
729e4ab9 1227 pkgName.append(U_ICUDATA_NAME, *pErrorCode);
73c04bcf 1228 } else {
729e4ab9 1229 pkgName.append(path, (int32_t)(treeChar-path), *pErrorCode);
73c04bcf
A
1230 if (first == NULL) {
1231 /*
1232 This user data has no path, but there is a tree name.
1233 Look up the correct path from the data cache later.
1234 */
729e4ab9 1235 path = pkgName.data();
73c04bcf 1236 }
374ca955
A
1237 }
1238 } else {
73c04bcf 1239 if(isICUData) {
729e4ab9 1240 pkgName.append(U_ICUDATA_NAME, *pErrorCode);
73c04bcf 1241 } else {
729e4ab9 1242 pkgName.append(path, *pErrorCode);
374ca955
A
1243 }
1244 }
1245 }
1246 }
1247
1248#ifdef UDATA_DEBUG
729e4ab9 1249 fprintf(stderr, " P=%s T=%s\n", pkgName.data(), treeName.data());
374ca955
A
1250#endif
1251
73c04bcf
A
1252 /* setting up the entry name and file name
1253 * Make up a full name by appending the type to the supplied
b75a7d8f
A
1254 * name, assuming that a type was supplied.
1255 */
1256
1257 /* prepend the package */
729e4ab9
A
1258 tocEntryName.append(pkgName, *pErrorCode);
1259 tocEntryPath.append(pkgName, *pErrorCode);
1260 tocEntrySuffixIndex = tocEntryName.length();
b75a7d8f 1261
729e4ab9
A
1262 if(!treeName.isEmpty()) {
1263 tocEntryName.append(U_TREE_ENTRY_SEP_CHAR, *pErrorCode).append(treeName, *pErrorCode);
1264 tocEntryPath.append(U_FILE_SEP_CHAR, *pErrorCode).append(treeName, *pErrorCode);
374ca955 1265 }
b75a7d8f 1266
729e4ab9
A
1267 tocEntryName.append(U_TREE_ENTRY_SEP_CHAR, *pErrorCode).append(name, *pErrorCode);
1268 tocEntryPath.append(U_FILE_SEP_CHAR, *pErrorCode).append(name, *pErrorCode);
b75a7d8f 1269 if(type!=NULL && *type!=0) {
729e4ab9
A
1270 tocEntryName.append(".", *pErrorCode).append(type, *pErrorCode);
1271 tocEntryPath.append(".", *pErrorCode).append(type, *pErrorCode);
b75a7d8f 1272 }
3d1f044b
A
1273 // The +1 is for the U_FILE_SEP_CHAR that is always appended above.
1274 tocEntryPathSuffix = tocEntryPath.data() + tocEntrySuffixIndex + 1; /* suffix starts here */
b75a7d8f
A
1275
1276#ifdef UDATA_DEBUG
729e4ab9
A
1277 fprintf(stderr, " tocEntryName = %s\n", tocEntryName.data());
1278 fprintf(stderr, " tocEntryPath = %s\n", tocEntryName.data());
1279#endif
b75a7d8f 1280
f3c0d7a5 1281#if U_PLATFORM_HAS_WINUWP_API == 0 // Windows UWP Platform does not support dll icu data at this time
b75a7d8f 1282 if(path == NULL) {
73c04bcf 1283 path = COMMON_DATA_NAME; /* "icudt26e" */
b75a7d8f 1284 }
f3c0d7a5
A
1285#else
1286 // Windows UWP expects only a single data file.
1287 path = COMMON_DATA_NAME; /* "icudt26e" */
1288#endif
b75a7d8f
A
1289
1290 /************************ Begin loop looking for ind. files ***************/
1291#ifdef UDATA_DEBUG
729e4ab9 1292 fprintf(stderr, "IND: inBasename = %s, pkg=%s\n", "(n/a)", packageNameFromPath(path));
b75a7d8f
A
1293#endif
1294
b75a7d8f 1295 /* End of dealing with a null basename */
b75a7d8f
A
1296 dataPath = u_getDataDirectory();
1297
b331163b 1298 /**** Time zone individual files override */
f3c0d7a5 1299 if (isICUData && isTimeZoneFile(name, type)) {
b331163b
A
1300 const char *tzFilesDir = u_getTimeZoneFilesDirectory(pErrorCode);
1301 if (tzFilesDir[0] != 0) {
1302#ifdef UDATA_DEBUG
1303 fprintf(stderr, "Trying Time Zone Files directory = %s\n", tzFilesDir);
2ca993e8
A
1304#endif
1305#ifdef UDATA_TZFILES_DEBUG
1306 fprintf(stderr, "# dOC U_TIMEZONE_FILES_DIR: %s\n", U_TIMEZONE_FILES_DIR);
1307#endif
1308
1309#if defined(U_TIMEZONE_PACKAGE)
1310 // make tztocEntryName, like tocEntryName but with our package name
1311 UErrorCode tzpkgErrorCode = U_ZERO_ERROR;
1312 CharString tztocPkgPath;
1313 tztocPkgPath.append(tzFilesDir, tzpkgErrorCode);
1314 tztocPkgPath.append(U_FILE_SEP_CHAR, tzpkgErrorCode).append(U_TIMEZONE_PACKAGE, tzpkgErrorCode);
1315 CharString tztocEntryName;
1316 tztocEntryName.append(U_TIMEZONE_PACKAGE, tzpkgErrorCode);
1317 if(!treeName.isEmpty()) {
1318 tztocEntryName.append(U_TREE_ENTRY_SEP_CHAR, tzpkgErrorCode).append(treeName, tzpkgErrorCode);
1319 }
1320 tztocEntryName.append(U_TREE_ENTRY_SEP_CHAR, tzpkgErrorCode).append(name, tzpkgErrorCode);
1321 if(type!=NULL && *type!=0) {
1322 tztocEntryName.append(".", tzpkgErrorCode).append(type, tzpkgErrorCode);
1323 }
1324#ifdef UDATA_TZFILES_DEBUG
1325 fprintf(stderr, "# dOC tz pkg, doLoadFromCommonData start; U_TIMEZONE_PACKAGE: %s, tztocPkgPath.data(): %s, tztocEntryName.data(): %s, name: %s\n",
1326 U_TIMEZONE_PACKAGE, tztocPkgPath.data(), tztocEntryName.data(), name);
1327#endif
1328 retVal = doLoadFromCommonData(FALSE, "" /*ignored*/, "" /*ignored*/, "" /*ignored*/,
1329 tztocEntryName.data(), // tocEntryName, like icutz44/zoneinfo64.res
1330 tztocPkgPath.data(), // path = path to pkg, like /usr/share/icu/icutz44l
1331 type, name, isAcceptable, context, &subErrorCode, &tzpkgErrorCode);
1332#ifdef UDATA_TZFILES_DEBUG
1333 fprintf(stderr, "# dOC tz pkg, doLoadFromCommonData end; status %d, retVal %p\n", tzpkgErrorCode, retVal);
1334#endif
1335 if(U_SUCCESS(tzpkgErrorCode) && retVal != NULL) {
1336 return retVal;
1337 }
1338#endif /* defined(U_TIMEZONE_PACKAGE) */
1339 // The following assumes any timezone resources in tzFilesDir are in individual .res files
1340#ifdef UDATA_TZFILES_DEBUG
1341 fprintf(stderr, "# dOC tz files, doLoadFromIndividualFiles start; tzFilesDir: %s, tocEntryPathSuffix: %s, name: %s\n",
1342 tzFilesDir, tocEntryPathSuffix, name);
b331163b
A
1343#endif
1344 retVal = doLoadFromIndividualFiles(/* pkgName.data() */ "", tzFilesDir, tocEntryPathSuffix,
1345 /* path */ "", type, name, isAcceptable, context, &subErrorCode, pErrorCode);
2ca993e8
A
1346#ifdef UDATA_TZFILES_DEBUG
1347 fprintf(stderr, "# dOC tz files, doLoadFromIndividualFiles end; status %d, retVal %p\n", *pErrorCode, retVal);
1348#endif
b331163b
A
1349 if((retVal != NULL) || U_FAILURE(*pErrorCode)) {
1350 return retVal;
1351 }
1352 }
1353 }
1354
73c04bcf
A
1355 /**** COMMON PACKAGE - only if packages are first. */
1356 if(gDataFileAccess == UDATA_PACKAGES_FIRST) {
374ca955 1357#ifdef UDATA_DEBUG
73c04bcf 1358 fprintf(stderr, "Trying packages (UDATA_PACKAGES_FIRST)\n");
374ca955 1359#endif
73c04bcf 1360 /* #2 */
2ca993e8
A
1361#ifdef UDATA_TZFILES_DEBUG
1362 if (isTimeZoneFile(name, type)) {
1363 fprintf(stderr, "# dOC std common 1, doLoadFromCommonData start; U_TIMEZONE_PACKAGE: path: %s, tocEntryName.data(): %s, name: %s\n",
1364 path, tocEntryName.data(), name);
1365 }
1366#endif
73c04bcf 1367 retVal = doLoadFromCommonData(isICUData,
729e4ab9 1368 pkgName.data(), dataPath, tocEntryPathSuffix, tocEntryName.data(),
73c04bcf 1369 path, type, name, isAcceptable, context, &subErrorCode, pErrorCode);
2ca993e8
A
1370#ifdef UDATA_TZFILES_DEBUG
1371 if (isTimeZoneFile(name, type)) {
1372 fprintf(stderr, "# dOC std common 1, doLoadFromCommonData end; status %d, retVal %p\n", *pErrorCode, retVal);
1373 }
1374#endif
73c04bcf 1375 if((retVal != NULL) || U_FAILURE(*pErrorCode)) {
729e4ab9 1376 return retVal;
b75a7d8f 1377 }
73c04bcf 1378 }
729e4ab9 1379
73c04bcf
A
1380 /**** INDIVIDUAL FILES */
1381 if((gDataFileAccess==UDATA_PACKAGES_FIRST) ||
1382 (gDataFileAccess==UDATA_FILES_FIRST)) {
374ca955 1383#ifdef UDATA_DEBUG
73c04bcf 1384 fprintf(stderr, "Trying individual files\n");
374ca955 1385#endif
73c04bcf
A
1386 /* Check to make sure that there is a dataPath to iterate over */
1387 if ((dataPath && *dataPath) || !isICUData) {
2ca993e8
A
1388#ifdef UDATA_TZFILES_DEBUG
1389 if (isTimeZoneFile(name, type)) {
1390 fprintf(stderr, "# dOC std indiv files, doLoadFromIndividualFiles start; dataPath: %s, tocEntryPathSuffix: %s, name: %s\n",
1391 dataPath, tocEntryPathSuffix, name);
1392 }
1393#endif
729e4ab9 1394 retVal = doLoadFromIndividualFiles(pkgName.data(), dataPath, tocEntryPathSuffix,
73c04bcf 1395 path, type, name, isAcceptable, context, &subErrorCode, pErrorCode);
2ca993e8
A
1396#ifdef UDATA_TZFILES_DEBUG
1397 if (isTimeZoneFile(name, type)) {
1398 fprintf(stderr, "# dOC std indiv files, doLoadFromIndividualFiles end; status %d, retVal %p\n", *pErrorCode, retVal);
1399 }
1400#endif
73c04bcf 1401 if((retVal != NULL) || U_FAILURE(*pErrorCode)) {
729e4ab9 1402 return retVal;
374ca955 1403 }
374ca955 1404 }
b75a7d8f
A
1405 }
1406
73c04bcf
A
1407 /**** COMMON PACKAGE */
1408 if((gDataFileAccess==UDATA_ONLY_PACKAGES) ||
1409 (gDataFileAccess==UDATA_FILES_FIRST)) {
b75a7d8f 1410#ifdef UDATA_DEBUG
73c04bcf 1411 fprintf(stderr, "Trying packages (UDATA_ONLY_PACKAGES || UDATA_FILES_FIRST)\n");
2ca993e8
A
1412#endif
1413#ifdef UDATA_TZFILES_DEBUG
1414 if (isTimeZoneFile(name, type)) {
1415 fprintf(stderr, "# dOC std common 2, doLoadFromCommonData start; U_TIMEZONE_PACKAGE: path: %s, tocEntryName.data(): %s, name: %s\n",
1416 path, tocEntryName.data(), name);
1417 }
b75a7d8f 1418#endif
729e4ab9
A
1419 retVal = doLoadFromCommonData(isICUData,
1420 pkgName.data(), dataPath, tocEntryPathSuffix, tocEntryName.data(),
73c04bcf 1421 path, type, name, isAcceptable, context, &subErrorCode, pErrorCode);
2ca993e8
A
1422#ifdef UDATA_TZFILES_DEBUG
1423 if (isTimeZoneFile(name, type)) {
1424 fprintf(stderr, "# dOC std common 2, doLoadFromCommonData end; status %d, retVal %p\n", *pErrorCode, retVal);
1425 }
1426#endif
73c04bcf 1427 if((retVal != NULL) || U_FAILURE(*pErrorCode)) {
729e4ab9 1428 return retVal;
73c04bcf
A
1429 }
1430 }
1431
1432 /* Load from DLL. If we haven't attempted package load, we also haven't had any chance to
1433 try a DLL (static or setCommonData/etc) load.
1434 If we ever have a "UDATA_ONLY_FILES", add it to the or list here. */
1435 if(gDataFileAccess==UDATA_NO_FILES) {
b75a7d8f 1436#ifdef UDATA_DEBUG
73c04bcf 1437 fprintf(stderr, "Trying common data (UDATA_NO_FILES)\n");
b75a7d8f 1438#endif
729e4ab9
A
1439 retVal = doLoadFromCommonData(isICUData,
1440 pkgName.data(), "", tocEntryPathSuffix, tocEntryName.data(),
73c04bcf
A
1441 path, type, name, isAcceptable, context, &subErrorCode, pErrorCode);
1442 if((retVal != NULL) || U_FAILURE(*pErrorCode)) {
729e4ab9 1443 return retVal;
b75a7d8f
A
1444 }
1445 }
1446
1447 /* data not found */
1448 if(U_SUCCESS(*pErrorCode)) {
73c04bcf 1449 if(U_SUCCESS(subErrorCode)) {
b75a7d8f
A
1450 /* file not found */
1451 *pErrorCode=U_FILE_ACCESS_ERROR;
1452 } else {
1453 /* entry point not found or rejected */
73c04bcf 1454 *pErrorCode=subErrorCode;
b75a7d8f
A
1455 }
1456 }
374ca955 1457 return retVal;
b75a7d8f
A
1458}
1459
1460
1461
1462/* API ---------------------------------------------------------------------- */
1463
1464U_CAPI UDataMemory * U_EXPORT2
1465udata_open(const char *path, const char *type, const char *name,
1466 UErrorCode *pErrorCode) {
1467#ifdef UDATA_DEBUG
374ca955 1468 fprintf(stderr, "udata_open(): Opening: %s : %s . %s\n", (path?path:"NULL"), name, type);
b75a7d8f
A
1469 fflush(stderr);
1470#endif
1471
1472 if(pErrorCode==NULL || U_FAILURE(*pErrorCode)) {
1473 return NULL;
1474 } else if(name==NULL || *name==0) {
1475 *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
1476 return NULL;
1477 } else {
1478 return doOpenChoice(path, type, name, NULL, NULL, pErrorCode);
1479 }
1480}
1481
1482
1483
1484U_CAPI UDataMemory * U_EXPORT2
1485udata_openChoice(const char *path, const char *type, const char *name,
1486 UDataMemoryIsAcceptable *isAcceptable, void *context,
1487 UErrorCode *pErrorCode) {
1488#ifdef UDATA_DEBUG
374ca955 1489 fprintf(stderr, "udata_openChoice(): Opening: %s : %s . %s\n", (path?path:"NULL"), name, type);
b75a7d8f
A
1490#endif
1491
1492 if(pErrorCode==NULL || U_FAILURE(*pErrorCode)) {
1493 return NULL;
1494 } else if(name==NULL || *name==0 || isAcceptable==NULL) {
1495 *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
1496 return NULL;
1497 } else {
1498 return doOpenChoice(path, type, name, isAcceptable, context, pErrorCode);
1499 }
1500}
1501
1502
1503
1504U_CAPI void U_EXPORT2
1505udata_getInfo(UDataMemory *pData, UDataInfo *pInfo) {
1506 if(pInfo!=NULL) {
1507 if(pData!=NULL && pData->pHeader!=NULL) {
1508 const UDataInfo *info=&pData->pHeader->info;
374ca955
A
1509 uint16_t dataInfoSize=udata_getInfoSize(info);
1510 if(pInfo->size>dataInfoSize) {
1511 pInfo->size=dataInfoSize;
1512 }
1513 uprv_memcpy((uint16_t *)pInfo+1, (const uint16_t *)info+1, pInfo->size-2);
1514 if(info->isBigEndian!=U_IS_BIG_ENDIAN) {
1515 /* opposite endianness */
1516 uint16_t x=info->reservedWord;
1517 pInfo->reservedWord=(uint16_t)((x<<8)|(x>>8));
b75a7d8f 1518 }
b75a7d8f
A
1519 } else {
1520 pInfo->size=0;
1521 }
1522 }
1523}
73c04bcf
A
1524
1525
729e4ab9 1526U_CAPI void U_EXPORT2 udata_setFileAccess(UDataFileAccess access, UErrorCode * /*status*/)
73c04bcf 1527{
2ca993e8 1528 // Note: this function is documented as not thread safe.
73c04bcf
A
1529 gDataFileAccess = access;
1530}