~ubuntu-branches/ubuntu/gutsy/icu/gutsy-updates

« back to all changes in this revision

Viewing changes to source/common/udata.c

  • Committer: Package Import Robot
  • Author(s): Jay Berkenbilt
  • Date: 2005-11-19 11:29:31 UTC
  • mfrom: (1.1.2)
  • Revision ID: package-import@ubuntu.com-20051119112931-vcizkrp10tli4enw
Tags: 3.4-3
Explicitly build with g++ 3.4.  The current ICU fails its test suite
with 4.0 but not with 3.4.  Future versions should work properly with
4.0.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/*
2
 
******************************************************************************
3
 
*
4
 
*   Copyright (C) 1999-2001, International Business Machines
5
 
*   Corporation and others.  All Rights Reserved.
6
 
*
7
 
******************************************************************************
8
 
*   file name:  udata.c
9
 
*   encoding:   US-ASCII
10
 
*   tab size:   8 (not used)
11
 
*   indentation:4
12
 
*
13
 
*   created on: 1999oct25
14
 
*   created by: Markus W. Scherer
15
 
*/
16
 
 
17
 
#include "unicode/utypes.h"
18
 
#include "unicode/putil.h"
19
 
#include "umutex.h"
20
 
#include "cmemory.h"
21
 
#include "cstring.h"
22
 
#include "unicode/udata.h"
23
 
#include "unicode/uversion.h"
24
 
#include "uhash.h"
25
 
#include "ucln_cmn.h"
26
 
 
27
 
#include "udatamem.h"
28
 
#include "umapfile.h"
29
 
#include "ucmndata.h"
30
 
 
31
 
/***********************************************************************
32
 
*
33
 
*   Notes on the organization of the ICU data implementation
34
 
*
35
 
*      All of the public API is defined in udata.h
36
 
*
37
 
*      The implementation is split into several files...
38
 
*
39
 
*         - udata.c  (this file) contains higher level code that knows about
40
 
*                     the search paths for locating data, caching opened data, etc.
41
 
*
42
 
*         - umapfile.c  contains the low level platform-specific code for actually loading
43
 
*                     (memory mapping, file reading, whatever) data into memory.
44
 
*
45
 
*         - ucmndata.c  deals with the tables of contents of ICU data items within
46
 
*                     an ICU common format data file.  The implementation includes
47
 
*                     an abstract interface and support for multiple TOC formats.
48
 
*                     All knowledge of any specific TOC format is encapsulated here.
49
 
*
50
 
*         - udatamem.c has code for managing UDataMemory structs.  These are little
51
 
*                     descriptor objects for blocks of memory holding ICU data of
52
 
*                     various types.
53
 
*/
54
 
 
55
 
/* configuration ---------------------------------------------------------- */
56
 
 
57
 
/* If you are excruciatingly bored turn this on .. */
58
 
/* #define UDATA_DEBUG 1 */
59
 
 
60
 
#if defined(UDATA_DEBUG)
61
 
#   include <stdio.h>
62
 
#endif
63
 
 
64
 
 
65
 
 
66
 
 
67
 
/***********************************************************************
68
 
*
69
 
*    static (Global) data
70
 
*
71
 
************************************************************************/
72
 
static UDataMemory *gCommonICUData = NULL;    /* Pointer to the common ICU data.           */
73
 
                                              /*   May be updated once, if we started with */
74
 
                                              /*   a stub or subset library.               */
75
 
 
76
 
static UDataMemory *gStubICUData   = NULL;    /* If gCommonICUData does get updated, remember */
77
 
                                              /*   the original one so that it can be cleaned */
78
 
                                              /*   up when ICU is shut down.                  */
79
 
 
80
 
static UHashtable  *gCommonDataCache = NULL;  /* Global hash table of opened ICU data files.  */
81
 
 
82
 
 
83
 
UBool
84
 
udata_cleanup()
85
 
{
86
 
    if (gCommonDataCache) {             /* Delete the cache of user data mappings.  */
87
 
        uhash_close(gCommonDataCache);  /*   Table owns the contents, and will delete them. */
88
 
        gCommonDataCache = NULL;        /*   Cleanup is not thread safe.                */
89
 
    }
90
 
 
91
 
    if (gCommonICUData != NULL) {
92
 
        udata_close(gCommonICUData);    /* Clean up common ICU Data             */
93
 
        gCommonICUData = NULL;
94
 
    }
95
 
 
96
 
    if (gStubICUData != NULL) {
97
 
        udata_close(gStubICUData);      /* Clean up the stub ICU Data             */
98
 
        gStubICUData = NULL;
99
 
    }
100
 
 
101
 
 
102
 
    return TRUE;                   /* Everything was cleaned up */
103
 
}
104
 
 
105
 
 
106
 
 
107
 
 
108
 
/*
109
 
 * setCommonICUData.   Set a UDataMemory to be the global ICU Data
110
 
 */
111
 
static void
112
 
