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