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