setCommonICUData(UDataMemory *pData,     /*  The new common data.  Belongs to caller, we copy it. */
113
 
                 UDataMemory *oldData,   /*  Old ICUData ptr.  Overwrite of this value is ok,     */
114
 
                                         /*     of any others is not.                             */
115
 
                 UBool       warn,       /*  If true, set USING_DEFAULT warning if ICUData was    */
116
 
                                         /*    changed by another thread before we got to it.     */
117
 
                 UErrorCode *pErr)
118
 
{
119
 
    UDataMemory  *newCommonData = UDataMemory_createNewInstance(pErr);
120
 
    if (U_FAILURE(*pErr)) {
121
 
        return;
122
 
    }
123
 
 
124
 
    /*  For the assignment, other threads must cleanly see either the old            */
125
 
    /*    or the new, not some partially initialized new.  The old can not be        */
126
 
    /*    deleted - someone may still have a pointer to it lying around in           */
127
 
    /*    their locals.                                                              */
128
 
    UDatamemory_assign(newCommonData, pData);
129
 
    umtx_lock(NULL);
130
 
    if (gCommonICUData==oldData) {
131
 
        gStubICUData   = gCommonICUData;   /* remember the old Common Data, so it can be cleaned up. */
132
 
        gCommonICUData = newCommonData;
133
 
    }
134
 
    else {
135
 
        if  (warn==TRUE) {
136
 
            *pErr = U_USING_DEFAULT_WARNING;
137
 
        }
138
 
        uprv_free(newCommonData);
139
 
    }
140
 
    umtx_unlock(NULL);
141
 
    return;
142
 
}
143
 
 
144
 
 
145
 
 
146
 
static char *
147
 
strcpy_returnEnd(char *dest, const char *src) {
148
 
    while((*dest=*src)!=0) {
149
 
        ++dest;
150
 
        ++src;
151
 
    }
152
 
    return dest;
153
 
}
154
 
 
155
 
/*------------------------------------------------------------------------------
156
 
 *                                                                              
157
 
 *  computeDirPath   given a user-supplied path of an item to be opened,             
158
 
 *                         compute and return 
159
 
 *                            - the full directory path to be used 
160
 
 *                              when opening the file.
161
 
 *                            - Pointer to null at end of above returned path    
162
 
 *
163
 
 *                       Parameters:
164
 
 *                          path:        input path.  Buffer is not altered.
165
 
 *                          pathBuffer:  Output buffer.  Any contents are overwritten.
166
 
 *
167
 
 *                       Returns:
168
 
 *                          Pointer to null termination in returned pathBuffer.
169
 
 *
170
 
 *                    TODO:  This works the way ICU historically has, but the
171
 
 *                           whole data fallback search path is so complicated that
172
 
 *                           proabably almost no one will ever really understand it,
173
 
 *                           the potential for confusion is large.  (It's not just 
174
 
 *                           this one function, but the whole scheme.)
175
 
 *                            
176
 
 *------------------------------------------------------------------------------*/
177
 
char *
178
 
uprv_computeDirPath(const char *path, char *pathBuffer) {
179
 
    char   *finalSlash;       /* Ptr to last dir separator in input path, or null if none. */
180
 
    int     pathLen;          /* Length of the returned directory path                     */
181
 
    
182
 
    finalSlash = 0;
183
 
    if (path != 0) {
184
 
        finalSlash = uprv_strrchr(path, U_FILE_SEP_CHAR);
185
 
    }
186
 
    
187
 
    *pathBuffer = 0;
188
 
    if (finalSlash == 0) {
189
 
        /* No user-supplied path.  
190
 
         * Copy the ICU_DATA path to the path buffer and return that*/
191
 
        const char *icuDataDir;
192
 
        icuDataDir=u_getDataDirectory();
193
 
        if(icuDataDir!=NULL && *icuDataDir!=0) {
194
 
            return strcpy_returnEnd(pathBuffer, icuDataDir);
195
 
        } else {
196
 
            /* there is no icuDataDir either.  Just return the empty pathBuffer. */
197
 
            return pathBuffer;
198
 
        }
199
 
    } 
200
 
    
201
 
    /* User supplied path did contain a directory portion.
202
 
     * Copy it to the output path buffer */
203
 
    pathLen = finalSlash - path + 1;
204
 
    uprv_memcpy(pathBuffer, path, pathLen);
205
 
    *(pathBuffer+pathLen) = 0;
206
 
    return pathBuffer+pathLen;
207
 
}
208
 
 
209
 
 
210
 
static const char *
211
 
findBasename(const char *path) {
212
 
    const char *basename=uprv_strrchr(path, U_FILE_SEP_CHAR);
213
 
    if(basename==NULL) {
214
 
        return path;
215
 
    } else {
216
 
        return basename+1;
217
 
    }
218
 
}
219
 
 
220
 
 
221
 
/*----------------------------------------------------------------------*
222
 
 *                                                                      *
223
 
 *   Cache for common data                                              *
224
 
 *      Functions for looking up or adding entries to a cache of        *
225
 
 *      data that has been previously opened.  Avoids a potentially     *
226
 
 *      expensive operation of re-opening the data for subsequent       *
227
 
 *      uses.                                                           *
228
 
 *                                                                      *
229
 
 *      Data remains cached for the duration of the process.            *
230
 
 *                                                                      *
231
 
 *----------------------------------------------------------------------*/
232
 
 
233
 
typedef struct DataCacheElement {
234
 
    char          *name;
235
 
    UDataMemory   *item;
236
 
} DataCacheElement;
237
 
 
238
 
 
239
 
 
240
 
/*
241
 
 * Deleter function for DataCacheElements.
242
 
 *         udata cleanup function closes the hash table; hash table in turn calls back to
243
 
 *         here for each entry.
244
 
 */
245
 
static void  U_EXPORT2 U_CALLCONV DataCacheElement_deleter(void *pDCEl) {
246
 
    DataCacheElement *p = (DataCacheElement *)pDCEl;
247
 
    udata_close(p->item);              /* unmaps storage */
248
 
    uprv_free(p->name);                /* delete the hash key string. */
249
 
    uprv_free(pDCEl);                  /* delete 'this'          */
250
 
}
251
 
 
252
 
 /*   udata_getCacheHashTable()
253
 
 *     Get the hash table used to store the data cache entries.
254
 
 *     Lazy create it if it doesn't yet exist.
255
 
 */
256
 
static UHashtable *udata_getHashTable() {
257
 
    UErrorCode err = U_ZERO_ERROR;
258
 
 
259
 
    if (gCommonDataCache != NULL) {
260
 
        return gCommonDataCache;
261
 
    }
262
 
    umtx_lock(NULL);
263
 
    if (gCommonDataCache == NULL) {
264
 
        gCommonDataCache = uhash_open(uhash_hashChars, uhash_compareChars, &err);
265
 
        uhash_setValueDeleter(gCommonDataCache, DataCacheElement_deleter);
266
 
    }
267
 
    umtx_unlock(NULL);
268
 
 
269
 
    if (U_FAILURE(err)) {
270
 
        return NULL;      /* TODO:  handle this error better.  */
271
 
    }
272
 
    return gCommonDataCache;
273
 
}
274
 
 
275
 
 
276
 
 
277
 
static UDataMemory *udata_findCachedData(const char *path)
278
 
{
279
 
    UHashtable        *htable;
280
 
    UDataMemory       *retVal = NULL;
281
 
    DataCacheElement  *el;
282
 
    const char        *baseName;
283
 
 
284
 
    baseName = findBasename(path);   /* Cache remembers only the base name, not the full path. */
285
 
    htable = udata_getHashTable();
286
 
    umtx_lock(NULL);
287
 
    el = (DataCacheElement *)uhash_get(htable, baseName);
288
 
    umtx_unlock(NULL);
289
 
    if (el != NULL) {
290
 
        retVal = el->item;
291
 
    }
292
 
    return retVal;
293
 
}
294
 
 
295
 
 
296
 
static UDataMemory *udata_cacheDataItem(const char *path, UDataMemory *item, UErrorCode *pErr) {
297
 
    DataCacheElement *newElement;
298
 
    const char       *baseName;
299
 
    int               nameLen;
300
 
    UHashtable       *htable;
301
 
    UDataMemory      *oldValue = NULL;
302
 
 
303
 
    if (U_FAILURE(*pErr)) {
304
 
        return NULL;
305
 
    }
306
 
 
307
 
    /* Create a new DataCacheElement - the thingy we store in the hash table -
308
 
     * and copy the supplied path and UDataMemoryItems into it.
309
 
     */
310
 
    newElement = uprv_malloc(sizeof(DataCacheElement));
311
 
    if (newElement == NULL) {
312
 
        *pErr = U_MEMORY_ALLOCATION_ERROR;
313
 
        return NULL;
314
 
    }
315
 
    newElement->item = UDataMemory_createNewInstance(pErr);
316
 
    if (U_FAILURE(*pErr)) {
317
 
        return NULL;
318
 
    }
319
 
    UDatamemory_assign(newElement->item, item);
320
 
 
321
 
    baseName = findBasename(path);
322
 
    nameLen = uprv_strlen(baseName);
323
 
    newElement->name = uprv_malloc(nameLen+1);
324
 
    if (newElement->name == NULL) {
325
 
        *pErr = U_MEMORY_ALLOCATION_ERROR;
326
 
        return NULL;
327
 
    }
328
 
    uprv_strcpy(newElement->name, baseName);
329
 
 
330
 
    /* Stick the new DataCacheElement into the hash table.
331
 
    */
332
 
    htable = udata_getHashTable();
333
 
    umtx_lock(NULL);
334
 
    oldValue = uhash_get(htable, path);
335
 
    if (oldValue != NULL) {
336
 
        *pErr = U_USING_DEFAULT_WARNING; }
337
 
    else {
338
 
        uhash_put(
339
 
            htable,
340
 
            newElement->name,               /* Key   */
341
 
            newElement,                     /* Value */
342
 
            pErr);
343
 
    }
344
 
    umtx_unlock(NULL);
345
 
 
346
 
    if (*pErr == U_USING_DEFAULT_WARNING || U_FAILURE(*pErr)) {
347
 
        uprv_free(newElement->name);
348
 
        uprv_free(newElement->item);
349
 
        uprv_free(newElement);
350
 
        return oldValue;
351
 
    }
352
 
 
353
 
    return newElement->item;
354
 
}
355
 
 
356
 
 
357
 
 
358
 
 
359
 
