Coverage Report

Created: 2026-05-06 06:16

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/icu/icu4c/source/i18n/collationdatareader.cpp
Line
Count
Source
1
// © 2016 and later: Unicode, Inc. and others.
2
// License & terms of use: http://www.unicode.org/copyright.html
3
/*
4
*******************************************************************************
5
* Copyright (C) 2013-2015, International Business Machines
6
* Corporation and others.  All Rights Reserved.
7
*******************************************************************************
8
* collationdatareader.cpp
9
*
10
* created on: 2013feb07
11
* created by: Markus W. Scherer
12
*/
13
14
#include "unicode/utypes.h"
15
16
#if !UCONFIG_NO_COLLATION
17
18
#include "unicode/ucol.h"
19
#include "unicode/udata.h"
20
#include "unicode/uscript.h"
21
#include "cmemory.h"
22
#include "collation.h"
23
#include "collationdata.h"
24
#include "collationdatareader.h"
25
#include "collationfastlatin.h"
26
#include "collationkeys.h"
27
#include "collationrootelements.h"
28
#include "collationsettings.h"
29
#include "collationtailoring.h"
30
#include "collunsafe.h"
31
#include "normalizer2impl.h"
32
#include "uassert.h"
33
#include "ucmndata.h"
34
#include "utrie2.h"
35
36
U_NAMESPACE_BEGIN
37
38
namespace {
39
40
3.90k
int32_t getIndex(const int32_t *indexes, int32_t length, int32_t i) {
41
3.90k
    return (i < length) ? indexes[i] : -1;
42
3.90k
}
43
44
}  // namespace
45
46
void
47
CollationDataReader::read(const CollationTailoring *base, const uint8_t *inBytes, int32_t inLength,
48
176
                          CollationTailoring &tailoring, UErrorCode &errorCode) {
49
176
    if(U_FAILURE(errorCode)) { return; }
50
173
    if(base != nullptr) {
51
171
        if(inBytes == nullptr || (0 <= inLength && inLength < 24)) {
52
0
            errorCode = U_ILLEGAL_ARGUMENT_ERROR;
53
0
            return;
54
0
        }
55
171
        const DataHeader *header = reinterpret_cast<const DataHeader *>(inBytes);
56
171
        if(!(header->dataHeader.magic1 == 0xda && header->dataHeader.magic2 == 0x27 &&
57
171
                isAcceptable(tailoring.version, nullptr, nullptr, &header->info))) {
58
0
            errorCode = U_INVALID_FORMAT_ERROR;
59
0
            return;
60
0
        }
61
171
        if(base->getUCAVersion() != tailoring.getUCAVersion()) {
62
0
            errorCode = U_COLLATOR_VERSION_MISMATCH;
63
0
            return;
64
0
        }
65
171
        int32_t headerLength = header->dataHeader.headerSize;
66
171
        inBytes += headerLength;
67
171
        if(inLength >= 0) {
68
171
            inLength -= headerLength;
69
171
        }
70
171
    }
71
72
173
    if(inBytes == nullptr || (0 <= inLength && inLength < 8)) {
73
0
        errorCode = U_ILLEGAL_ARGUMENT_ERROR;
74
0
        return;
75
0
    }
76
173
    const int32_t *inIndexes = reinterpret_cast<const int32_t *>(inBytes);
77
173
    int32_t indexesLength = inIndexes[IX_INDEXES_LENGTH];
78
173
    if(indexesLength < 2 || (0 <= inLength && inLength < indexesLength * 4)) {
79
0
        errorCode = U_INVALID_FORMAT_ERROR;  // Not enough indexes.
80
0
        return;
81
0
    }
82
83
    // Assume that the tailoring data is in initial state,
84
    // with nullptr pointers and 0 lengths.
85
86
    // Set pointers to non-empty data parts.
87
    // Do this in order of their byte offsets. (Should help porting to Java.)
88
89
173
    int32_t index;  // one of the indexes[] slots
90
173
    int32_t offset;  // byte offset for the index part
91
173
    int32_t length;  // number of bytes in the index part
92
93
173
    if(indexesLength > IX_TOTAL_SIZE) {
94
2
        length = inIndexes[IX_TOTAL_SIZE];
95
171
    } else if(indexesLength > IX_REORDER_CODES_OFFSET) {
96
169
        length = inIndexes[indexesLength - 1];
97
169
    } else {
98
2
        length = 0;  // only indexes, and inLength was already checked for them
99
2
    }
100
173
    if(0 <= inLength && inLength < length) {
101
0
        errorCode = U_INVALID_FORMAT_ERROR;
102
0
        return;
103
0
    }
104
105
173
    const CollationData *baseData = base == nullptr ? nullptr : base->data;
106
173
    const int32_t *reorderCodes = nullptr;
107
173
    int32_t reorderCodesLength = 0;
108
173
    const uint32_t *reorderRanges = nullptr;
109
173
    int32_t reorderRangesLength = 0;
110
173
    index = IX_REORDER_CODES_OFFSET;
111
173
    offset = getIndex(inIndexes, indexesLength, index);
112
173
    length = getIndex(inIndexes, indexesLength, index + 1) - offset;
113
173
    if(length >= 4) {
114
75
        if(baseData == nullptr) {
115
            // We assume for collation settings that
116
            // the base data does not have a reordering.
117
0
            errorCode = U_INVALID_FORMAT_ERROR;
118
0
            return;
119
0
        }
120
75
        reorderCodes = reinterpret_cast<const int32_t *>(inBytes + offset);
121
75
        reorderCodesLength = length / 4;
122
123
        // The reorderRanges (if any) are the trailing reorderCodes entries.
124
        // Split the array at the boundary.
125
        // Script or reorder codes do not exceed 16-bit values.
126
        // Range limits are stored in the upper 16 bits, and are never 0.
127
234
        while(reorderRangesLength < reorderCodesLength &&
128
234
                (reorderCodes[reorderCodesLength - reorderRangesLength - 1] & 0xffff0000) != 0) {
129
159
            ++reorderRangesLength;
130
159
        }
131
75
        U_ASSERT(reorderRangesLength < reorderCodesLength);
132
75
        if(reorderRangesLength != 0) {
133
34
            reorderCodesLength -= reorderRangesLength;
134
34
            reorderRanges = reinterpret_cast<const uint32_t *>(reorderCodes + reorderCodesLength);
135
34
        }
136
75
    }
137
138
    // There should be a reorder table only if there are reorder codes.
139
    // However, when there are reorder codes the reorder table may be omitted to reduce
140
    // the data size.
141
173
    const uint8_t *reorderTable = nullptr;
142
173
    index = IX_REORDER_TABLE_OFFSET;
143
173
    offset = getIndex(inIndexes, indexesLength, index);
144
173
    length = getIndex(inIndexes, indexesLength, index + 1) - offset;
145
173
    if(length >= 256) {
146
75
        if(reorderCodesLength == 0) {
147
0
            errorCode = U_INVALID_FORMAT_ERROR;  // Reordering table without reordering codes.
148
0
            return;
149
0
        }
150
75
        reorderTable = inBytes + offset;
151
98
    } else {
152
        // If we have reorder codes, then build the reorderTable at the end,
153
        // when the CollationData is otherwise complete.
154
98
    }
155
156
173
    if(baseData != nullptr && baseData->numericPrimary != (inIndexes[IX_OPTIONS] & 0xff000000)) {
157
0
        errorCode = U_INVALID_FORMAT_ERROR;
158
0
        return;
159
0
    }
160
173
    CollationData *data = nullptr;  // Remains nullptr if there are no mappings.
161
162
173
    index = IX_TRIE_OFFSET;
163
173
    offset = getIndex(inIndexes, indexesLength, index);
164
173
    length = getIndex(inIndexes, indexesLength, index + 1) - offset;
165
173
    if(length >= 8) {
166
152
        if(!tailoring.ensureOwnedData(errorCode)) { return; }
167
152
        data = tailoring.ownedData;
168
152
        data->base = baseData;
169
152
        data->numericPrimary = inIndexes[IX_OPTIONS] & 0xff000000;
170
152
        data->trie = tailoring.trie = utrie2_openFromSerialized(
171
152
            UTRIE2_32_VALUE_BITS, inBytes + offset, length, nullptr,
172
152
            &errorCode);
173
152
        if(U_FAILURE(errorCode)) { return; }
174
152
    } else if(baseData != nullptr) {
175
        // Use the base data. Only the settings are tailored.
176
21
        tailoring.data = baseData;
177
21
    } else {
178
0
        errorCode = U_INVALID_FORMAT_ERROR;  // No mappings.
179
0
        return;
180
0
    }
181
182
173
    index = IX_CES_OFFSET;
183
173
    offset = getIndex(inIndexes, indexesLength, index);
184
173
    length = getIndex(inIndexes, indexesLength, index + 1) - offset;
185
173
    if(length >= 8) {
186
40
        if(data == nullptr) {
187
0
            errorCode = U_INVALID_FORMAT_ERROR;  // Tailored ces without tailored trie.
188
0
            return;
189
0
        }
190
40
        data->ces = reinterpret_cast<const int64_t *>(inBytes + offset);
191
40
        data->cesLength = length / 8;
192
40
    }
193
194
173
    index = IX_CE32S_OFFSET;
195
173
    offset = getIndex(inIndexes, indexesLength, index);
196
173
    length = getIndex(inIndexes, indexesLength, index + 1) - offset;
197
173
    if(length >= 4) {
198
152
        if(data == nullptr) {
199
0
            errorCode = U_INVALID_FORMAT_ERROR;  // Tailored ce32s without tailored trie.
200
0
            return;
201
0
        }
202
152
        data->ce32s = reinterpret_cast<const uint32_t *>(inBytes + offset);
203
152
        data->ce32sLength = length / 4;
204
152
    }
205
206
173
    int32_t jamoCE32sStart = getIndex(inIndexes, indexesLength, IX_JAMO_CE32S_START);
207
173
    if(jamoCE32sStart >= 0) {
208
13
        if(data == nullptr || data->ce32s == nullptr) {
209
0
            errorCode = U_INVALID_FORMAT_ERROR;  // Index into non-existent ce32s[].
210
0
            return;
211
0
        }
212
13
        data->jamoCE32s = data->ce32s + jamoCE32sStart;
213
160
    } else if(data == nullptr) {
214
        // Nothing to do.
215
139
    } else if(baseData != nullptr) {
216
139
        data->jamoCE32s = baseData->jamoCE32s;
217
139
    } else {
218
0
        errorCode = U_INVALID_FORMAT_ERROR;  // No Jamo CE32s for Hangul processing.
219
0
        return;
220
0
    }
221
222
173
    index = IX_ROOT_ELEMENTS_OFFSET;
223
173
    offset = getIndex(inIndexes, indexesLength, index);
224
173
    length = getIndex(inIndexes, indexesLength, index + 1) - offset;
225
173
    if(length >= 4) {
226
2
        length /= 4;
227
2
        if(data == nullptr || length <= CollationRootElements::IX_SEC_TER_BOUNDARIES) {
228
0
            errorCode = U_INVALID_FORMAT_ERROR;
229
0
            return;
230
0
        }
231
2
        data->rootElements = reinterpret_cast<const uint32_t *>(inBytes + offset);
232
2
        data->rootElementsLength = length;
233
2
        uint32_t commonSecTer = data->rootElements[CollationRootElements::IX_COMMON_SEC_AND_TER_CE];
234
2
        if(commonSecTer != Collation::COMMON_SEC_AND_TER_CE) {
235
0
            errorCode = U_INVALID_FORMAT_ERROR;
236
0
            return;
237
0
        }
238
2
        uint32_t secTerBoundaries = data->rootElements[CollationRootElements::IX_SEC_TER_BOUNDARIES];
239
2
        if((secTerBoundaries >> 24) < CollationKeys::SEC_COMMON_HIGH) {
240
            // [fixed last secondary common byte] is too low,
241
            // and secondary weights would collide with compressed common secondaries.
242
0
            errorCode = U_INVALID_FORMAT_ERROR;
243
0
            return;
244
0
        }
245
2
    }
246
247
173
    index = IX_CONTEXTS_OFFSET;
248
173
    offset = getIndex(inIndexes, indexesLength, index);
249
173
    length = getIndex(inIndexes, indexesLength, index + 1) - offset;
250
173
    if(length >= 2) {
251
133
        if(data == nullptr) {
252
0
            errorCode = U_INVALID_FORMAT_ERROR;  // Tailored contexts without tailored trie.
253
0
            return;
254
0
        }
255
133
        data->contexts = reinterpret_cast<const char16_t *>(inBytes + offset);
256
133
        data->contextsLength = length / 2;
257
133
    }
258
259
173
    index = IX_UNSAFE_BWD_OFFSET;
260
173
    offset = getIndex(inIndexes, indexesLength, index);
261
173
    length = getIndex(inIndexes, indexesLength, index + 1) - offset;
262
173
    if(length >= 2) {
263
63
        if(data == nullptr) {
264
0
            errorCode = U_INVALID_FORMAT_ERROR;
265
0
            return;
266
0
        }
267
63
        if(baseData == nullptr) {
268
2
#if defined(COLLUNSAFE_COLL_VERSION) && defined (COLLUNSAFE_SERIALIZE)
269
2
          tailoring.unsafeBackwardSet = new UnicodeSet(unsafe_serializedData, unsafe_serializedCount, UnicodeSet::kSerialized, errorCode);
270
2
          if(tailoring.unsafeBackwardSet == nullptr) {
271
0
            errorCode = U_MEMORY_ALLOCATION_ERROR;
272
0
            return;
273
2
          } else if (U_FAILURE(errorCode)) {
274
0
            return;
275
0
          }
276
#else
277
            // Create the unsafe-backward set for the root collator.
278
            // Include all non-zero combining marks and trail surrogates.
279
            // We do this at load time, rather than at build time,
280
            // to simplify Unicode version bootstrapping:
281
            // The root data builder only needs the new FractionalUCA.txt data,
282
            // but it need not be built with a version of ICU already updated to
283
            // the corresponding new Unicode Character Database.
284
            //
285
            // The following is an optimized version of
286
            // new UnicodeSet("[[:^lccc=0:][\\udc00-\\udfff]]").
287
            // It is faster and requires fewer code dependencies.
288
            tailoring.unsafeBackwardSet = new UnicodeSet(0xdc00, 0xdfff);  // trail surrogates
289
            if(tailoring.unsafeBackwardSet == nullptr) {
290
                errorCode = U_MEMORY_ALLOCATION_ERROR;
291
                return;
292
            }
293
            data->nfcImpl.addLcccChars(*tailoring.unsafeBackwardSet);
294
#endif // !COLLUNSAFE_SERIALIZE || !COLLUNSAFE_COLL_VERSION
295
61
        } else {
296
            // Clone the root collator's set contents.
297
61
            tailoring.unsafeBackwardSet = static_cast<UnicodeSet *>(
298
61
                baseData->unsafeBackwardSet->cloneAsThawed());
299
61
            if(tailoring.unsafeBackwardSet == nullptr) {
300
0
                errorCode = U_MEMORY_ALLOCATION_ERROR;
301
0
                return;
302
0
            }
303
61
        }
304
        // Add the ranges from the data file to the unsafe-backward set.
305
63
        USerializedSet sset;
306
63
        const uint16_t *unsafeData = reinterpret_cast<const uint16_t *>(inBytes + offset);
307
63
        if(!uset_getSerializedSet(&sset, unsafeData, length / 2)) {
308
0
            errorCode = U_INVALID_FORMAT_ERROR;
309
0
            return;
310
0
        }
311
63
        int32_t count = uset_getSerializedRangeCount(&sset);
312
1.58k
        for(int32_t i = 0; i < count; ++i) {
313
1.52k
            UChar32 start, end;
314
1.52k
            uset_getSerializedRange(&sset, i, &start, &end);
315
1.52k
            tailoring.unsafeBackwardSet->add(start, end);
316
1.52k
        }
317
        // Mark each lead surrogate as "unsafe"
318
        // if any of its 1024 associated supplementary code points is "unsafe".
319
63
        UChar32 c = 0x10000;
320
64.5k
        for(char16_t lead = 0xd800; lead < 0xdc00; ++lead, c += 0x400) {
321
64.5k
            if(!tailoring.unsafeBackwardSet->containsNone(c, c + 0x3ff)) {
322
1.45k
                tailoring.unsafeBackwardSet->add(lead);
323
1.45k
            }
324
64.5k
        }
325
63
        tailoring.unsafeBackwardSet->freeze();
326
63
        data->unsafeBackwardSet = tailoring.unsafeBackwardSet;
327
110
    } else if(data == nullptr) {
328
        // Nothing to do.
329
89
    } else if(baseData != nullptr) {
330
        // No tailoring-specific data: Alias the root collator's set.
331
89
        data->unsafeBackwardSet = baseData->unsafeBackwardSet;
332
89
    } else {
333
0
        errorCode = U_INVALID_FORMAT_ERROR;  // No unsafeBackwardSet.
334
0
        return;
335
0
    }
336
337
    // If the fast Latin format version is different,
338
    // or the version is set to 0 for "no fast Latin table",
339
    // then just always use the normal string comparison path.
340
173
    if(data != nullptr) {
341
152
        data->fastLatinTable = nullptr;
342
152
        data->fastLatinTableLength = 0;
343
152
        if(((inIndexes[IX_OPTIONS] >> 16) & 0xff) == CollationFastLatin::VERSION) {
344
138
            index = IX_FAST_LATIN_TABLE_OFFSET;
345
138
            offset = getIndex(inIndexes, indexesLength, index);
346
138
            length = getIndex(inIndexes, indexesLength, index + 1) - offset;
347
138
            if(length >= 2) {
348
92
                data->fastLatinTable = reinterpret_cast<const uint16_t *>(inBytes + offset);
349
92
                data->fastLatinTableLength = length / 2;
350
92
                if((*data->fastLatinTable >> 8) != CollationFastLatin::VERSION) {
351
0
                    errorCode = U_INVALID_FORMAT_ERROR;  // header vs. table version mismatch
352
0
                    return;
353
0
                }
354
92
            } else if(baseData != nullptr) {
355
46
                data->fastLatinTable = baseData->fastLatinTable;
356
46
                data->fastLatinTableLength = baseData->fastLatinTableLength;
357
46
            }
358
138
        }
359
152
    }
360
361
173
    index = IX_SCRIPTS_OFFSET;
362
173
    offset = getIndex(inIndexes, indexesLength, index);
363
173
    length = getIndex(inIndexes, indexesLength, index + 1) - offset;
364
173
    if(length >= 2) {
365
2
        if(data == nullptr) {
366
0
            errorCode = U_INVALID_FORMAT_ERROR;
367
0
            return;
368
0
        }
369
2
        const uint16_t *scripts = reinterpret_cast<const uint16_t *>(inBytes + offset);
370
2
        int32_t scriptsLength = length / 2;
371
2
        data->numScripts = scripts[0];
372
        // There must be enough entries for both arrays, including more than two range starts.
373
2
        data->scriptStartsLength = scriptsLength - (1 + data->numScripts + 16);
374
2
        if(data->scriptStartsLength <= 2 ||
375
2
                CollationData::MAX_NUM_SCRIPT_RANGES < data->scriptStartsLength) {
376
0
            errorCode = U_INVALID_FORMAT_ERROR;
377
0
            return;
378
0
        }
379
2
        data->scriptsIndex = scripts + 1;
380
2
        data->scriptStarts = scripts + 1 + data->numScripts + 16;
381
2
        if(!(data->scriptStarts[0] == 0 &&
382
2
                data->scriptStarts[1] == ((Collation::MERGE_SEPARATOR_BYTE + 1) << 8) &&
383
2
                data->scriptStarts[data->scriptStartsLength - 1] ==
384
2
                        (Collation::TRAIL_WEIGHT_BYTE << 8))) {
385
0
            errorCode = U_INVALID_FORMAT_ERROR;
386
0
            return;
387
0
        }
388
171
    } else if(data == nullptr) {
389
        // Nothing to do.
390
150
    } else if(baseData != nullptr) {
391
150
        data->numScripts = baseData->numScripts;
392
150
        data->scriptsIndex = baseData->scriptsIndex;
393
150
        data->scriptStarts = baseData->scriptStarts;
394
150
        data->scriptStartsLength = baseData->scriptStartsLength;
395
150
    }
396
397
173
    index = IX_COMPRESSIBLE_BYTES_OFFSET;
398
173
    offset = getIndex(inIndexes, indexesLength, index);
399
173
    length = getIndex(inIndexes, indexesLength, index + 1) - offset;
400
173
    if(length >= 256) {
401
2
        if(data == nullptr) {
402
0
            errorCode = U_INVALID_FORMAT_ERROR;
403
0
            return;
404
0
        }
405
2
        data->compressibleBytes = reinterpret_cast<const UBool *>(inBytes + offset);
406
171
    } else if(data == nullptr) {
407
        // Nothing to do.
408
150
    } else if(baseData != nullptr) {
409
150
        data->compressibleBytes = baseData->compressibleBytes;
410
150
    } else {
411
0
        errorCode = U_INVALID_FORMAT_ERROR;  // No compressibleBytes[].
412
0
        return;
413
0
    }
414
415
173
    const CollationSettings &ts = *tailoring.settings;
416
173
    int32_t options = inIndexes[IX_OPTIONS] & 0xffff;
417
173
    uint16_t fastLatinPrimaries[CollationFastLatin::LATIN_LIMIT];
418
173
    int32_t fastLatinOptions = CollationFastLatin::getOptions(
419
173
            tailoring.data, ts, fastLatinPrimaries, UPRV_LENGTHOF(fastLatinPrimaries));
420
173
    if(options == ts.options && ts.variableTop != 0 &&
421
123
            reorderCodesLength == ts.reorderCodesLength &&
422
74
            (reorderCodesLength == 0 ||
423
74
                uprv_memcmp(reorderCodes, ts.reorderCodes, reorderCodesLength * 4) == 0) &&
424
74
            fastLatinOptions == ts.fastLatinOptions &&
425
71
            (fastLatinOptions < 0 ||
426
71
                uprv_memcmp(fastLatinPrimaries, ts.fastLatinPrimaries,
427
71
                            sizeof(fastLatinPrimaries)) == 0)) {
428
3
        return;
429
3
    }
430
431
170
    CollationSettings *settings = SharedObject::copyOnWrite(tailoring.settings);
432
170
    if(settings == nullptr) {
433
0
        errorCode = U_MEMORY_ALLOCATION_ERROR;
434
0
        return;
435
0
    }
436
170
    settings->options = options;
437
    // Set variableTop from options and scripts data.
438
170
    settings->variableTop = tailoring.data->getLastPrimaryForGroup(
439
170
            UCOL_REORDER_CODE_FIRST + int32_t{settings->getMaxVariable()});
440
170
    if(settings->variableTop == 0) {
441
0
        errorCode = U_INVALID_FORMAT_ERROR;
442
0
        return;
443
0
    }
444
445
170
    if(reorderCodesLength != 0) {
446
75
        settings->aliasReordering(*baseData, reorderCodes, reorderCodesLength,
447
75
                                  reorderRanges, reorderRangesLength,
448
75
                                  reorderTable, errorCode);
449
75
    }
450
451
170
    settings->fastLatinOptions = CollationFastLatin::getOptions(
452
170
        tailoring.data, *settings,
453
170
        settings->fastLatinPrimaries, UPRV_LENGTHOF(settings->fastLatinPrimaries));
454
170
}
455
456
UBool U_CALLCONV
457
CollationDataReader::isAcceptable(void *context,
458
                                  const char * /* type */, const char * /*name*/,
459
173
                                  const UDataInfo *pInfo) {
460
173
    if(
461
173
        pInfo->size >= 20 &&
462
173
        pInfo->isBigEndian == U_IS_BIG_ENDIAN &&
463
173
        pInfo->charsetFamily == U_CHARSET_FAMILY &&
464
173
        pInfo->dataFormat[0] == 0x55 &&  // dataFormat="UCol"
465
173
        pInfo->dataFormat[1] == 0x43 &&
466
173
        pInfo->dataFormat[2] == 0x6f &&
467
173
        pInfo->dataFormat[3] == 0x6c &&
468
173
        pInfo->formatVersion[0] == 5
469
173
    ) {
470
173
        UVersionInfo *version = static_cast<UVersionInfo *>(context);
471
173
        if(version != nullptr) {
472
173
            uprv_memcpy(version, pInfo->dataVersion, 4);
473
173
        }
474
173
        return true;
475
173
    } else {
476
0
        return false;
477
0
    }
478
173
}
479
480
U_NAMESPACE_END
481
482
#endif  // !UCONFIG_NO_COLLATION