Debian Codegraph @

src/DartsDictTest.cpp

raw symbols SCIP
1 /*
2 * Open Chinese Convert
3 *
4 * Copyright 2015-2026 Carbo Kuo and contributors
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 #include <cstdint>
20 #include <cstring>
21 #include <vector>
22
23 #include "DartsDict.hpp"
24 #include "TestUtilsUTF8.hpp"
25 #include "TextDictTestBase.hpp"
26
27 namespace opencc {
28
29 class DartsDictTest : public TextDictTestBase {
30 protected:
31 DartsDictTest()
32 : dartsDict(DartsDict::NewFromDict(*textDict.get())),
33 fileName("dict.ocd"){};
34
35 // Write a crafted 32-bit-format OCD file with a controllable dartsSize.
36 // A non-zero fakeFirstUnit is appended so probe[4..7] are not all zero,
37 // ensuring the 32-bit detection path is taken even for malformed files.
38 static std::string WriteMalformedDartsFile(uint32_t dartsSize) {
39 const std::string path = "malformed_darts.ocd";
40 FILE* fp = fopen(path.c_str(), "wb");
41 const char* header = "OPENCCDARTS1";
42 fwrite(header, sizeof(char), strlen(header), fp);
43 fwrite(&dartsSize, sizeof(uint32_t), 1, fp);
44 // Minimal non-zero root unit so probe[4..7] != 0 → 32-bit path taken
45 uint32_t fakeFirstUnit = 0x00000400U;
46 fwrite(&fakeFirstUnit, sizeof(uint32_t), 1, fp);
47 fclose(fp);
48 return path;
49 }
50
51 // Serialize dict as a legacy 64-bit OPENCCDARTS1 file by zero-extending
52 // each 32-bit darts unit to 64 bits, writing dartsSize as uint64_t, and
53 // widening every BinaryDict integer field from the fixed 4-byte layout to
54 // 8 bytes. This reproduces files produced by old builds where id_type and
55 // size_t were 8 bytes on 64-bit platforms.
56 static void SerializeAsLegacy64(const DartsDictPtr& dict,
57 const std::string& path) {
58 const std::string tmp = path + ".tmp";
59 dict->opencc::SerializableDict::SerializeToFile(tmp);
60
61 FILE* src = fopen(tmp.c_str(), "rb");
62 fseek(src, 12, SEEK_SET); // skip 12-byte magic
63
64 uint32_t dartsSize32 = 0;
65 fread(&dartsSize32, sizeof(uint32_t), 1, src);
66 size_t numUnits = dartsSize32 / sizeof(uint32_t);
67 std::vector<uint32_t> units32(numUnits);
68 fread(units32.data(), sizeof(uint32_t), numUnits, src);
69
70 FILE* dst = fopen(path.c_str(), "wb");
71 const char* header = "OPENCCDARTS1";
72 fwrite(header, sizeof(char), strlen(header), dst);
73 uint64_t dartsSize64 =
74 static_cast<uint64_t>(numUnits) * sizeof(uint64_t);
75 fwrite(&dartsSize64, sizeof(uint64_t), 1, dst);
76 for (size_t i = 0; i < numUnits; ++i) {
77 uint64_t unit64 = units32[i]; // zero-extend; high bits are 0
78 fwrite(&unit64, sizeof(uint64_t), 1, dst);
79 }
80
81 // Widen the BinaryDict section field by field.
82 const auto widenField = [src, dst]() -> uint64_t {
83 uint32_t field32 = 0;
84 fread(&field32, sizeof(field32), 1, src);
85 uint64_t field64 = field32;
86 fwrite(&field64, sizeof(field64), 1, dst);
87 return field64;
88 };
89 const auto copyBytes = [src, dst](uint64_t count) {
90 std::vector<char> buf(static_cast<size_t>(count));
91 fread(buf.data(), sizeof(char), buf.size(), src);
92 fwrite(buf.data(), sizeof(char), buf.size(), dst);
93 };
94 const uint64_t numItems = widenField();
95 copyBytes(widenField()); // keyTotalLength + key buffer
96 copyBytes(widenField()); // valueTotalLength + value buffer
97 for (uint64_t i = 0; i < numItems; i++) {
98 const uint64_t numValues = widenField();
99 widenField(); // keyOffset
100 for (uint64_t j = 0; j < numValues; j++) {
101 widenField(); // valueOffset
102 }
103 }
104 fclose(src);
105 fclose(dst);
106 std::remove(tmp.c_str());
107 }
108
109 static void CorruptDartsRootUnit(const std::string& path) {
110 FILE* fp = fopen(path.c_str(), "r+b");
111 const char* header = "OPENCCDARTS1";
112 // Seek past magic (12) + uint32_t dartsSize (4) to the first unit
113 fseek(fp, static_cast<long>(strlen(header) + sizeof(uint32_t)), SEEK_SET);
114 uint32_t invalidRoot = 0;
115 fwrite(&invalidRoot, sizeof(uint32_t), 1, fp);
116 fclose(fp);
117 }
118
119 static void CorruptFirstDartsValue(const std::string& path) {
120 FILE* fp = fopen(path.c_str(), "r+b");
121 const char* header = "OPENCCDARTS1";
122 fseek(fp, static_cast<long>(strlen(header)), SEEK_SET);
123 uint32_t dartsSize = 0;
124 fread(&dartsSize, sizeof(uint32_t), 1, fp);
125 const long dartsOffset =
126 static_cast<long>(strlen(header) + sizeof(uint32_t));
127 const size_t numUnits = static_cast<size_t>(dartsSize) / sizeof(uint32_t);
128 for (size_t i = 0; i < numUnits; i++) {
129 uint32_t unit = 0;
130 fseek(fp, dartsOffset + static_cast<long>(i * sizeof(uint32_t)),
131 SEEK_SET);
132 fread(&unit, sizeof(uint32_t), 1, fp);
133 const uint32_t label = unit & ((1U << 31) | 0xFF);
134 if (label > 0xFF) {
135 const uint32_t invalidValue = (1U << 31) | ((1U << 31) - 1);
136 fseek(fp, dartsOffset + static_cast<long>(i * sizeof(uint32_t)),
137 SEEK_SET);
138 fwrite(&invalidValue, sizeof(uint32_t), 1, fp);
139 break;
140 }
141 }
142 fclose(fp);
143 }
144
145 const DartsDictPtr dartsDict;
146 const std::string fileName;
147 };
148
149 TEST_F(DartsDictTest, DictTest) { TestDict(dartsDict); }
150
151 TEST_F(DartsDictTest, Serialization) {
152 dartsDict->opencc::SerializableDict::SerializeToFile(fileName);
153 }
154
155 TEST_F(DartsDictTest, Deserialization) {
156 const DartsDictPtr& deserialized =
157 SerializableDict::NewFromFile<DartsDict>(fileName);
158 TestDict(deserialized);
159
160 const LexiconPtr& lex1 = dartsDict->GetLexicon();
161 const LexiconPtr& lex2 = deserialized->GetLexicon();
162
163 EXPECT_EQ(lex1->Length(), lex2->Length());
164 for (size_t i = 0; i < lex1->Length(); i++) {
165 EXPECT_EQ(lex1->At(i)->Key(), lex2->At(i)->Key());
166 EXPECT_EQ(lex1->At(i)->NumValues(), lex2->At(i)->NumValues());
167 }
168
169 const TextDictPtr deserializedTextDict(new TextDict(lex2));
170 TestDict(deserializedTextDict);
171 }
172
173 TEST_F(DartsDictTest, ExactMatch) {
174 auto there = dartsDict->Match("積羽沉舟", 12);
175 EXPECT_FALSE(there.IsNull());
176 auto dictEntry = there.Get();
177 EXPECT_EQ(1, dictEntry->NumValues());
178 EXPECT_EQ(utf8("羣輕折軸"), dictEntry->GetDefault());
179
180 auto nowhere = dartsDict->Match("積羽沉舟衆口鑠金", 24);
181 EXPECT_TRUE(nowhere.IsNull());
182 }
183
184 // dartsSize exceeding remaining file size must throw (#816).
185 TEST_F(DartsDictTest, RejectsHugeDartsSize) {
186 std::string path = WriteMalformedDartsFile(0x13000000U);
187 EXPECT_THROW(SerializableDict::NewFromFile<DartsDict>(path), InvalidFormat);
188 std::remove(path.c_str());
189 }
190
191 TEST_F(DartsDictTest, RejectsMisalignedDartsSize) {
192 std::string path = WriteMalformedDartsFile(1);
193 FILE* fp = fopen(path.c_str(), "ab");
194 char padding = '\0';
195 fwrite(&padding, sizeof(char), 1, fp);
196 fclose(fp);
197
198 EXPECT_THROW(SerializableDict::NewFromFile<DartsDict>(path), InvalidFormat);
199 std::remove(path.c_str());
200 }
201
202 TEST_F(DartsDictTest, RejectsInvalidDartsRoot) {
203 const std::string path = "invalid_darts_root.ocd";
204 dartsDict->opencc::SerializableDict::SerializeToFile(path);
205 CorruptDartsRootUnit(path);
206
207 EXPECT_THROW(SerializableDict::NewFromFile<DartsDict>(path), InvalidFormat);
208 std::remove(path.c_str());
209 }
210
211 TEST_F(DartsDictTest, RejectsInvalidDartsValue) {
212 const std::string path = "invalid_darts_value.ocd";
213 dartsDict->opencc::SerializableDict::SerializeToFile(path);
214 CorruptFirstDartsValue(path);
215
216 EXPECT_THROW(SerializableDict::NewFromFile<DartsDict>(path), InvalidFormat);
217 std::remove(path.c_str());
218 }
219
220 // Verify that a legacy 64-bit OPENCCDARTS1 file (where id_type was size_t on
221 // a 64-bit host) loads correctly and produces identical lookup results.
222 TEST_F(DartsDictTest, LoadsLegacy64bitFormat) {
223 const std::string path = "legacy64_dict.ocd";
224 SerializeAsLegacy64(dartsDict, path);
225
226 const DartsDictPtr& loaded = SerializableDict::NewFromFile<DartsDict>(path);
227 TestDict(loaded);
228
229 auto there = loaded->Match("積羽沉舟", 12);
230 EXPECT_FALSE(there.IsNull());
231 EXPECT_EQ(utf8("羣輕折軸"), there.Get()->GetDefault());
232
233 std::remove(path.c_str());
234 }
235
236 // A legacy 64-bit file with a zeroed root unit must be rejected (validate).
237 TEST_F(DartsDictTest, RejectsInvalidLegacy64Root) {
238 const std::string path = "invalid_legacy64_root.ocd";
239 SerializeAsLegacy64(dartsDict, path);
240
241 // Overwrite the root unit (magic=12, dartsSize64=8, root at offset 20)
242 FILE* fp = fopen(path.c_str(), "r+b");
243 fseek(fp, 12 + 8, SEEK_SET);
244 uint64_t zeroUnit = 0;
245 fwrite(&zeroUnit, sizeof(uint64_t), 1, fp);
246 fclose(fp);
247
248 EXPECT_THROW(SerializableDict::NewFromFile<DartsDict>(path), InvalidFormat);
249 std::remove(path.c_str());
250 }
251
252 // Regression for 888459fb: when a legacy 64-bit OCD has >64 prefix matches,
253 // MatchPrefix must return the true longest match, not the 64th.
254 TEST_F(DartsDictTest, Legacy64PrefixSearchBeyond64Matches) {
255 // Build a dict with 65 purely-nested entries: "a"×1→"v1", ..., "a"×65→"v65"
256 const size_t kEntries = 65;
257 LexiconPtr lex(new Lexicon);
258 for (size_t i = 1; i <= kEntries; ++i) {
259 lex->Add(DictEntryFactory::New(std::string(i, 'a'), "v" + std::to_string(i)));
260 }
261 lex->Sort();
262 TextDictPtr deepText(new TextDict(lex));
263 DartsDictPtr deepDict = DartsDict::NewFromDict(*deepText);
264
265 const std::string path = "legacy64_deep.ocd";
266 SerializeAsLegacy64(deepDict, path);
267
268 const DartsDictPtr& loaded = SerializableDict::NewFromFile<DartsDict>(path);
269 // All 65 entries are prefix matches; must return the longest ("v65").
270 auto result = loaded->MatchPrefix(std::string(kEntries, 'a').c_str(), kEntries);
271 ASSERT_FALSE(result.IsNull());
272 EXPECT_EQ("v65", result.Get()->GetDefault());
273
274 std::remove(path.c_str());
275 }
276
277 // SerializeToFile on a legacy-loaded dict must throw instead of crashing.
278 TEST_F(DartsDictTest, Legacy64SerializeToFileThrows) {
279 const std::string path = "legacy64_for_serialize.ocd";
280 SerializeAsLegacy64(dartsDict, path);
281
282 const DartsDictPtr& loaded = SerializableDict::NewFromFile<DartsDict>(path);
283 const std::string outPath = "legacy64_out.ocd";
284 EXPECT_THROW(loaded->opencc::SerializableDict::SerializeToFile(outPath),
285 InvalidFormat);
286
287 std::remove(path.c_str());
288 std::remove(outPath.c_str());
289 }
290
291 } // namespace opencc