/*----------------------------------------------------------------------*
360
 
 *                                                                      *
361
 
 *  Add a static reference to the common data  library                  *
362
 
 *   Unless overridden by an explicit u_setCommonData, this will be     *
363
 
 *      our common data.                                                *
364
 
 *                                                                      *
365
 
 *----------------------------------------------------------------------*/
366
 
extern  const DataHeader U_IMPORT U_ICUDATA_ENTRY_POINT;
367
 
 
368
 
 
369
 
/*----------------------------------------------------------------------*
370
 
 *                                                                      *
371
 
 *   openCommonData   Attempt to open a common format (.dat) file       *
372
 
 *                    Map it into memory (if it's not there already)    *
373
 
 *                    and return a UDataMemory object for it.           *
374
 
 *                                                                      *
375
 
 *                    If the requested data is already open and cached  *
376
 
 *                       just return the cached UDataMem object.        *
377
 
 *                                                                      *
378
 
 *----------------------------------------------------------------------*/
379
 
static UDataMemory *
380
 
openCommonData(
381
 
               const char *path,          /*  Path from OpenCHoice?          */
382
 
               UBool isICUData,           /*  ICU Data true if path == NULL  */
383
 
               UErrorCode *pErrorCode)
384
 
{
385
 
    const char *inBasename;
386
 
    char *basename, *suffix;
387
 
    char pathBuffer[1024];
388
 
    UDataMemory   tData;
389
 
 
390
 
    if (U_FAILURE(*pErrorCode)) {
391
 
        return NULL;
392
 
    }
393
 
 
394
 
    UDataMemory_init(&tData);
395
 
 
396
 
    if (isICUData) {
397
 
        /* "mini-cache" for common ICU data */
398
 
        if(gCommonICUData != NULL) {
399
 
            return gCommonICUData;
400
 
        }
401
 
 
402
 
        tData.pHeader = &U_ICUDATA_ENTRY_POINT;
403
 
        udata_checkCommonData(&tData, pErrorCode);
404
 
        setCommonICUData(&tData, NULL, FALSE, pErrorCode);
405
 
        return gCommonICUData;
406
 
    }
407
 
 
408
 
 
409
 
    /* request is NOT for ICU Data.  */
410
 
 
411
 
    /* Find the base name portion of the supplied path.   */
412
 
    /*   inBasename will be left pointing somewhere within the original path string.      */
413
 
    inBasename=findBasename(path);
414
 
    if(*inBasename==0) {
415
 
        /* no basename.     This will happen if the original path was a directory name,   */
416
 
        /*    like  "a/b/c/".   (Fallback to separate files will still work.)             */
417
 
        *pErrorCode=U_FILE_ACCESS_ERROR;
418
 
        return NULL;
419
 
    }
420
 
 
421
 
   /* Is the requested common data file already open and cached?                     */
422
 
   /*   Note that the cache is keyed by the base name only.  The rest of the path,   */
423
 
   /*     if any, is not considered.                                                 */
424
 
   {
425
 
        UDataMemory  *dataToReturn = udata_findCachedData(inBasename);
426
 
        if (dataToReturn != NULL) {
427
 
            return dataToReturn;
428
 
        }
429
 
    }
430
 
 
431
 
    /* Requested item is not in the cache.
432
 
     * Hunt it down, trying all the fall back locations.
433
 
     */
434
 
 
435
 
    /* try path/basename first, then basename only */
436
 
    basename=uprv_computeDirPath(path, pathBuffer);       /*  pathBuffer = directory path */
437
 
    suffix=strcpy_returnEnd(basename, inBasename);   /*     append the base name.    */
438
 
    uprv_strcpy(suffix, ".dat");                     /*     append ".dat"            */
439
 
 
440
 
    uprv_mapFile(&tData, pathBuffer);
441
 
 
442
 
    if (!UDataMemory_isLoaded(&tData)) {
443
 
        /* The data didn't open.  Try again without the directory portion of the name */
444
 
        if (basename!=pathBuffer) {
445
 
            uprv_mapFile(&tData, basename);
446
 
        }
447
 
    }
448
 
 
449
 
    if (!UDataMemory_isLoaded(&tData)) {
450
 
        /* no common data */
451
 
        *pErrorCode=U_FILE_ACCESS_ERROR;
452
 
        return NULL;
453
 
    }
454
 
 
455
 
    /* we have mapped a file, check its header */
456
 
    udata_checkCommonData(&tData, pErrorCode);
457
 
 
458
 
 
459
 
    /* Cache the UDataMemory struct for this .dat file,
460
 
     *   so we won't need to hunt it down and map it again next time
461
 
     *   something is needed from it.                */
462
 
    return udata_cacheDataItem(inBasename, &tData, pErrorCode);
463
 
}
464
 
 
465
 
 
466
 
