VirtualBox

source: vbox/trunk/src/VBox/Main/src-all/QMTranslatorImpl.cpp@ 86250

Last change on this file since 86250 was 85212, checked in by vboxsync, 4 years ago

Main/QMTranslatorImpl.cpp: Sign conversion issues with Clang 11. Fixed seek() to stop at m_end. Some doxgyen conversion and likely mojo. bugref:9790

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 13.2 KB
Line 
1/* $Id: QMTranslatorImpl.cpp 85212 2020-07-11 12:27:52Z vboxsync $ */
2/** @file
3 * VirtualBox API translation handling class
4 */
5
6/*
7 * Copyright (C) 2014-2020 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18#include <vector>
19#include <set>
20#include <algorithm>
21#include <iprt/sanitized/iterator>
22#include <iprt/errcore.h>
23#include <iprt/file.h>
24#include <iprt/asm.h>
25#include <VBox/com/string.h>
26#include <VBox/log.h>
27#include <QMTranslator.h>
28
29/* QM File Magic Number */
30static const size_t g_cbMagic = 16;
31static const uint8_t g_abMagic[g_cbMagic] =
32{
33 0x3c, 0xb8, 0x64, 0x18, 0xca, 0xef, 0x9c, 0x95,
34 0xcd, 0x21, 0x1c, 0xbf, 0x60, 0xa1, 0xbd, 0xdd
35};
36
37/* Used internally */
38class QMException : public std::exception
39{
40 const char *m_str;
41public:
42 QMException(const char *str) : m_str(str) {}
43 virtual const char *what() const throw() { return m_str; }
44};
45
46/* Bytes stream. Used by the parser to iterate through the data */
47class QMBytesStream
48{
49 size_t m_cbSize;
50 const uint8_t * const m_dataStart;
51 const uint8_t *m_iter;
52 const uint8_t *m_end;
53
54 /* Function stub for transform method */
55 static uint16_t func_BE2H_U16(uint16_t value)
56 {
57 return RT_BE2H_U16(value);
58 }
59
60public:
61
62 QMBytesStream(const uint8_t *const dataStart, size_t cbSize)
63 : m_cbSize(dataStart ? cbSize : 0)
64 , m_dataStart(dataStart)
65 , m_iter(dataStart)
66 {
67 setEnd();
68 }
69
70 /** Sets end pointer.
71 * Used in message reader to detect the end of message block */
72 inline void setEnd(size_t pos = 0)
73 {
74 m_end = m_dataStart + (pos && pos < m_cbSize ? pos : m_cbSize);
75 }
76
77 inline uint8_t read8()
78 {
79 checkSize(1);
80 return *m_iter++;
81 }
82
83 inline uint32_t read32()
84 {
85 checkSize(4);
86 uint32_t result = *reinterpret_cast<const uint32_t *>(m_iter);
87 m_iter += 4;
88 return RT_BE2H_U32(result);
89 }
90
91 /** Reads string in UTF16 and converts it into a UTF8 string */
92 inline com::Utf8Str readUtf16String()
93 {
94 uint32_t size = read32();
95 checkSize(size);
96 if (size & 1) throw QMException("Incorrect string size");
97 std::vector<uint16_t> wstr;
98 wstr.reserve(size / 2);
99
100 /* We cannot convert to host endianess without copying the data
101 * since the file might be mapped to the memory and any memory
102 * change will lead to the change of the file. */
103 std::transform(reinterpret_cast<const uint16_t *>(m_iter),
104 reinterpret_cast<const uint16_t *>(m_iter + size),
105 std::back_inserter(wstr),
106 func_BE2H_U16);
107 m_iter += size;
108 return com::Utf8Str((CBSTR) &wstr.front(), wstr.size());
109 }
110
111 /** Reads string in one-byte encoding.
112 * The string is assumed to be in ISO-8859-1 encoding */
113 inline com::Utf8Str readString()
114 {
115 uint32_t size = read32();
116 checkSize(size);
117 com::Utf8Str result(reinterpret_cast<const char *>(m_iter), size);
118 m_iter += size;
119 return result;
120 }
121
122 /** Checks the magic number.
123 * Should be called when in the beginning of the data
124 * @throws exception on mismatch */
125 inline void checkMagic()
126 {
127 checkSize(g_cbMagic);
128 if (RT_LIKELY(memcmp(&(*m_iter), g_abMagic, g_cbMagic) == 0))
129 m_iter += g_cbMagic;
130 else
131 throw QMException("Wrong magic number");
132 }
133
134 /** Has we reached the end pointer? */
135 inline bool hasFinished()
136 {
137 return m_iter == m_end;
138 }
139
140 /** Returns current stream position */
141 inline size_t tellPos()
142 {
143 return (size_t)(m_iter - m_dataStart);
144 }
145
146 /** Moves current pointer to a desired position */
147 inline void seek(uint32_t offSkip)
148 {
149 size_t cbLeft = (size_t)(m_end - m_iter);
150 if (cbLeft <= offSkip)
151 m_iter += offSkip;
152 else
153 m_iter = m_end; /** @todo r=bird: Or throw exception via checkSize? */
154 }
155
156 /** Checks whether stream has enough data to read size bytes */
157 inline void checkSize(size_t size)
158 {
159 if (RT_LIKELY((size_t)(m_end - m_iter) >= size))
160 return;
161 throw QMException("Incorrect item size");
162 }
163};
164
165/* Internal QMTranslator implementation */
166class QMTranslator_Impl
167{
168 struct QMMessage
169 {
170 /* Everything is in UTF-8 */
171 com::Utf8Str strContext;
172 com::Utf8Str strTranslation;
173 com::Utf8Str strComment;
174 com::Utf8Str strSource;
175 uint32_t hash;
176 QMMessage() : hash(0) {}
177 };
178
179 struct HashOffset
180 {
181 uint32_t hash;
182 uint32_t offset;
183
184 HashOffset(uint32_t _hash = 0, uint32_t _offs = 0) : hash(_hash), offset(_offs) {}
185
186 bool operator<(const HashOffset &obj) const
187 {
188 return (hash != obj.hash ? hash < obj.hash : offset < obj.offset);
189 }
190
191 };
192
193 typedef std::set<HashOffset> QMHashSet;
194 typedef QMHashSet::const_iterator QMHashSetConstIter;
195 typedef std::vector<QMMessage> QMMessageArray;
196
197 QMHashSet m_hashSet;
198 QMMessageArray m_messageArray;
199
200public:
201
202 QMTranslator_Impl() {}
203
204 const char *translate(const char *pszContext,
205 const char *pszSource,
206 const char *pszDisamb) const
207 {
208 QMHashSetConstIter iter;
209 QMHashSetConstIter lowerIter, upperIter;
210
211 do {
212 uint32_t hash = calculateHash(pszSource, pszDisamb);
213 lowerIter = m_hashSet.lower_bound(HashOffset(hash, 0));
214 upperIter = m_hashSet.upper_bound(HashOffset(hash, UINT32_MAX));
215
216 for (iter = lowerIter; iter != upperIter; ++iter)
217 {
218 const QMMessage &message = m_messageArray[iter->offset];
219 if ((!pszContext || !*pszContext || message.strContext == pszContext) &&
220 message.strSource == pszSource &&
221 ((pszDisamb && !*pszDisamb) || message.strComment == pszDisamb))
222 break;
223 }
224
225 /* Try without disambiguating comment if it isn't empty */
226 if (pszDisamb)
227 {
228 if (!*pszDisamb) pszDisamb = 0;
229 else pszDisamb = "";
230 }
231
232 } while (iter == upperIter && pszDisamb);
233
234 return (iter != upperIter ? m_messageArray[iter->offset].strTranslation.c_str() : "");
235 }
236
237 void load(QMBytesStream &stream)
238 {
239 /* Load into local variables. If we failed during the load,
240 * it would allow us to keep the object in a valid (previous) state. */
241 QMHashSet hashSet;
242 QMMessageArray messageArray;
243
244 stream.checkMagic();
245
246 while (!stream.hasFinished())
247 {
248 uint32_t sectionCode = stream.read8();
249 uint32_t sLen = stream.read32();
250
251 /* Hashes and Context sections are ignored. They contain hash tables
252 * to speed-up search which is not useful since we recalculate all hashes
253 * and don't perform context search by hash */
254 switch (sectionCode)
255 {
256 case Messages:
257 parseMessages(stream, &hashSet, &messageArray, sLen);
258 break;
259 case Hashes:
260 /* Only get size information to speed-up vector filling
261 * if Hashes section goes in the file before Message section */
262 m_messageArray.reserve(sLen >> 3);
263 RT_FALL_THRU();
264 case Context:
265 stream.seek(sLen);
266 break;
267 default:
268 throw QMException("Unkown section");
269 }
270 }
271 /* Store the data into member variables.
272 * The following functions never generate exceptions */
273 m_hashSet.swap(hashSet);
274 m_messageArray.swap(messageArray);
275 }
276
277private:
278
279 /* Some QM stuff */
280 enum SectionType
281 {
282 Hashes = 0x42,
283 Messages = 0x69,
284 Contexts = 0x2f
285 };
286
287 enum MessageType
288 {
289 End = 1,
290 SourceText16 = 2,
291 Translation = 3,
292 Context16 = 4,
293 Hash = 5,
294 SourceText = 6,
295 Context = 7,
296 Comment = 8
297 };
298
299 /* Read messages from the stream. */
300 static void parseMessages(QMBytesStream &stream, QMHashSet * const hashSet, QMMessageArray * const messageArray, size_t cbSize)
301 {
302 stream.setEnd(stream.tellPos() + cbSize);
303 uint32_t cMessage = 0;
304 while (!stream.hasFinished())
305 {
306 QMMessage message;
307 HashOffset hashOffs;
308
309 parseMessageRecord(stream, &message);
310 if (!message.hash)
311 message.hash = calculateHash(message.strSource.c_str(), message.strComment.c_str());
312
313 hashOffs.hash = message.hash;
314 hashOffs.offset = cMessage++;
315
316 hashSet->insert(hashOffs);
317 messageArray->push_back(message);
318 }
319 stream.setEnd();
320 }
321
322 /* Parse one message from the stream */
323 static void parseMessageRecord(QMBytesStream &stream, QMMessage * const message)
324 {
325 while (!stream.hasFinished())
326 {
327 uint8_t type = stream.read8();
328 switch (type)
329 {
330 case End:
331 return;
332 /* Ignored as obsolete */
333 case Context16:
334 case SourceText16:
335 stream.seek(stream.read32());
336 break;
337 case Translation:
338 {
339 com::Utf8Str str = stream.readUtf16String();
340 message->strTranslation.swap(str);
341 break;
342 }
343 case Hash:
344 message->hash = stream.read32();
345 break;
346
347 case SourceText:
348 {
349 com::Utf8Str str = stream.readString();
350 message->strSource.swap(str);
351 break;
352 }
353
354 case Context:
355 {
356 com::Utf8Str str = stream.readString();
357 message->strContext.swap(str);
358 break;
359 }
360
361 case Comment:
362 {
363 com::Utf8Str str = stream.readString();
364 message->strComment.swap(str);
365 break;
366 }
367
368 default:
369 /* Ignore unknown block */
370 LogRel(("QMTranslator::parseMessageRecord(): Unkown message block %x\n", type));
371 break;
372 }
373 }
374 }
375
376 /* Defines the so called `hashpjw' function by P.J. Weinberger
377 [see Aho/Sethi/Ullman, COMPILERS: Principles, Techniques and Tools,
378 1986, 1987 Bell Telephone Laboratories, Inc.] */
379 static uint32_t calculateHash(const char *pszStr1, const char *pszStr2 = 0)
380 {
381 uint32_t hash = 0, g;
382
383 for (const char *pszStr = pszStr1; pszStr != pszStr2; pszStr = pszStr2)
384 for (; pszStr && *pszStr; pszStr++)
385 {
386 hash = (hash << 4) + static_cast<uint8_t>(*pszStr);
387
388 if ((g = hash & 0xf0000000ul) != 0)
389 {
390 hash ^= g >> 24;
391 hash ^= g;
392 }
393 }
394
395 return (hash != 0 ? hash : 1);
396 }
397};
398
399/* Inteface functions implementation */
400QMTranslator::QMTranslator() : _impl(new QMTranslator_Impl) {}
401
402QMTranslator::~QMTranslator() { delete _impl; }
403
404const char *QMTranslator::translate(const char *pszContext, const char *pszSource, const char *pszDisamb) const throw()
405{
406 return _impl->translate(pszContext, pszSource, pszDisamb);
407}
408
409/* The function is noexcept for now but it may be changed
410 * to throw exceptions if required to catch them in another
411 * place. */
412int QMTranslator::load(const char *pszFilename) throw()
413{
414 /* To free safely the file in case of exception */
415 struct FileLoader
416 {
417 uint8_t *data;
418 size_t cbSize;
419 int rc;
420 FileLoader(const char *pszFname)
421 {
422 rc = RTFileReadAll(pszFname, (void**) &data, &cbSize);
423 }
424
425 ~FileLoader()
426 {
427 if (isSuccess())
428 RTFileReadAllFree(data, cbSize);
429 }
430 bool isSuccess() { return RT_SUCCESS(rc); }
431 };
432
433 try
434 {
435 FileLoader loader(pszFilename);
436 if (loader.isSuccess())
437 {
438 QMBytesStream stream(loader.data, loader.cbSize);
439 _impl->load(stream);
440 }
441 return loader.rc;
442 }
443 catch(std::exception &e)
444 {
445 LogRel(("QMTranslator::load() failed to load file '%s', reason: %s\n", pszFilename, e.what()));
446 return VERR_INTERNAL_ERROR;
447 }
448 catch(...)
449 {
450 LogRel(("QMTranslator::load() failed to load file '%s'\n", pszFilename));
451 return VERR_GENERAL_FAILURE;
452 }
453}
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette