Coverage Report

Created: 2023-02-22 06:51

/src/icu/source/common/rbbidata.cpp
Line
Count
Source (jump to first uncovered line)
1
// © 2016 and later: Unicode, Inc. and others.
2
// License & terms of use: http://www.unicode.org/copyright.html
3
/*
4
***************************************************************************
5
*   Copyright (C) 1999-2014 International Business Machines Corporation   *
6
*   and others. All rights reserved.                                      *
7
***************************************************************************
8
*/
9
10
#include "unicode/utypes.h"
11
12
#if !UCONFIG_NO_BREAK_ITERATION
13
14
#include "unicode/ucptrie.h"
15
#include "unicode/utypes.h"
16
#include "rbbidata.h"
17
#include "rbbirb.h"
18
#include "udatamem.h"
19
#include "cmemory.h"
20
#include "cstring.h"
21
#include "umutex.h"
22
23
#include "uassert.h"
24
25
26
U_NAMESPACE_BEGIN
27
28
//-----------------------------------------------------------------------------
29
//
30
//    Constructors.
31
//
32
//-----------------------------------------------------------------------------
33
0
RBBIDataWrapper::RBBIDataWrapper(const RBBIDataHeader *data, UErrorCode &status) {
34
0
    init0();
35
0
    init(data, status);
36
0
}
37
38
0
RBBIDataWrapper::RBBIDataWrapper(const RBBIDataHeader *data, enum EDontAdopt, UErrorCode &status) {
39
0
    init0();
40
0
    init(data, status);
41
0
    fDontFreeData = TRUE;
42
0
}
43
44
0
RBBIDataWrapper::RBBIDataWrapper(UDataMemory* udm, UErrorCode &status) {
45
0
    init0();
46
0
    if (U_FAILURE(status)) {
47
0
        return;
48
0
    }
49
0
    const DataHeader *dh = udm->pHeader;
50
0
    int32_t headerSize = dh->dataHeader.headerSize;
51
0
    if (  !(headerSize >= 20 &&
52
0
            dh->info.isBigEndian == U_IS_BIG_ENDIAN &&
53
0
            dh->info.charsetFamily == U_CHARSET_FAMILY &&
54
0
            dh->info.dataFormat[0] == 0x42 &&  // dataFormat="Brk "
55
0
            dh->info.dataFormat[1] == 0x72 &&
56
0
            dh->info.dataFormat[2] == 0x6b &&
57
0
            dh->info.dataFormat[3] == 0x20 &&
58
0
            isDataVersionAcceptable(dh->info.formatVersion))
59
0
        ) {
60
0
        status = U_INVALID_FORMAT_ERROR;
61
0
        return;
62
0
    }
63
0
    const char *dataAsBytes = reinterpret_cast<const char *>(dh);
64
0
    const RBBIDataHeader *rbbidh = reinterpret_cast<const RBBIDataHeader *>(dataAsBytes + headerSize);
65
0
    init(rbbidh, status);
66
0
    fUDataMem = udm;
67
0
}
68
69
0
UBool RBBIDataWrapper::isDataVersionAcceptable(const UVersionInfo version) {
70
0
    return RBBI_DATA_FORMAT_VERSION[0] == version[0];
71
0
}
72
73
74
//-----------------------------------------------------------------------------
75
//
76
//    init().   Does most of the work of construction, shared between the
77
//              constructors.
78
//
79
//-----------------------------------------------------------------------------
80
0
void RBBIDataWrapper::init0() {
81
0
    fHeader = NULL;
82
0
    fForwardTable = NULL;
83
0
    fReverseTable = NULL;
84
0
    fRuleSource   = NULL;
85
0
    fRuleStatusTable = NULL;
86
0
    fTrie         = NULL;
87
0
    fUDataMem     = NULL;
88
0
    fRefCount     = 0;
89
0
    fDontFreeData = TRUE;
90
0
}
91
92
0
void RBBIDataWrapper::init(const RBBIDataHeader *data, UErrorCode &status) {
93
0
    if (U_FAILURE(status)) {
94
0
        return;
95
0
    }
96
0
    fHeader = data;
97
0
    if (fHeader->fMagic != 0xb1a0 || !isDataVersionAcceptable(fHeader->fFormatVersion)) {
98
0
        status = U_INVALID_FORMAT_ERROR;
99
0
        return;
100
0
    }
101
    // Note: in ICU version 3.2 and earlier, there was a formatVersion 1
102
    //       that is no longer supported.  At that time fFormatVersion was
103
    //       an int32_t field, rather than an array of 4 bytes.
104
105
0
    fDontFreeData = FALSE;
106
0
    if (data->fFTableLen != 0) {
107
0
        fForwardTable = (RBBIStateTable *)((char *)data + fHeader->fFTable);
108
0
    }
109
0
    if (data->fRTableLen != 0) {
110
0
        fReverseTable = (RBBIStateTable *)((char *)data + fHeader->fRTable);
111
0
    }
112
113
0
    fTrie = ucptrie_openFromBinary(UCPTRIE_TYPE_FAST,
114
0
                                   UCPTRIE_VALUE_BITS_ANY,
115
0
                                   (uint8_t *)data + fHeader->fTrie,
116
0
                                   fHeader->fTrieLen,
117
0
                                   nullptr,           // *actual length
118
0
                                   &status);
119
0
    if (U_FAILURE(status)) {
120
0
        return;
121
0
    }
122
123
0
    UCPTrieValueWidth width = ucptrie_getValueWidth(fTrie);
124
0
    if (!(width == UCPTRIE_VALUE_BITS_8 || width == UCPTRIE_VALUE_BITS_16)) {
125
0
        status = U_INVALID_FORMAT_ERROR;
126
0
        return;
127
0
    }
128
129
0
    fRuleSource   = ((char *)data + fHeader->fRuleSource);
130
0
    fRuleString = UnicodeString::fromUTF8(StringPiece(fRuleSource, fHeader->fRuleSourceLen));
131
0
    U_ASSERT(data->fRuleSourceLen > 0);
132
133
0
    fRuleStatusTable = (int32_t *)((char *)data + fHeader->fStatusTable);
134
0
    fStatusMaxIdx    = data->fStatusTableLen / sizeof(int32_t);
135
136
0
    fRefCount = 1;
137
138
#ifdef RBBI_DEBUG
139
    char *debugEnv = getenv("U_RBBIDEBUG");
140
    if (debugEnv && uprv_strstr(debugEnv, "data")) {this->printData();}
141
#endif
142
0
}
143
144
145
//-----------------------------------------------------------------------------
146
//
147
//    Destructor.     Don't call this - use removeReference() instead.
148
//
149
//-----------------------------------------------------------------------------
150
0
RBBIDataWrapper::~RBBIDataWrapper() {
151
0
    U_ASSERT(fRefCount == 0);
152
0
    ucptrie_close(fTrie);
153
0
    fTrie = nullptr;
154
0
    if (fUDataMem) {
155
0
        udata_close(fUDataMem);
156
0
    } else if (!fDontFreeData) {
157
0
        uprv_free((void *)fHeader);
158
0
    }
159
0
}
160
161
162
163
//-----------------------------------------------------------------------------
164
//
165
//   Operator ==    Consider two RBBIDataWrappers to be equal if they
166
//                  refer to the same underlying data.  Although
167
//                  the data wrappers are normally shared between
168
//                  iterator instances, it's possible to independently
169
//                  open the same data twice, and get two instances, which
170
//                  should still be ==.
171
//
172
//-----------------------------------------------------------------------------
173
0
bool RBBIDataWrapper::operator ==(const RBBIDataWrapper &other) const {
174
0
    if (fHeader == other.fHeader) {
175
0
        return TRUE;
176
0
    }
177
0
    if (fHeader->fLength != other.fHeader->fLength) {
178
0
        return FALSE;
179
0
    }
180
0
    if (uprv_memcmp(fHeader, other.fHeader, fHeader->fLength) == 0) {
181
0
        return TRUE;
182
0
    }
183
0
    return FALSE;
184
0
}
185
186
0
int32_t  RBBIDataWrapper::hashCode() {
187
0
    return fHeader->fFTableLen;
188
0
}
189
190
191
192
//-----------------------------------------------------------------------------
193
//
194
//    Reference Counting.   A single RBBIDataWrapper object is shared among
195
//                          however many RulesBasedBreakIterator instances are
196
//                          referencing the same data.
197
//
198
//-----------------------------------------------------------------------------
199
0
void RBBIDataWrapper::removeReference() {
200
0
    if (umtx_atomic_dec(&fRefCount) == 0) {
201
0
        delete this;
202
0
    }
203
0
}
204
205
206
0
RBBIDataWrapper *RBBIDataWrapper::addReference() {
207
0
   umtx_atomic_inc(&fRefCount);
208
0
   return this;
209
0
}
210
211
212
213
//-----------------------------------------------------------------------------
214
//
215
//  getRuleSourceString
216
//
217
//-----------------------------------------------------------------------------
218
0
const UnicodeString &RBBIDataWrapper::getRuleSourceString() const {
219
0
    return fRuleString;
220
0
}
221
222
223
//-----------------------------------------------------------------------------
224
//
225
//  print   -  debugging function to dump the runtime data tables.
226
//
227
//-----------------------------------------------------------------------------
228
#ifdef RBBI_DEBUG
229
void  RBBIDataWrapper::printTable(const char *heading, const RBBIStateTable *table) {
230
    uint32_t   c;
231
    uint32_t   s;
232
233
    RBBIDebugPrintf("%s\n", heading);
234
235
    RBBIDebugPrintf("   fDictCategoriesStart: %d\n", table->fDictCategoriesStart);
236
    RBBIDebugPrintf("   fLookAheadResultsSize: %d\n", table->fLookAheadResultsSize);
237
    RBBIDebugPrintf("   Flags: %4x RBBI_LOOKAHEAD_HARD_BREAK=%s RBBI_BOF_REQUIRED=%s  RBBI_8BITS_ROWS=%s\n",
238
                    table->fFlags,
239
                    table->fFlags & RBBI_LOOKAHEAD_HARD_BREAK ? "T" : "F",
240
                    table->fFlags & RBBI_BOF_REQUIRED ? "T" : "F",
241
                    table->fFlags & RBBI_8BITS_ROWS ? "T" : "F");
242
    RBBIDebugPrintf("\nState |  Acc  LA TagIx");
243
    for (c=0; c<fHeader->fCatCount; c++) {RBBIDebugPrintf("%3d ", c);}
244
    RBBIDebugPrintf("\n------|---------------"); for (c=0;c<fHeader->fCatCount; c++) {
245
        RBBIDebugPrintf("----");
246
    }
247
    RBBIDebugPrintf("\n");
248
249
    if (table == NULL) {
250
        RBBIDebugPrintf("         N U L L   T A B L E\n\n");
251
        return;
252
    }
253
    UBool use8Bits = table->fFlags & RBBI_8BITS_ROWS;
254
    for (s=0; s<table->fNumStates; s++) {
255
        RBBIStateTableRow *row = (RBBIStateTableRow *)
256
                                  (table->fTableData + (table->fRowLen * s));
257
        if (use8Bits) {
258
            RBBIDebugPrintf("%4d  |  %3d %3d %3d ", s, row->r8.fAccepting, row->r8.fLookAhead, row->r8.fTagsIdx);
259
            for (c=0; c<fHeader->fCatCount; c++)  {
260
                RBBIDebugPrintf("%3d ", row->r8.fNextState[c]);
261
            }
262
        } else {
263
            RBBIDebugPrintf("%4d  |  %3d %3d %3d ", s, row->r16.fAccepting, row->r16.fLookAhead, row->r16.fTagsIdx);
264
            for (c=0; c<fHeader->fCatCount; c++)  {
265
                RBBIDebugPrintf("%3d ", row->r16.fNextState[c]);
266
            }
267
        }
268
        RBBIDebugPrintf("\n");
269
    }
270
    RBBIDebugPrintf("\n");
271
}
272
#endif
273
274
275
0
void  RBBIDataWrapper::printData() {
276
#ifdef RBBI_DEBUG
277
    RBBIDebugPrintf("RBBI Data at %p\n", (void *)fHeader);
278
    RBBIDebugPrintf("   Version = {%d %d %d %d}\n", fHeader->fFormatVersion[0], fHeader->fFormatVersion[1],
279
                                                    fHeader->fFormatVersion[2], fHeader->fFormatVersion[3]);
280
    RBBIDebugPrintf("   total length of data  = %d\n", fHeader->fLength);
281
    RBBIDebugPrintf("   number of character categories = %d\n\n", fHeader->fCatCount);
282
283
    printTable("Forward State Transition Table", fForwardTable);
284
    printTable("Reverse State Transition Table", fReverseTable);
285
286
    RBBIDebugPrintf("\nOriginal Rules source:\n");
287
    for (int32_t c=0; fRuleSource[c] != 0; c++) {
288
        RBBIDebugPrintf("%c", fRuleSource[c]);
289
    }
290
    RBBIDebugPrintf("\n\n");
291
#endif
292
0
}
293
294
295
U_NAMESPACE_END
296
U_NAMESPACE_USE
297
298
//-----------------------------------------------------------------------------
299
//
300
//  ubrk_swap   -  byte swap and char encoding swap of RBBI data
301
//
302
//-----------------------------------------------------------------------------
303
304
U_CAPI int32_t U_EXPORT2
305
ubrk_swap(const UDataSwapper *ds, const void *inData, int32_t length, void *outData,
306
0
           UErrorCode *status) {
307
308
0
    if (status == NULL || U_FAILURE(*status)) {
309
0
        return 0;
310
0
    }
311
0
    if(ds==NULL || inData==NULL || length<-1 || (length>0 && outData==NULL)) {
312
0
        *status=U_ILLEGAL_ARGUMENT_ERROR;
313
0
        return 0;
314
0
    }
315
316
    //
317
    //  Check that the data header is for for break data.
318
    //    (Header contents are defined in genbrk.cpp)
319
    //
320
0
    const UDataInfo *pInfo = (const UDataInfo *)((const char *)inData+4);
321
0
    if(!(  pInfo->dataFormat[0]==0x42 &&   /* dataFormat="Brk " */
322
0
           pInfo->dataFormat[1]==0x72 &&
323
0
           pInfo->dataFormat[2]==0x6b &&
324
0
           pInfo->dataFormat[3]==0x20 &&
325
0
           RBBIDataWrapper::isDataVersionAcceptable(pInfo->formatVersion) )) {
326
0
        udata_printError(ds, "ubrk_swap(): data format %02x.%02x.%02x.%02x (format version %02x) is not recognized\n",
327
0
                         pInfo->dataFormat[0], pInfo->dataFormat[1],
328
0
                         pInfo->dataFormat[2], pInfo->dataFormat[3],
329
0
                         pInfo->formatVersion[0]);
330
0
        *status=U_UNSUPPORTED_ERROR;
331
0
        return 0;
332
0
    }
333
334
    //
335
    // Swap the data header.  (This is the generic ICU Data Header, not the RBBI Specific
336
    //                         RBBIDataHeader).  This swap also conveniently gets us
337
    //                         the size of the ICU d.h., which lets us locate the start
338
    //                         of the RBBI specific data.
339
    //
340
0
    int32_t headerSize=udata_swapDataHeader(ds, inData, length, outData, status);
341
342
343
    //
344
    // Get the RRBI Data Header, and check that it appears to be OK.
345
    //
346
0
    const uint8_t  *inBytes =(const uint8_t *)inData+headerSize;
347
0
    RBBIDataHeader *rbbiDH = (RBBIDataHeader *)inBytes;
348
0
    if (ds->readUInt32(rbbiDH->fMagic) != 0xb1a0 || 
349
0
            !RBBIDataWrapper::isDataVersionAcceptable(rbbiDH->fFormatVersion) ||
350
0
            ds->readUInt32(rbbiDH->fLength)  <  sizeof(RBBIDataHeader)) {
351
0
        udata_printError(ds, "ubrk_swap(): RBBI Data header is invalid.\n");
352
0
        *status=U_UNSUPPORTED_ERROR;
353
0
        return 0;
354
0
    }
355
356
    //
357
    // Prefight operation?  Just return the size
358
    //
359
0
    int32_t breakDataLength = ds->readUInt32(rbbiDH->fLength);
360
0
    int32_t totalSize = headerSize + breakDataLength;
361
0
    if (length < 0) {
362
0
        return totalSize;
363
0
    }
364
365
    //
366
    // Check that length passed in is consistent with length from RBBI data header.
367
    //
368
0
    if (length < totalSize) {
369
0
        udata_printError(ds, "ubrk_swap(): too few bytes (%d after ICU Data header) for break data.\n",
370
0
                            breakDataLength);
371
0
        *status=U_INDEX_OUTOFBOUNDS_ERROR;
372
0
        return 0;
373
0
        }
374
375
376
    //
377
    // Swap the Data.  Do the data itself first, then the RBBI Data Header, because
378
    //                 we need to reference the header to locate the data, and an
379
    //                 inplace swap of the header leaves it unusable.
380
    //
381
0
    uint8_t         *outBytes = (uint8_t *)outData + headerSize;
382
0
    RBBIDataHeader  *outputDH = (RBBIDataHeader *)outBytes;
383
384
0
    int32_t   tableStartOffset;
385
0
    int32_t   tableLength;
386
387
    //
388
    // If not swapping in place, zero out the output buffer before starting.
389
    //    Individual tables and other data items within are aligned to 8 byte boundaries
390
    //    when originally created.  Any unused space between items needs to be zero.
391
    //
392
0
    if (inBytes != outBytes) {
393
0
        uprv_memset(outBytes, 0, breakDataLength);
394
0
    }
395
396
    //
397
    // Each state table begins with several 32 bit fields.  Calculate the size
398
    //   in bytes of these.
399
    //
400
0
    int32_t         topSize = offsetof(RBBIStateTable, fTableData);
401
402
    // Forward state table.
403
0
    tableStartOffset = ds->readUInt32(rbbiDH->fFTable);
404
0
    tableLength      = ds->readUInt32(rbbiDH->fFTableLen);
405
406
0
    if (tableLength > 0) {
407
0
        RBBIStateTable *rbbiST = (RBBIStateTable *)(inBytes+tableStartOffset);
408
0
        UBool use8Bits = ds->readUInt32(rbbiST->fFlags) & RBBI_8BITS_ROWS;
409
410
0
        ds->swapArray32(ds, inBytes+tableStartOffset, topSize,
411
0
                            outBytes+tableStartOffset, status);
412
413
        // Swap the state table if the table is in 16 bits.
414
0
        if (use8Bits) {
415
0
            if (outBytes != inBytes) {
416
0
                uprv_memmove(outBytes+tableStartOffset+topSize,
417
0
                             inBytes+tableStartOffset+topSize,
418
0
                             tableLength-topSize);
419
0
            }
420
0
        } else {
421
0
            ds->swapArray16(ds, inBytes+tableStartOffset+topSize, tableLength-topSize,
422
0
                                outBytes+tableStartOffset+topSize, status);
423
0
        }
424
0
    }
425
426
    // Reverse state table.  Same layout as forward table, above.
427
0
    tableStartOffset = ds->readUInt32(rbbiDH->fRTable);
428
0
    tableLength      = ds->readUInt32(rbbiDH->fRTableLen);
429
430
0
    if (tableLength > 0) {
431
0
        RBBIStateTable *rbbiST = (RBBIStateTable *)(inBytes+tableStartOffset);
432
0
        UBool use8Bits = ds->readUInt32(rbbiST->fFlags) & RBBI_8BITS_ROWS;
433
434
0
        ds->swapArray32(ds, inBytes+tableStartOffset, topSize,
435
0
                            outBytes+tableStartOffset, status);
436
437
        // Swap the state table if the table is in 16 bits.
438
0
        if (use8Bits) {
439
0
            if (outBytes != inBytes) {
440
0
                uprv_memmove(outBytes+tableStartOffset+topSize,
441
0
                             inBytes+tableStartOffset+topSize,
442
0
                             tableLength-topSize);
443
0
            }
444
0
        } else {
445
0
            ds->swapArray16(ds, inBytes+tableStartOffset+topSize, tableLength-topSize,
446
0
                                outBytes+tableStartOffset+topSize, status);
447
0
        }
448
0
    }
449
450
    // Trie table for character categories
451
0
    ucptrie_swap(ds, inBytes+ds->readUInt32(rbbiDH->fTrie), ds->readUInt32(rbbiDH->fTrieLen),
452
0
                     outBytes+ds->readUInt32(rbbiDH->fTrie), status);
453
454
    // Source Rules Text.  It's UTF8 data
455
0
    if (outBytes != inBytes) {
456
0
        uprv_memmove(outBytes+ds->readUInt32(rbbiDH->fRuleSource),
457
0
                     inBytes+ds->readUInt32(rbbiDH->fRuleSource),
458
0
                     ds->readUInt32(rbbiDH->fRuleSourceLen));
459
0
    }
460
461
    // Table of rule status values.  It's all int_32 values
462
0
    ds->swapArray32(ds, inBytes+ds->readUInt32(rbbiDH->fStatusTable), ds->readUInt32(rbbiDH->fStatusTableLen),
463
0
                        outBytes+ds->readUInt32(rbbiDH->fStatusTable), status);
464
465
    // And, last, the header.
466
    //   It is all int32_t values except for fFormataVersion, which is an array of four bytes.
467
    //   Swap the whole thing as int32_t, then re-swap the one field.
468
    //
469
0
    ds->swapArray32(ds, inBytes, sizeof(RBBIDataHeader), outBytes, status);
470
0
    ds->swapArray32(ds, outputDH->fFormatVersion, 4, outputDH->fFormatVersion, status);
471
472
0
    return totalSize;
473
0
}
474
475
476
#endif /* #if !UCONFIG_NO_BREAK_ITERATION */