#ifdef OS390
467
 
#   define MAX_STUB_ENTRIES 7
468
 
#else
469
 
#   define MAX_STUB_ENTRIES 0
470
 
#endif
471
 
 
472
 
 
473
 
/*----------------------------------------------------------------------*
474
 
 *                                                                      *
475
 
 *   extendICUData   If the full set of ICU data was not loaded at      *
476
 
 *                   program startup, load it now.  This function will  *
477
 
 *                   be called when the lookup of an ICU data item in   *
478
 
 *                   the common ICU data fails.                         *
479
 
 *                                                                      *
480
 
 *                   The parameter is the UDataMemory in which the      *
481
 
 *                   search for a requested item failed.                *
482
 
 *                                                                      *
483
 
 *                   return true if new data is loaded, false otherwise.*
484
 
 *                                                                      *
485
 
 *----------------------------------------------------------------------*/
486
 
static UBool extendICUData(UDataMemory *failedData, UErrorCode *pErr)
487
 
{
488
 
    /*  If the data library that we are running with turns out to be the
489
 
     *   stub library (or, on the 390, the subset library), we will try to
490
 
     *   load a .dat file instead.  The stub library has no entries in its
491
 
     *   TOC, which is how we identify it here.
492
 
     */
493
 
    UDataMemory   *pData;
494
 
    UDataMemory   copyPData;
495
 
 
496
 
    if (failedData->vFuncs->NumEntries(failedData) > MAX_STUB_ENTRIES) {
497
 
        /*  Not the stub.  We can't extend.  */
498
 
        return FALSE;
499
 
    }
500
 
 
501
 
    /* See if we can explicitly open a .dat file for the ICUData. */
502
 
    pData = openCommonData(
503
 
               U_ICUDATA_NAME,            /*  "icudt20l" , for example.          */
504
 
               FALSE,                     /*  Pretend we're not opening ICUData  */
505
 
               pErr);
506
 
 
507
 
    /* How about if there is no pData, eh... */
508
 
 
509
 
   UDataMemory_init(&copyPData);
510
 
   if(pData != NULL) {
511
 
      UDatamemory_assign(&copyPData, pData);
512
 
      copyPData.map = 0;              /* The mapping for this data is owned by the hash table */
513
 
      copyPData.mapAddr = 0;          /*   which will unmap it when ICU is shut down.         */
514
 
                                      /* CommonICUData is also unmapped when ICU is shut down.*/
515
 
                                      /* To avoid unmapping the data twice, zero out the map  */
516
 
                                      /*   fields in the UDataMemory that we're assigning     */
517
 
                                      /*   to CommonICUData.                                  */
518
 
 
519
 
      setCommonICUData(&copyPData,    /*  The new common data.                                */
520
 
                   failedData,        /*  Old ICUData ptr.  Overwrite of this value is ok,    */
521
 
                   FALSE,             /*  No warnings if write didn't happen                  */
522
 
                   pErr);             /*  setCommonICUData honors errors; NOP if error set    */
523
 
    }
524
 
    
525
 
 
526
 
    return gCommonICUData != failedData;   /* Return true if ICUData pointer was updated.   */
527
 
                                    /*   (Could potentialy have been done by another thread racing */
528
 
                                    /*   us through here, but that's fine, we still return true    */
529
 
                                    /*   so that current thread will also examine extended data.   */
530
 
}
531
 
 
532
 
 
533
 
 
534
 
 
535
 
/*----------------------------------------------------------------------*
536
 
 *                                                                      *
537
 
 *   udata_setCommonData                                                *
538
 
 *                                                                      *
539
 
 *----------------------------------------------------------------------*/
540
 
U_CAPI void U_EXPORT2
541
 
udata_setCommonData(const void *data, UErrorCode *pErrorCode) {
542
 
    UDataMemory dataMemory;
543
 
 
544
 
    if(pErrorCode==NULL || U_FAILURE(*pErrorCode)) {
545
 
        return;
546
 
    }
547
 
 
548
 
    if(data==NULL) {
549
 
        *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
550
 
        return;
551
 
    }
552
 
 
553
 
    /* do we already have common ICU data set? */
554
 
    if(gCommonICUData != NULL) {
555
 
        *pErrorCode=U_USING_DEFAULT_ERROR;
556
 
        return;
557
 
    }
558
 
 
559
 
    /* set the data pointer and test for validity */
560
 
    UDataMemory_init(&dataMemory);
561
 
    UDataMemory_setData(&dataMemory, data);
562
 
    udata_checkCommonData(&dataMemory, pErrorCode);
563
 
    if (U_FAILURE(*pErrorCode)) {return;}
564
 
 
565
 
    /* we have good data */
566
 
    /* Set it up as the ICU Common Data.  */
567
 
    setCommonICUData(&dataMemory, NULL, TRUE, pErrorCode);
568
 
}
569
 
 
570
 
 
571
 
 
572
 
 
573
 
