2 ******************************************************************************
4 * Copyright (C) 1999-2014, International Business Machines
5 * Corporation and others. All Rights Reserved.
7 ******************************************************************************
10 * tab size: 8 (not used)
13 * created on: 1999oct25
14 * created by: Markus W. Scherer
17 #include "unicode/utypes.h" /* U_PLATFORM etc. */
21 #define ATTRIBUTE_WEAK __attribute__ ((weak))
22 might have to #include some other header
26 #include "unicode/putil.h"
27 #include "unicode/udata.h"
28 #include "unicode/uversion.h"
41 /***********************************************************************
43 * Notes on the organization of the ICU data implementation
45 * All of the public API is defined in udata.h
47 * The implementation is split into several files...
49 * - udata.c (this file) contains higher level code that knows about
50 * the search paths for locating data, caching opened data, etc.
52 * - umapfile.c contains the low level platform-specific code for actually loading
53 * (memory mapping, file reading, whatever) data into memory.
55 * - ucmndata.c deals with the tables of contents of ICU data items within
56 * an ICU common format data file. The implementation includes
57 * an abstract interface and support for multiple TOC formats.
58 * All knowledge of any specific TOC format is encapsulated here.
60 * - udatamem.c has code for managing UDataMemory structs. These are little
61 * descriptor objects for blocks of memory holding ICU data of
65 /* configuration ---------------------------------------------------------- */
67 /* If you are excruciatingly bored turn this on .. */
68 /* #define UDATA_DEBUG 1 */
70 #if defined(UDATA_DEBUG)
77 * Forward declarations
79 static UDataMemory
*udata_findCachedData(const char *path
);
81 /***********************************************************************
83 * static (Global) data
85 ************************************************************************/
88 * Pointers to the common ICU data.
90 * We store multiple pointers to ICU data packages and iterate through them
91 * when looking for a data item.
93 * It is possible to combine this with dependency inversion:
94 * One or more data package libraries may export
95 * functions that each return a pointer to their piece of the ICU data,
96 * and this file would import them as weak functions, without a
97 * strong linker dependency from the common library on the data library.
99 * Then we can have applications depend on only that part of ICU's data
100 * that they really need, reducing the size of binaries that take advantage
103 static UDataMemory
*gCommonICUDataArray
[10] = { NULL
};
105 static UBool gHaveTriedToLoadCommonData
= FALSE
; /* See extendICUData(). */
107 static UHashtable
*gCommonDataCache
= NULL
; /* Global hash table of opened ICU data files. */
108 static icu::UInitOnce gCommonDataCacheInitOnce
= U_INITONCE_INITIALIZER
;
110 static UDataFileAccess gDataFileAccess
= UDATA_DEFAULT_ACCESS
;
112 static UBool U_CALLCONV
117 if (gCommonDataCache
) { /* Delete the cache of user data mappings. */
118 uhash_close(gCommonDataCache
); /* Table owns the contents, and will delete them. */
119 gCommonDataCache
= NULL
; /* Cleanup is not thread safe. */
121 gCommonDataCacheInitOnce
.reset();
123 for (i
= 0; i
< UPRV_LENGTHOF(gCommonICUDataArray
) && gCommonICUDataArray
[i
] != NULL
; ++i
) {
124 udata_close(gCommonICUDataArray
[i
]);
125 gCommonICUDataArray
[i
] = NULL
;
127 gHaveTriedToLoadCommonData
= FALSE
;
129 return TRUE
; /* Everything was cleaned up */
132 static UBool U_CALLCONV
133 findCommonICUDataByName(const char *inBasename
)
138 UDataMemory
*pData
= udata_findCachedData(inBasename
);
142 for (i
= 0; i
< UPRV_LENGTHOF(gCommonICUDataArray
); ++i
) {
143 if ((gCommonICUDataArray
[i
] != NULL
) && (gCommonICUDataArray
[i
]->pHeader
== pData
->pHeader
)) {
144 /* The data pointer is already in the array. */
155 * setCommonICUData. Set a UDataMemory to be the global ICU Data
158 setCommonICUData(UDataMemory
*pData
, /* The new common data. Belongs to caller, we copy it. */
159 UBool warn
, /* If true, set USING_DEFAULT warning if ICUData was */
160 /* changed by another thread before we got to it. */
163 UDataMemory
*newCommonData
= UDataMemory_createNewInstance(pErr
);
165 UBool didUpdate
= FALSE
;
166 if (U_FAILURE(*pErr
)) {
170 /* For the assignment, other threads must cleanly see either the old */
171 /* or the new, not some partially initialized new. The old can not be */
172 /* deleted - someone may still have a pointer to it lying around in */
174 UDatamemory_assign(newCommonData
, pData
);
176 for (i
= 0; i
< UPRV_LENGTHOF(gCommonICUDataArray
); ++i
) {
177 if (gCommonICUDataArray
[i
] == NULL
) {
178 gCommonICUDataArray
[i
] = newCommonData
;
181 } else if (gCommonICUDataArray
[i
]->pHeader
== pData
->pHeader
) {
182 /* The same data pointer is already in the array. */
188 if (i
== UPRV_LENGTHOF(gCommonICUDataArray
) && warn
) {
189 *pErr
= U_USING_DEFAULT_WARNING
;
192 ucln_common_registerCleanup(UCLN_COMMON_UDATA
, udata_cleanup
);
194 uprv_free(newCommonData
);
200 setCommonICUDataPointer(const void *pData
, UBool
/*warn*/, UErrorCode
*pErrorCode
) {
202 UDataMemory_init(&tData
);
203 UDataMemory_setData(&tData
, pData
);
204 udata_checkCommonData(&tData
, pErrorCode
);
205 return setCommonICUData(&tData
, FALSE
, pErrorCode
);
209 findBasename(const char *path
) {
210 const char *basename
=uprv_strrchr(path
, U_FILE_SEP_CHAR
);
220 packageNameFromPath(const char *path
)
222 if((path
== NULL
) || (*path
== 0)) {
223 return U_ICUDATA_NAME
;
226 path
= findBasename(path
);
228 if((path
== NULL
) || (*path
== 0)) {
229 return U_ICUDATA_NAME
;
236 /*----------------------------------------------------------------------*
238 * Cache for common data *
239 * Functions for looking up or adding entries to a cache of *
240 * data that has been previously opened. Avoids a potentially *
241 * expensive operation of re-opening the data for subsequent *
244 * Data remains cached for the duration of the process. *
246 *----------------------------------------------------------------------*/
248 typedef struct DataCacheElement
{
256 * Deleter function for DataCacheElements.
257 * udata cleanup function closes the hash table; hash table in turn calls back to
258 * here for each entry.
260 static void U_CALLCONV
DataCacheElement_deleter(void *pDCEl
) {
261 DataCacheElement
*p
= (DataCacheElement
*)pDCEl
;
262 udata_close(p
->item
); /* unmaps storage */
263 uprv_free(p
->name
); /* delete the hash key string. */
264 uprv_free(pDCEl
); /* delete 'this' */
267 static void udata_initHashTable() {
268 UErrorCode err
= U_ZERO_ERROR
;
269 U_ASSERT(gCommonDataCache
== NULL
);
270 gCommonDataCache
= uhash_open(uhash_hashChars
, uhash_compareChars
, NULL
, &err
);
271 if (U_FAILURE(err
)) {
272 // TODO: handle errors better.
273 gCommonDataCache
= NULL
;
275 if (gCommonDataCache
!= NULL
) {
276 uhash_setValueDeleter(gCommonDataCache
, DataCacheElement_deleter
);
277 ucln_common_registerCleanup(UCLN_COMMON_UDATA
, udata_cleanup
);
281 /* udata_getCacheHashTable()
282 * Get the hash table used to store the data cache entries.
283 * Lazy create it if it doesn't yet exist.
285 static UHashtable
*udata_getHashTable() {
286 umtx_initOnce(gCommonDataCacheInitOnce
, &udata_initHashTable
);
287 return gCommonDataCache
;
292 static UDataMemory
*udata_findCachedData(const char *path
)
295 UDataMemory
*retVal
= NULL
;
296 DataCacheElement
*el
;
297 const char *baseName
;
299 baseName
= findBasename(path
); /* Cache remembers only the base name, not the full path. */
300 htable
= udata_getHashTable();
302 el
= (DataCacheElement
*)uhash_get(htable
, baseName
);
308 fprintf(stderr
, "Cache: [%s] -> %p\n", baseName
, retVal
);
314 static UDataMemory
*udata_cacheDataItem(const char *path
, UDataMemory
*item
, UErrorCode
*pErr
) {
315 DataCacheElement
*newElement
;
316 const char *baseName
;
319 DataCacheElement
*oldValue
= NULL
;
320 UErrorCode subErr
= U_ZERO_ERROR
;
322 if (U_FAILURE(*pErr
)) {
326 /* Create a new DataCacheElement - the thingy we store in the hash table -
327 * and copy the supplied path and UDataMemoryItems into it.
329 newElement
= (DataCacheElement
*)uprv_malloc(sizeof(DataCacheElement
));
330 if (newElement
== NULL
) {
331 *pErr
= U_MEMORY_ALLOCATION_ERROR
;
334 newElement
->item
= UDataMemory_createNewInstance(pErr
);
335 if (U_FAILURE(*pErr
)) {
336 uprv_free(newElement
);
339 UDatamemory_assign(newElement
->item
, item
);
341 baseName
= findBasename(path
);
342 nameLen
= (int32_t)uprv_strlen(baseName
);
343 newElement
->name
= (char *)uprv_malloc(nameLen
+1);
344 if (newElement
->name
== NULL
) {
345 *pErr
= U_MEMORY_ALLOCATION_ERROR
;
346 uprv_free(newElement
->item
);
347 uprv_free(newElement
);
350 uprv_strcpy(newElement
->name
, baseName
);
352 /* Stick the new DataCacheElement into the hash table.
354 htable
= udata_getHashTable();
356 oldValue
= (DataCacheElement
*)uhash_get(htable
, path
);
357 if (oldValue
!= NULL
) {
358 subErr
= U_USING_DEFAULT_WARNING
;
363 newElement
->name
, /* Key */
364 newElement
, /* Value */
370 fprintf(stderr
, "Cache: [%s] <<< %p : %s. vFunc=%p\n", newElement
->name
,
371 newElement
->item
, u_errorName(subErr
), newElement
->item
->vFuncs
);
374 if (subErr
== U_USING_DEFAULT_WARNING
|| U_FAILURE(subErr
)) {
375 *pErr
= subErr
; /* copy sub err unto fillin ONLY if something happens. */
376 uprv_free(newElement
->name
);
377 uprv_free(newElement
->item
);
378 uprv_free(newElement
);
379 return oldValue
? oldValue
->item
: NULL
;
382 return newElement
->item
;
385 /*----------------------------------------------------------------------*==============
387 * Path management. Could be shared with other tools/etc if need be *
390 *----------------------------------------------------------------------*/
392 #define U_DATA_PATHITER_BUFSIZ 128 /* Size of local buffer for paths */
393 /* Overflow causes malloc of larger buf */
397 class UDataPathIterator
400 UDataPathIterator(const char *path
, const char *pkg
,
401 const char *item
, const char *suffix
, UBool doCheckLastFour
,
402 UErrorCode
*pErrorCode
);
403 const char *next(UErrorCode
*pErrorCode
);
406 const char *path
; /* working path (u_icudata_Dir) */
407 const char *nextPath
; /* path following this one */
408 const char *basename
; /* item's basename (icudt22e_mt.res)*/
409 const char *suffix
; /* item suffix (can be null) */
411 uint32_t basenameLen
; /* length of basename */
413 CharString itemPath
; /* path passed in with item name */
414 CharString pathBuffer
; /* output path for this it'ion */
415 CharString packageStub
; /* example: "/icudt28b". Will ignore that leaf in set paths. */
417 UBool checkLastFour
; /* if TRUE then allow paths such as '/foo/myapp.dat'
418 * to match, checks last 4 chars of suffix with
419 * last 4 of path, then previous chars. */
423 * @param iter The iterator to be initialized. Its current state does not matter.
424 * @param path The full pathname to be iterated over. If NULL, defaults to U_ICUDATA_NAME
425 * @param pkg Package which is being searched for, ex "icudt28l". Will ignore leave directories such as /icudt28l
426 * @param item Item to be searched for. Can include full path, such as /a/b/foo.dat
427 * @param suffix Optional item suffix, if not-null (ex. ".dat") then 'path' can contain 'item' explicitly.
428 * Ex: 'stuff.dat' would be found in '/a/foo:/tmp/stuff.dat:/bar/baz' as item #2.
429 * '/blarg/stuff.dat' would also be found.
431 UDataPathIterator::UDataPathIterator(const char *inPath
, const char *pkg
,
432 const char *item
, const char *inSuffix
, UBool doCheckLastFour
,
433 UErrorCode
*pErrorCode
)
436 fprintf(stderr
, "SUFFIX1=%s PATH=%s\n", inSuffix
, inPath
);
440 path
= u_getDataDirectory();
447 packageStub
.append(U_FILE_SEP_CHAR
, *pErrorCode
).append(pkg
, *pErrorCode
);
449 fprintf(stderr
, "STUB=%s [%d]\n", packageStub
.data(), packageStub
.length());
454 basename
= findBasename(item
);
455 basenameLen
= (int32_t)uprv_strlen(basename
);
458 if(basename
== item
) {
461 itemPath
.append(item
, (int32_t)(basename
-item
), *pErrorCode
);
462 nextPath
= itemPath
.data();
465 fprintf(stderr
, "SUFFIX=%s [%p]\n", inSuffix
, inSuffix
);
469 if(inSuffix
!= NULL
) {
475 checkLastFour
= doCheckLastFour
;
477 /* pathBuffer will hold the output path strings returned by this iterator */
480 fprintf(stderr
, "%p: init %s -> [path=%s], [base=%s], [suff=%s], [itempath=%s], [nextpath=%s], [checklast4=%s]\n",
488 checkLastFour
?"TRUE":"false");
493 * Get the next path on the list.
495 * @param iter The Iter to be used
496 * @param len If set, pointer to the length of the returned path, for convenience.
497 * @return Pointer to the next path segment, or NULL if there are no more.
499 const char *UDataPathIterator::next(UErrorCode
*pErrorCode
)
501 if(U_FAILURE(*pErrorCode
)) {
505 const char *currentPath
= NULL
;
507 const char *pathBasename
;
511 if( nextPath
== NULL
) {
514 currentPath
= nextPath
;
516 if(nextPath
== itemPath
.data()) { /* we were processing item's path. */
517 nextPath
= path
; /* start with regular path next tm. */
518 pathLen
= (int32_t)uprv_strlen(currentPath
);
520 /* fix up next for next time */
521 nextPath
= uprv_strchr(currentPath
, U_PATH_SEP_CHAR
);
522 if(nextPath
== NULL
) {
523 /* segment: entire path */
524 pathLen
= (int32_t)uprv_strlen(currentPath
);
526 /* segment: until next segment */
527 pathLen
= (int32_t)(nextPath
- currentPath
);
538 fprintf(stderr
, "rest of path (IDD) = %s\n", currentPath
);
539 fprintf(stderr
, " ");
542 for(qqq
=0;qqq
<pathLen
;qqq
++)
544 fprintf(stderr
, " ");
547 fprintf(stderr
, "^\n");
550 pathBuffer
.clear().append(currentPath
, pathLen
, *pErrorCode
);
552 /* check for .dat files */
553 pathBasename
= findBasename(pathBuffer
.data());
555 if(checkLastFour
== TRUE
&&
557 uprv_strncmp(pathBuffer
.data() +(pathLen
-4), suffix
, 4)==0 && /* suffix matches */
558 uprv_strncmp(findBasename(pathBuffer
.data()), basename
, basenameLen
)==0 && /* base matches */
559 uprv_strlen(pathBasename
)==(basenameLen
+4)) { /* base+suffix = full len */
562 fprintf(stderr
, "Have %s file on the path: %s\n", suffix
, pathBuffer
.data());
567 { /* regular dir path */
568 if(pathBuffer
[pathLen
-1] != U_FILE_SEP_CHAR
) {
570 uprv_strncmp(pathBuffer
.data()+(pathLen
-4), ".dat", 4) == 0)
573 fprintf(stderr
, "skipping non-directory .dat file %s\n", pathBuffer
.data());
578 /* Check if it is a directory with the same name as our package */
579 if(!packageStub
.isEmpty() &&
580 (pathLen
> packageStub
.length()) &&
581 !uprv_strcmp(pathBuffer
.data() + pathLen
- packageStub
.length(), packageStub
.data())) {
583 fprintf(stderr
, "Found stub %s (will add package %s of len %d)\n", packageStub
.data(), basename
, basenameLen
);
585 pathBuffer
.truncate(pathLen
- packageStub
.length());
587 pathBuffer
.append(U_FILE_SEP_CHAR
, *pErrorCode
);
591 pathBuffer
.append(packageStub
.data()+1, packageStub
.length()-1, *pErrorCode
);
593 if(*suffix
) /* tack on suffix */
595 pathBuffer
.append(suffix
, *pErrorCode
);
600 fprintf(stderr
, " --> %s\n", pathBuffer
.data());
603 return pathBuffer
.data();
607 /* fell way off the end */
613 /* ==================================================================================*/
616 /*----------------------------------------------------------------------*
618 * Add a static reference to the common data library *
619 * Unless overridden by an explicit udata_setCommonData, this will be *
622 *----------------------------------------------------------------------*/
623 extern "C" const DataHeader U_DATA_API U_ICUDATA_ENTRY_POINT
;
626 * This would be a good place for weak-linkage declarations of
627 * partial-data-library access functions where each returns a pointer
628 * to its data package, if it is linked in.
631 extern const void *uprv_getICUData_collation(void) ATTRIBUTE_WEAK;
632 extern const void *uprv_getICUData_conversion(void) ATTRIBUTE_WEAK;
635 /*----------------------------------------------------------------------*
637 * openCommonData Attempt to open a common format (.dat) file *
638 * Map it into memory (if it's not there already) *
639 * and return a UDataMemory object for it. *
641 * If the requested data is already open and cached *
642 * just return the cached UDataMem object. *
644 *----------------------------------------------------------------------*/
646 openCommonData(const char *path
, /* Path from OpenChoice? */
647 int32_t commonDataIndex
, /* ICU Data (index >= 0) if path == NULL */
648 UErrorCode
*pErrorCode
)
651 const char *pathBuffer
;
652 const char *inBasename
;
654 if (U_FAILURE(*pErrorCode
)) {
658 UDataMemory_init(&tData
);
660 /* ??????? TODO revisit this */
661 if (commonDataIndex
>= 0) {
662 /* "mini-cache" for common ICU data */
663 if(commonDataIndex
>= UPRV_LENGTHOF(gCommonICUDataArray
)) {
666 if(gCommonICUDataArray
[commonDataIndex
] == NULL
) {
668 for(i
= 0; i
< commonDataIndex
; ++i
) {
669 if(gCommonICUDataArray
[i
]->pHeader
== &U_ICUDATA_ENTRY_POINT
) {
670 /* The linked-in data is already in the list. */
675 /* Add the linked-in data to the list. */
677 * This is where we would check and call weakly linked partial-data-library
681 if (uprv_getICUData_collation) {
682 setCommonICUDataPointer(uprv_getICUData_collation(), FALSE, pErrorCode);
684 if (uprv_getICUData_conversion) {
685 setCommonICUDataPointer(uprv_getICUData_conversion(), FALSE, pErrorCode);
688 setCommonICUDataPointer(&U_ICUDATA_ENTRY_POINT
, FALSE
, pErrorCode
);
690 return gCommonICUDataArray
[commonDataIndex
];
694 /* request is NOT for ICU Data. */
696 /* Find the base name portion of the supplied path. */
697 /* inBasename will be left pointing somewhere within the original path string. */
698 inBasename
= findBasename(path
);
700 fprintf(stderr
, "inBasename = %s\n", inBasename
);
704 /* no basename. This will happen if the original path was a directory name, */
705 /* like "a/b/c/". (Fallback to separate files will still work.) */
707 fprintf(stderr
, "ocd: no basename in %s, bailing.\n", path
);
709 *pErrorCode
=U_FILE_ACCESS_ERROR
;
713 /* Is the requested common data file already open and cached? */
714 /* Note that the cache is keyed by the base name only. The rest of the path, */
715 /* if any, is not considered. */
717 UDataMemory
*dataToReturn
= udata_findCachedData(inBasename
);
718 if (dataToReturn
!= NULL
) {
723 /* Requested item is not in the cache.
724 * Hunt it down, trying all the path locations
727 UDataPathIterator
iter(u_getDataDirectory(), inBasename
, path
, ".dat", TRUE
, pErrorCode
);
729 while((UDataMemory_isLoaded(&tData
)==FALSE
) && (pathBuffer
= iter
.next(pErrorCode
)) != NULL
)
732 fprintf(stderr
, "ocd: trying path %s - ", pathBuffer
);
734 uprv_mapFile(&tData
, pathBuffer
);
736 fprintf(stderr
, "%s\n", UDataMemory_isLoaded(&tData
)?"LOADED":"not loaded");
740 #if defined(OS390_STUBDATA) && defined(OS390BATCH)
741 if (!UDataMemory_isLoaded(&tData
)) {
742 char ourPathBuffer
[1024];
743 /* One more chance, for extendCommonData() */
744 uprv_strncpy(ourPathBuffer
, path
, 1019);
745 ourPathBuffer
[1019]=0;
746 uprv_strcat(ourPathBuffer
, ".dat");
747 uprv_mapFile(&tData
, ourPathBuffer
);
751 if (!UDataMemory_isLoaded(&tData
)) {
753 *pErrorCode
=U_FILE_ACCESS_ERROR
;
757 /* we have mapped a file, check its header */
758 udata_checkCommonData(&tData
, pErrorCode
);
761 /* Cache the UDataMemory struct for this .dat file,
762 * so we won't need to hunt it down and map it again next time
763 * something is needed from it. */
764 return udata_cacheDataItem(inBasename
, &tData
, pErrorCode
);
768 /*----------------------------------------------------------------------*
770 * extendICUData If the full set of ICU data was not loaded at *
771 * program startup, load it now. This function will *
772 * be called when the lookup of an ICU data item in *
773 * the common ICU data fails. *
775 * return true if new data is loaded, false otherwise.*
777 *----------------------------------------------------------------------*/
778 static UBool
extendICUData(UErrorCode
*pErr
)
781 UDataMemory copyPData
;
782 UBool didUpdate
= FALSE
;
785 * There is a chance for a race condition here.
786 * Normally, ICU data is loaded from a DLL or via mmap() and
787 * setCommonICUData() will detect if the same address is set twice.
788 * If ICU is built with data loading via fread() then the address will
789 * be different each time the common data is loaded and we may add
790 * multiple copies of the data.
791 * In this case, use a mutex to prevent the race.
792 * Use a specific mutex to avoid nested locks of the global mutex.
794 #if MAP_IMPLEMENTATION==MAP_STDIO
795 static UMutex extendICUDataMutex
= U_MUTEX_INITIALIZER
;
796 umtx_lock(&extendICUDataMutex
);
798 if(!gHaveTriedToLoadCommonData
) {
799 /* See if we can explicitly open a .dat file for the ICUData. */
800 pData
= openCommonData(
801 U_ICUDATA_NAME
, /* "icudt20l" , for example. */
802 -1, /* Pretend we're not opening ICUData */
805 /* How about if there is no pData, eh... */
807 UDataMemory_init(©PData
);
809 UDatamemory_assign(©PData
, pData
);
810 copyPData
.map
= 0; /* The mapping for this data is owned by the hash table */
811 copyPData
.mapAddr
= 0; /* which will unmap it when ICU is shut down. */
812 /* CommonICUData is also unmapped when ICU is shut down.*/
813 /* To avoid unmapping the data twice, zero out the map */
814 /* fields in the UDataMemory that we're assigning */
815 /* to CommonICUData. */
817 didUpdate
= /* no longer using this result */
818 setCommonICUData(©PData
,/* The new common data. */
819 FALSE
, /* No warnings if write didn't happen */
820 pErr
); /* setCommonICUData honors errors; NOP if error set */
823 gHaveTriedToLoadCommonData
= TRUE
;
826 didUpdate
= findCommonICUDataByName(U_ICUDATA_NAME
); /* Return 'true' when a racing writes out the extended */
827 /* data after another thread has failed to see it (in openCommonData), so */
828 /* extended data can be examined. */
829 /* Also handles a race through here before gHaveTriedToLoadCommonData is set. */
831 #if MAP_IMPLEMENTATION==MAP_STDIO
832 umtx_unlock(&extendICUDataMutex
);
834 return didUpdate
; /* Return true if ICUData pointer was updated. */
835 /* (Could potentialy have been done by another thread racing */
836 /* us through here, but that's fine, we still return true */
837 /* so that current thread will also examine extended data. */
840 /*----------------------------------------------------------------------*
842 * udata_setCommonData *
844 *----------------------------------------------------------------------*/
845 U_CAPI
void U_EXPORT2
846 udata_setCommonData(const void *data
, UErrorCode
*pErrorCode
) {
847 UDataMemory dataMemory
;
849 if(pErrorCode
==NULL
|| U_FAILURE(*pErrorCode
)) {
854 *pErrorCode
=U_ILLEGAL_ARGUMENT_ERROR
;
858 /* set the data pointer and test for validity */
859 UDataMemory_init(&dataMemory
);
860 UDataMemory_setData(&dataMemory
, data
);
861 udata_checkCommonData(&dataMemory
, pErrorCode
);
862 if (U_FAILURE(*pErrorCode
)) {return;}
864 /* we have good data */
865 /* Set it up as the ICU Common Data. */
866 setCommonICUData(&dataMemory
, TRUE
, pErrorCode
);
869 /*---------------------------------------------------------------------------
873 *---------------------------------------------------------------------------- */
874 U_CAPI
void U_EXPORT2
875 udata_setAppData(const char *path
, const void *data
, UErrorCode
*err
)
879 if(err
==NULL
|| U_FAILURE(*err
)) {
883 *err
=U_ILLEGAL_ARGUMENT_ERROR
;
887 UDataMemory_init(&udm
);
888 UDataMemory_setData(&udm
, data
);
889 udata_checkCommonData(&udm
, err
);
890 udata_cacheDataItem(path
, &udm
, err
);
893 /*----------------------------------------------------------------------------*
895 * checkDataItem Given a freshly located/loaded data item, either *
896 * an entry in a common file or a separately loaded file, *
897 * sanity check its header, and see if the data is *
898 * acceptable to the app. *
899 * If the data is good, create and return a UDataMemory *
900 * object that can be returned to the application. *
901 * Return NULL on any sort of failure. *
903 *----------------------------------------------------------------------------*/
907 const DataHeader
*pHeader
, /* The data item to be checked. */
908 UDataMemoryIsAcceptable
*isAcceptable
, /* App's call-back function */
909 void *context
, /* pass-thru param for above. */
910 const char *type
, /* pass-thru param for above. */
911 const char *name
, /* pass-thru param for above. */
912 UErrorCode
*nonFatalErr
, /* Error code if this data was not acceptable */
913 /* but openChoice should continue with */
914 /* trying to get data from fallback path. */
915 UErrorCode
*fatalErr
/* Bad error, caller should return immediately */
918 UDataMemory
*rDataMem
= NULL
; /* the new UDataMemory, to be returned. */
920 if (U_FAILURE(*fatalErr
)) {
924 if(pHeader
->dataHeader
.magic1
==0xda &&
925 pHeader
->dataHeader
.magic2
==0x27 &&
926 (isAcceptable
==NULL
|| isAcceptable(context
, type
, name
, &pHeader
->info
))
928 rDataMem
=UDataMemory_createNewInstance(fatalErr
);
929 if (U_FAILURE(*fatalErr
)) {
932 rDataMem
->pHeader
= pHeader
;
934 /* the data is not acceptable, look further */
935 /* If we eventually find something good, this errorcode will be */
937 *nonFatalErr
=U_INVALID_FORMAT_ERROR
;
943 * @return 0 if not loaded, 1 if loaded or err
945 static UDataMemory
*doLoadFromIndividualFiles(const char *pkgName
,
946 const char *dataPath
, const char *tocEntryPathSuffix
,
947 /* following arguments are the same as doOpenChoice itself */
948 const char *path
, const char *type
, const char *name
,
949 UDataMemoryIsAcceptable
*isAcceptable
, void *context
,
950 UErrorCode
*subErrorCode
,
951 UErrorCode
*pErrorCode
)
953 const char *pathBuffer
;
954 UDataMemory dataMemory
;
955 UDataMemory
*pEntryData
;
957 /* look in ind. files: package\nam.typ ========================= */
958 /* init path iterator for individual files */
959 UDataPathIterator
iter(dataPath
, pkgName
, path
, tocEntryPathSuffix
, FALSE
, pErrorCode
);
961 while((pathBuffer
= iter
.next(pErrorCode
)))
964 fprintf(stderr
, "UDATA: trying individual file %s\n", pathBuffer
);
966 if(uprv_mapFile(&dataMemory
, pathBuffer
))
968 pEntryData
= checkDataItem(dataMemory
.pHeader
, isAcceptable
, context
, type
, name
, subErrorCode
, pErrorCode
);
969 if (pEntryData
!= NULL
) {
971 * Hand off ownership of the backing memory to the user's UDataMemory.
973 pEntryData
->mapAddr
= dataMemory
.mapAddr
;
974 pEntryData
->map
= dataMemory
.map
;
977 fprintf(stderr
, "** Mapped file: %s\n", pathBuffer
);
982 /* the data is not acceptable, or some error occured. Either way, unmap the memory */
983 udata_close(&dataMemory
);
985 /* If we had a nasty error, bail out completely. */
986 if (U_FAILURE(*pErrorCode
)) {
990 /* Otherwise remember that we found data but didn't like it for some reason */
991 *subErrorCode
=U_INVALID_FORMAT_ERROR
;
994 fprintf(stderr
, "%s\n", UDataMemory_isLoaded(&dataMemory
)?"LOADED":"not loaded");
1001 * @return 0 if not loaded, 1 if loaded or err
1003 static UDataMemory
*doLoadFromCommonData(UBool isICUData
, const char * /*pkgName*/,
1004 const char * /*dataPath*/, const char * /*tocEntryPathSuffix*/, const char *tocEntryName
,
1005 /* following arguments are the same as doOpenChoice itself */
1006 const char *path
, const char *type
, const char *name
,
1007 UDataMemoryIsAcceptable
*isAcceptable
, void *context
,
1008 UErrorCode
*subErrorCode
,
1009 UErrorCode
*pErrorCode
)
1011 UDataMemory
*pEntryData
;
1012 const DataHeader
*pHeader
;
1013 UDataMemory
*pCommonData
;
1014 int32_t commonDataIndex
;
1015 UBool checkedExtendedICUData
= FALSE
;
1016 /* try to get common data. The loop is for platforms such as the 390 that do
1017 * not initially load the full set of ICU data. If the lookup of an ICU data item
1018 * fails, the full (but slower to load) set is loaded, the and the loop repeats,
1019 * trying the lookup again. Once the full set of ICU data is loaded, the loop wont
1020 * repeat because the full set will be checked the first time through.
1022 * The loop also handles the fallback to a .dat file if the application linked
1023 * to the stub data library rather than a real library.
1025 for (commonDataIndex
= isICUData
? 0 : -1;;) {
1026 pCommonData
=openCommonData(path
, commonDataIndex
, subErrorCode
); /** search for pkg **/
1028 if(U_SUCCESS(*subErrorCode
) && pCommonData
!=NULL
) {
1031 /* look up the data piece in the common data */
1032 pHeader
=pCommonData
->vFuncs
->Lookup(pCommonData
, tocEntryName
, &length
, subErrorCode
);
1034 fprintf(stderr
, "%s: pHeader=%p - %s\n", tocEntryName
, pHeader
, u_errorName(*subErrorCode
));
1038 pEntryData
= checkDataItem(pHeader
, isAcceptable
, context
, type
, name
, subErrorCode
, pErrorCode
);
1040 fprintf(stderr
, "pEntryData=%p\n", pEntryData
);
1042 if (U_FAILURE(*pErrorCode
)) {
1045 if (pEntryData
!= NULL
) {
1046 pEntryData
->length
= length
;
1051 /* Data wasn't found. If we were looking for an ICUData item and there is
1052 * more data available, load it and try again,
1053 * otherwise break out of this loop. */
1056 } else if (pCommonData
!= NULL
) {
1057 ++commonDataIndex
; /* try the next data package */
1058 } else if ((!checkedExtendedICUData
) && extendICUData(subErrorCode
)) {
1059 checkedExtendedICUData
= TRUE
;
1060 /* try this data package slot again: it changed from NULL to non-NULL */
1068 * Identify the Time Zone resources that are subject to special override data loading.
1070 static UBool
isTimeZoneFile(const char *name
, const char *type
) {
1071 return ((uprv_strcmp(type
, "res") == 0) &&
1072 (uprv_strcmp(name
, "zoneinfo64") == 0 ||
1073 uprv_strcmp(name
, "timezoneTypes") == 0 ||
1074 uprv_strcmp(name
, "windowsZones") == 0 ||
1075 uprv_strcmp(name
, "metaZones") == 0));
1079 * A note on the ownership of Mapped Memory
1081 * For common format files, ownership resides with the UDataMemory object
1082 * that lives in the cache of opened common data. These UDataMemorys are private
1083 * to the udata implementation, and are never seen directly by users.
1085 * The UDataMemory objects returned to users will have the address of some desired
1086 * data within the mapped region, but they wont have the mapping info itself, and thus
1087 * won't cause anything to be removed from memory when they are closed.
1089 * For individual data files, the UDataMemory returned to the user holds the
1090 * information necessary to unmap the data on close. If the user independently
1091 * opens the same data file twice, two completely independent mappings will be made.
1092 * (There is no cache of opened data items from individual files, only a cache of
1093 * opened Common Data files, that is, files containing a collection of data items.)
1095 * For common data passed in from the user via udata_setAppData() or
1096 * udata_setCommonData(), ownership remains with the user.
1098 * UDataMemory objects themselves, as opposed to the memory they describe,
1099 * can be anywhere - heap, stack/local or global.
1100 * They have a flag to indicate when they're heap allocated and thus
1101 * must be deleted when closed.
1105 /*----------------------------------------------------------------------------*
1107 * main data loading functions *
1109 *----------------------------------------------------------------------------*/
1110 static UDataMemory
*
1111 doOpenChoice(const char *path
, const char *type
, const char *name
,
1112 UDataMemoryIsAcceptable
*isAcceptable
, void *context
,
1113 UErrorCode
*pErrorCode
)
1115 UDataMemory
*retVal
= NULL
;
1117 const char *dataPath
;
1119 int32_t tocEntrySuffixIndex
;
1120 const char *tocEntryPathSuffix
;
1121 UErrorCode subErrorCode
=U_ZERO_ERROR
;
1122 const char *treeChar
;
1124 UBool isICUData
= FALSE
;
1127 /* Is this path ICU data? */
1129 !strcmp(path
, U_ICUDATA_ALIAS
) || /* "ICUDATA" */
1130 !uprv_strncmp(path
, U_ICUDATA_NAME U_TREE_SEPARATOR_STRING
, /* "icudt26e-" */
1131 uprv_strlen(U_ICUDATA_NAME U_TREE_SEPARATOR_STRING
)) ||
1132 !uprv_strncmp(path
, U_ICUDATA_ALIAS U_TREE_SEPARATOR_STRING
, /* "ICUDATA-" */
1133 uprv_strlen(U_ICUDATA_ALIAS U_TREE_SEPARATOR_STRING
))) {
1137 #if (U_FILE_SEP_CHAR != U_FILE_ALT_SEP_CHAR) /* Windows: try "foo\bar" and "foo/bar" */
1138 /* remap from alternate path char to the main one */
1139 CharString altSepPath
;
1141 if(uprv_strchr(path
,U_FILE_ALT_SEP_CHAR
) != NULL
) {
1142 altSepPath
.append(path
, *pErrorCode
);
1144 while((p
=uprv_strchr(altSepPath
.data(), U_FILE_ALT_SEP_CHAR
))) {
1145 *p
= U_FILE_SEP_CHAR
;
1147 #if defined (UDATA_DEBUG)
1148 fprintf(stderr
, "Changed path from [%s] to [%s]\n", path
, altSepPath
.s
);
1150 path
= altSepPath
.data();
1155 CharString tocEntryName
; /* entry name in tree format. ex: 'icudt28b/coll/ar.res' */
1156 CharString tocEntryPath
; /* entry name in path format. ex: 'icudt28b\\coll\\ar.res' */
1159 CharString treeName
;
1161 /* ======= Set up strings */
1163 pkgName
.append(U_ICUDATA_NAME
, *pErrorCode
);
1167 pkg
= uprv_strrchr(path
, U_FILE_SEP_CHAR
);
1168 first
= uprv_strchr(path
, U_FILE_SEP_CHAR
);
1169 if(uprv_pathIsAbsolute(path
) || (pkg
!= first
)) { /* more than one slash in the path- not a tree name */
1170 /* see if this is an /absolute/path/to/package path */
1172 pkgName
.append(pkg
+1, *pErrorCode
);
1174 pkgName
.append(path
, *pErrorCode
);
1177 treeChar
= uprv_strchr(path
, U_TREE_SEPARATOR
);
1179 treeName
.append(treeChar
+1, *pErrorCode
); /* following '-' */
1181 pkgName
.append(U_ICUDATA_NAME
, *pErrorCode
);
1183 pkgName
.append(path
, (int32_t)(treeChar
-path
), *pErrorCode
);
1184 if (first
== NULL
) {
1186 This user data has no path, but there is a tree name.
1187 Look up the correct path from the data cache later.
1189 path
= pkgName
.data();
1194 pkgName
.append(U_ICUDATA_NAME
, *pErrorCode
);
1196 pkgName
.append(path
, *pErrorCode
);
1203 fprintf(stderr
, " P=%s T=%s\n", pkgName
.data(), treeName
.data());
1206 /* setting up the entry name and file name
1207 * Make up a full name by appending the type to the supplied
1208 * name, assuming that a type was supplied.
1211 /* prepend the package */
1212 tocEntryName
.append(pkgName
, *pErrorCode
);
1213 tocEntryPath
.append(pkgName
, *pErrorCode
);
1214 tocEntrySuffixIndex
= tocEntryName
.length();
1216 if(!treeName
.isEmpty()) {
1217 tocEntryName
.append(U_TREE_ENTRY_SEP_CHAR
, *pErrorCode
).append(treeName
, *pErrorCode
);
1218 tocEntryPath
.append(U_FILE_SEP_CHAR
, *pErrorCode
).append(treeName
, *pErrorCode
);
1221 tocEntryName
.append(U_TREE_ENTRY_SEP_CHAR
, *pErrorCode
).append(name
, *pErrorCode
);
1222 tocEntryPath
.append(U_FILE_SEP_CHAR
, *pErrorCode
).append(name
, *pErrorCode
);
1223 if(type
!=NULL
&& *type
!=0) {
1224 tocEntryName
.append(".", *pErrorCode
).append(type
, *pErrorCode
);
1225 tocEntryPath
.append(".", *pErrorCode
).append(type
, *pErrorCode
);
1227 tocEntryPathSuffix
= tocEntryPath
.data()+tocEntrySuffixIndex
; /* suffix starts here */
1230 fprintf(stderr
, " tocEntryName = %s\n", tocEntryName
.data());
1231 fprintf(stderr
, " tocEntryPath = %s\n", tocEntryName
.data());
1235 path
= COMMON_DATA_NAME
; /* "icudt26e" */
1238 /************************ Begin loop looking for ind. files ***************/
1240 fprintf(stderr
, "IND: inBasename = %s, pkg=%s\n", "(n/a)", packageNameFromPath(path
));
1243 /* End of dealing with a null basename */
1244 dataPath
= u_getDataDirectory();
1246 /**** Time zone individual files override */
1247 if (isTimeZoneFile(name
, type
) && isICUData
) {
1248 const char *tzFilesDir
= u_getTimeZoneFilesDirectory(pErrorCode
);
1249 if (tzFilesDir
[0] != 0) {
1251 fprintf(stderr
, "Trying Time Zone Files directory = %s\n", tzFilesDir
);
1253 retVal
= doLoadFromIndividualFiles(/* pkgName.data() */ "", tzFilesDir
, tocEntryPathSuffix
,
1254 /* path */ "", type
, name
, isAcceptable
, context
, &subErrorCode
, pErrorCode
);
1255 if((retVal
!= NULL
) || U_FAILURE(*pErrorCode
)) {
1261 /**** COMMON PACKAGE - only if packages are first. */
1262 if(gDataFileAccess
== UDATA_PACKAGES_FIRST
) {
1264 fprintf(stderr
, "Trying packages (UDATA_PACKAGES_FIRST)\n");
1267 retVal
= doLoadFromCommonData(isICUData
,
1268 pkgName
.data(), dataPath
, tocEntryPathSuffix
, tocEntryName
.data(),
1269 path
, type
, name
, isAcceptable
, context
, &subErrorCode
, pErrorCode
);
1270 if((retVal
!= NULL
) || U_FAILURE(*pErrorCode
)) {
1275 /**** INDIVIDUAL FILES */
1276 if((gDataFileAccess
==UDATA_PACKAGES_FIRST
) ||
1277 (gDataFileAccess
==UDATA_FILES_FIRST
)) {
1279 fprintf(stderr
, "Trying individual files\n");
1281 /* Check to make sure that there is a dataPath to iterate over */
1282 if ((dataPath
&& *dataPath
) || !isICUData
) {
1283 retVal
= doLoadFromIndividualFiles(pkgName
.data(), dataPath
, tocEntryPathSuffix
,
1284 path
, type
, name
, isAcceptable
, context
, &subErrorCode
, pErrorCode
);
1285 if((retVal
!= NULL
) || U_FAILURE(*pErrorCode
)) {
1291 /**** COMMON PACKAGE */
1292 if((gDataFileAccess
==UDATA_ONLY_PACKAGES
) ||
1293 (gDataFileAccess
==UDATA_FILES_FIRST
)) {
1295 fprintf(stderr
, "Trying packages (UDATA_ONLY_PACKAGES || UDATA_FILES_FIRST)\n");
1297 retVal
= doLoadFromCommonData(isICUData
,
1298 pkgName
.data(), dataPath
, tocEntryPathSuffix
, tocEntryName
.data(),
1299 path
, type
, name
, isAcceptable
, context
, &subErrorCode
, pErrorCode
);
1300 if((retVal
!= NULL
) || U_FAILURE(*pErrorCode
)) {
1305 /* Load from DLL. If we haven't attempted package load, we also haven't had any chance to
1306 try a DLL (static or setCommonData/etc) load.
1307 If we ever have a "UDATA_ONLY_FILES", add it to the or list here. */
1308 if(gDataFileAccess
==UDATA_NO_FILES
) {
1310 fprintf(stderr
, "Trying common data (UDATA_NO_FILES)\n");
1312 retVal
= doLoadFromCommonData(isICUData
,
1313 pkgName
.data(), "", tocEntryPathSuffix
, tocEntryName
.data(),
1314 path
, type
, name
, isAcceptable
, context
, &subErrorCode
, pErrorCode
);
1315 if((retVal
!= NULL
) || U_FAILURE(*pErrorCode
)) {
1320 /* data not found */
1321 if(U_SUCCESS(*pErrorCode
)) {
1322 if(U_SUCCESS(subErrorCode
)) {
1323 /* file not found */
1324 *pErrorCode
=U_FILE_ACCESS_ERROR
;
1326 /* entry point not found or rejected */
1327 *pErrorCode
=subErrorCode
;
1335 /* API ---------------------------------------------------------------------- */
1337 U_CAPI UDataMemory
* U_EXPORT2
1338 udata_open(const char *path
, const char *type
, const char *name
,
1339 UErrorCode
*pErrorCode
) {
1341 fprintf(stderr
, "udata_open(): Opening: %s : %s . %s\n", (path
?path
:"NULL"), name
, type
);
1345 if(pErrorCode
==NULL
|| U_FAILURE(*pErrorCode
)) {
1347 } else if(name
==NULL
|| *name
==0) {
1348 *pErrorCode
=U_ILLEGAL_ARGUMENT_ERROR
;
1351 return doOpenChoice(path
, type
, name
, NULL
, NULL
, pErrorCode
);
1357 U_CAPI UDataMemory
* U_EXPORT2
1358 udata_openChoice(const char *path
, const char *type
, const char *name
,
1359 UDataMemoryIsAcceptable
*isAcceptable
, void *context
,
1360 UErrorCode
*pErrorCode
) {
1362 fprintf(stderr
, "udata_openChoice(): Opening: %s : %s . %s\n", (path
?path
:"NULL"), name
, type
);
1365 if(pErrorCode
==NULL
|| U_FAILURE(*pErrorCode
)) {
1367 } else if(name
==NULL
|| *name
==0 || isAcceptable
==NULL
) {
1368 *pErrorCode
=U_ILLEGAL_ARGUMENT_ERROR
;
1371 return doOpenChoice(path
, type
, name
, isAcceptable
, context
, pErrorCode
);
1377 U_CAPI
void U_EXPORT2
1378 udata_getInfo(UDataMemory
*pData
, UDataInfo
*pInfo
) {
1380 if(pData
!=NULL
&& pData
->pHeader
!=NULL
) {
1381 const UDataInfo
*info
=&pData
->pHeader
->info
;
1382 uint16_t dataInfoSize
=udata_getInfoSize(info
);
1383 if(pInfo
->size
>dataInfoSize
) {
1384 pInfo
->size
=dataInfoSize
;
1386 uprv_memcpy((uint16_t *)pInfo
+1, (const uint16_t *)info
+1, pInfo
->size
-2);
1387 if(info
->isBigEndian
!=U_IS_BIG_ENDIAN
) {
1388 /* opposite endianness */
1389 uint16_t x
=info
->reservedWord
;
1390 pInfo
->reservedWord
=(uint16_t)((x
<<8)|(x
>>8));
1399 U_CAPI
void U_EXPORT2
udata_setFileAccess(UDataFileAccess access
, UErrorCode
* /*status*/)
1401 gDataFileAccess
= access
;