/*---------------------------------------------------------------------------
574
 
 *
575
 
 *  udata_setAppData
576
 
 *
577
 
 *---------------------------------------------------------------------------- */
578
 
U_CAPI void U_EXPORT2
579
 
udata_setAppData(const char *path, const void *data, UErrorCode *err)
580
 
{
581
 
    UDataMemory     udm;
582
 
 
583
 
    if(err==NULL || U_FAILURE(*err)) {
584
 
        return;
585
 
    }
586
 
    if(data==NULL) {
587
 
        *err=U_ILLEGAL_ARGUMENT_ERROR;
588
 
        return;
589
 
    }
590
 
 
591
 
    UDataMemory_init(&udm);
592
 
    udm.pHeader = data;
593
 
    udata_checkCommonData(&udm, err);
594
 
    udata_cacheDataItem(path, &udm, err);
595
 
}
596
 
 
597
 
/*----------------------------------------------------------------------------*
598
 
 *                                                                            *
599
 
 *  checkDataItem     Given a freshly located/loaded data item, either        *
600
 
 *                    an entry in a common file or a separately loaded file,  *
601
 
 *                    sanity check its header, and see if the data is         *
602
 
 *                    acceptable to the app.                                  *
603
 
 *                    If the data is good, create and return a UDataMemory    *
604
 
 *                    object that can be returned to the application.         *
605
 
 *                    Return NULL on any sort of failure.                     *
606
 
 *                                                                            *
607
 
 *----------------------------------------------------------------------------*/
608
 
static UDataMemory *
609
 
checkDataItem
610
 
(
611
 
 const DataHeader         *pHeader,         /* The data item to be checked.                */
612
 
 UDataMemoryIsAcceptable  *isAcceptable,    /* App's call-back function                    */
613
 
 void                     *context,         /*   pass-thru param for above.                */
614
 
 const char               *type,            /*   pass-thru param for above.                */
615
 
 const char               *name,            /*   pass-thru param for above.                */
616
 
 UErrorCode               *nonFatalErr,     /* Error code if this data was not acceptable  */
617
 
                                            /*   but openChoice should continue with       */
618
 
                                            /*   trying to get data from fallback path.    */
619
 
 UErrorCode               *fatalErr         /* Bad error, caller should return immediately */
620
 
 )
621
 
{
622
 
    UDataMemory  *rDataMem = NULL;          /* the new UDataMemory, to be returned.        */
623
 
 
624
 
    if (U_FAILURE(*fatalErr)) {
625
 
        return NULL;
626
 
    }
627
 
 
628
 
    if(pHeader->dataHeader.magic1==0xda &&
629
 
        pHeader->dataHeader.magic2==0x27 &&
630
 
        pHeader->info.isBigEndian==U_IS_BIG_ENDIAN &&
631
 
        (isAcceptable==NULL || isAcceptable(context, type, name, &pHeader->info))
632
 
        ) {
633
 
        rDataMem=UDataMemory_createNewInstance(fatalErr);
634
 
        if (U_FAILURE(*fatalErr)) {
635
 
            return NULL;
636
 
        }
637
 
        rDataMem->pHeader = pHeader;
638
 
    } else {
639
 
        /* the data is not acceptable, look further */
640
 
        /* If we eventually find something good, this errorcode will be */
641
 
        /*    cleared out.                                              */
642
 
        *nonFatalErr=U_INVALID_FORMAT_ERROR;
643
 
    }
644
 
    return rDataMem;
645
 
}
646
 
 
647
 
 
648
 
 
649
 
 
650
 
/*
651
 
 *  A note on the ownership of Mapped Memory
652
 
 *
653
 
 *  For common format files, ownership resides with the UDataMemory object
654
 
 *    that lives in the cache of opened common data.  These UDataMemorys are private
655
 
 *    to the udata implementation, and are never seen directly by users.
656
 
 *
657
 
 *    The UDataMemory objects returned to users will have the address of some desired
658
 
 *    data within the mapped region, but they wont have the mapping info itself, and thus
659
 
 *    won't cause anything to be removed from memory when they are closed.
660
 
 *
661
 
 *  For individual data files, the UDataMemory returned to the user holds the
662
 
 *  information necessary to unmap the data on close.  If the user independently
663
 
 *  opens the same data file twice, two completely independent mappings will be made.
664
 
 *  (There is no cache of opened data items from individual files, only a cache of
665
 
 *   opened Common Data files, that is, files containing a collection of data items.)
666
 
 *
667
 
 *  For common data passed in from the user via udata_setAppData() or
668
 
 *  udata_setCommonData(), ownership remains with the user.
669
 
 *
670
 
 *  UDataMemory objects themselves, as opposed to the memory they describe,
671
 
 *  can be anywhere - heap, stack/local or global.
672
 
 *  They have a flag to indicate when they're heap allocated and thus
673
 
 *  must be deleted when closed.
674
 
 */
675
 
 
676
 
 
677
 
/*----------------------------------------------------------------------------*
678
 
 *                                                                            *
679
 
 * main data loading functions                                                *
680
 
 *                                                                            *
681
 
 *----------------------------------------------------------------------------*/
682
 
static UDataMemory *
683
 
doOpenChoice(const char *path, const char *type, const char *name,
684
 
             UDataMemoryIsAcceptable *isAcceptable, void *context,
685
 
             UErrorCode *pErrorCode)
686
 
{
687
 
    char                pathBuffer[1024];
688
 
    char                tocEntryName[100];
689
 
    UDataMemory         dataMemory;
690
 
    UDataMemory        *pCommonData;
691
 
    UDataMemory        *pEntryData;
692
 
    const DataHeader   *pHeader;
693
 
    const char         *inBasename;
694
 
    char               *basename;
695
 
    char               *suffix;
696
 
    UErrorCode          errorCode=U_ZERO_ERROR;
697
 
    UBool               isICUData= (UBool)(path==NULL);
698
 
 
699
 
 
700
 
    /* Make up a full mame by appending the type to the supplied
701
 
     *  name, assuming that a type was supplied.
702
 
     */
703
 
    uprv_strcpy(tocEntryName, name);
704
 
    if(type!=NULL && *type!=0) {
705
 
        uprv_strcat(tocEntryName, ".");
706
 
        uprv_strcat(tocEntryName, type);
707
 
    }
708
 
 
709
 
    /* try to get common data.  The loop is for platforms such as the 390 that do
710
 
     *  not initially load the full set of ICU data.  If the lookup of an ICU data item
711
 
     *  fails, the full (but slower to load) set is loaded, the and the loop repeats,
712
 
     *  trying the lookup again.  Once the full set of ICU data is loaded, the loop wont
713
 
     *  repeat because the full set will be checked the first time through.
714
 
     *
715
 
     *  The loop also handles the fallback to a .dat file if the application linked
716
 
     *   to the stub data library rather than a real library.
717
 
     */
718
 
    for (;;) {
719
 
        pCommonData=openCommonData(path, isICUData, &errorCode);
720
 
 
721
 
        if(U_SUCCESS(errorCode)) {
722
 
            /* look up the data piece in the common data */
723
 
            pHeader=pCommonData->vFuncs->Lookup(pCommonData, tocEntryName, &errorCode);
724
 
            if(pHeader!=NULL) {
725
 
                pEntryData = checkDataItem(pHeader, isAcceptable, context, type, name, &errorCode, pErrorCode);
726
 
                if (U_FAILURE(*pErrorCode)) {
727
 
                    return NULL;
728
 
                }
729
 
                if (pEntryData != NULL) {
730
 
                    return pEntryData;
731
 
                }
732
 
            }
733
 
        }
734
 
        /* Data wasn't found.  If we were looking for an ICUData item and there is
735
 
         * more data available, load it and try again,
736
 
         * otherwise break out of this loop. */
737
 
        if (!(isICUData && extendICUData(pCommonData, &errorCode))) {
738
 
            break;
739
 
        }
740
 
    };
741
 
 
742
 
 
743
 
    /* the data was not found in the common data,  look further, */
744
 
    /* try to get an individual data file */
745
 
    basename=uprv_computeDirPath(path, pathBuffer);
746
 
    if(isICUData) {
747
 
        inBasename=COMMON_DATA_NAME;
748
 
    } else {
749
 
        inBasename=findBasename(path);
750
 
    }
751
 
 
752
 
#ifdef UDATA_DEBUG
753
 
    fprintf(stderr, "looking for ind. file\n");
754
 
#endif
755
 
 
756
 
    /* try path+basename+"_"+entryName first */
757
 
    if(*inBasename!=0) {
758
 
        suffix=strcpy_returnEnd(basename, inBasename);
759
 
        *suffix++='_';
760
 
        uprv_strcpy(suffix, tocEntryName);
761
 
 
762
 
        if( uprv_mapFile(&dataMemory, pathBuffer) ||
763
 
            (basename!=pathBuffer && uprv_mapFile(&dataMemory, basename)))
764
 
        {
765
 
            /* We mapped a file.  Check out its contents.   */
766
 
            pEntryData = checkDataItem(dataMemory.pHeader, isAcceptable, context, type, name, &errorCode, pErrorCode);
767
 
            if (pEntryData != NULL)
768
 
            {
769
 
               /* Got good data.
770
 
                *  Hand off ownership of the backing memory to the user's UDataMemory.
771
 
                *  and return it. */
772
 
                pEntryData->mapAddr = dataMemory.mapAddr;
773
 
                pEntryData->map     = dataMemory.map;
774
 
                return pEntryData;
775
 
            }
776
 
 
777
 
            /* the data is not acceptable, or some error occured.  Either way, unmap the memory */
778
 
            udata_close(&dataMemory);
779
 
 
780
 
            /* If we had a nasty error, bail out completely.  */
781
 
            if (U_FAILURE(*pErrorCode)) {
782
 
                return NULL;
783
 
            }
784
 
 
785
 
            /* Otherwise remember that we found data but didn't like it for some reason,
786
 
            *  and continue looking
787
 
            */
788
 
            errorCode=U_INVALID_FORMAT_ERROR;
789
 
        }
790
 
    }
791
 
 
792
 
    /* try path+entryName next */
793
 
    uprv_strcpy(basename, tocEntryName);
794
 
    if( uprv_mapFile(&dataMemory, pathBuffer) ||
795
 
        (basename!=pathBuffer && uprv_mapFile(&dataMemory, basename)))
796
 
    {
797
 
        pEntryData = checkDataItem(dataMemory.pHeader, isAcceptable, context, type, name, &errorCode, pErrorCode);
798
 
        if (pEntryData != NULL) {
799
 
           /* Data is good.
800
 
            *  Hand off ownership of the backing memory to the user's UDataMemory.
801
 
            *  and return it.   */
802
 
            pEntryData->mapAddr = dataMemory.mapAddr;
803
 
            pEntryData->map     = dataMemory.map;
804
 
            return pEntryData;
805
 
        }
806
 
 
807
 
        /* the data is not acceptable, or some error occured.  Either way, unmap the memory */
808
 
        udata_close(&dataMemory);
809
 
 
810
 
        /* If we had a nasty error, bail out completely.  */
811
 
        if (U_FAILURE(*pErrorCode)) {
812
 
            return NULL;
813
 
        }
814
 
 
815
 
        /* Otherwise remember that we found data but didn't like it for some reason  */
816
 
        errorCode=U_INVALID_FORMAT_ERROR;
817
 
    }
818
 
 
819
 
    /* data not found */
820
 
    if(U_SUCCESS(*pErrorCode)) {
821
 
        if(U_SUCCESS(errorCode)) {
822
 
            /* file not found */
823
 
            *pErrorCode=U_FILE_ACCESS_ERROR;
824
 
        } else {
825
 
            /* entry point not found or rejected */
826
 
            *pErrorCode=errorCode;
827
 
        }
828
 
    }
829
 
    return NULL;
830
 
}
831
 
 
832
 
 
833
 
 
834
 
/* API ---------------------------------------------------------------------- */
835
 
 
836
 
U_CAPI UDataMemory * U_EXPORT2
837
 
udata_open(const char *path, const char *type, const char *name,
838
 
           UErrorCode *pErrorCode) {
839
 
#ifdef UDATA_DEBUG
840
 
    fprintf(stderr, "udata_open(): Opening: %s . %s\n", name, type);
841
 
    fflush(stderr);
842
 
#endif
843
 
 
844
 
    if(pErrorCode==NULL || U_FAILURE(*pErrorCode)) {
845
 
        return NULL;
846
 
    } else if(name==NULL || *name==0) {
847
 
        *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
848
 
        return NULL;
849
 
    } else {
850
 
        return doOpenChoice(path, type, name, NULL, NULL, pErrorCode);
851
 
    }
852
 
}
853
 
 
854
 
 
855
 
 
856
 
U_CAPI UDataMemory * U_EXPORT2
857
 
udata_openChoice(const char *path, const char *type, const char *name,
858
 
                 UDataMemoryIsAcceptable *isAcceptable, void *context,
859
 
                 UErrorCode *pErrorCode) {
860
 
#ifdef UDATA_DEBUG
861
 
  fprintf(stderr, "udata_openChoice(): Opening: %s . %s\n", name, type);fflush(stderr);
862
 
#endif
863
 
 
864
 
    if(pErrorCode==NULL || U_FAILURE(*pErrorCode)) {
865
 
        return NULL;
866
 
    } else if(name==NULL || *name==0 || isAcceptable==NULL) {
867
 
        *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
868
 
        return NULL;
869
 
    } else {
870
 
        return doOpenChoice(path, type, name, isAcceptable, context, pErrorCode);
871
 
    }
872
 
}
873
 
 
874
 
 
875
 
 
876
 
U_CAPI void U_EXPORT2
877
 
udata_getInfo(UDataMemory *pData, UDataInfo *pInfo) {
878
 
    if(pInfo!=NULL) {
879
 
        if(pData!=NULL && pData->pHeader!=NULL) {
880
 
            const UDataInfo *info=&pData->pHeader->info;
881
 
            if(pInfo->size>info->size) {
882
 
                pInfo->size=info->size;
883
 
            }
884
 
            uprv_memcpy((uint16_t *)pInfo+1, (uint16_t *)info+1, pInfo->size-2);
885
 
        } else {
886
 
            pInfo->size=0;
887
 
        }
888
 
    }
889
 
}