summaryrefslogtreecommitdiff
path: root/python/examples/kaitai/gettext_mo.py
blob: c5de94b870d2787c31a728e2778966e671b48518 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
# This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild

from pkg_resources import parse_version
from .kaitaistruct import __version__ as ks_version, KaitaiStruct, KaitaiStream, BytesIO
import collections


if parse_version(ks_version) < parse_version('0.7'):
    raise Exception("Incompatible Kaitai Struct Python API: 0.7 or later is required, but you have %s" % (ks_version))

class GettextMo(KaitaiStruct):
    """[GNU gettext](https://www.gnu.org/software/gettext/) is a popular
    solution in free/open source software world to do i18n/l10n of
    software, by providing translated strings that will substitute
    strings in original language (typically, English).
    
    gettext .mo is a binary database format which stores these string
    translation pairs in an efficient binary format, ready to be used by
    gettext-enabled software. .mo format is a result of compilation of
    text-based .po files using
    [msgfmt](https://www.gnu.org/software/gettext/manual/html_node/msgfmt-Invocation.html#msgfmt-Invocation)
    utility. The reverse conversion (.mo -> .po) is also possible using
    [msgunfmt](https://www.gnu.org/software/gettext/manual/html_node/msgunfmt-Invocation.html#msgunfmt-Invocation)
    decompiler utility.
    
    .. seealso::
       Source - https://gitlab.com/worr/libintl
    """
    SEQ_FIELDS = ["signature", "mo"]
    def __init__(self, _io, _parent=None, _root=None):
        self._io = _io
        self._parent = _parent
        self._root = _root if _root else self
        self._debug = collections.defaultdict(dict)

    def _read(self):
        self._debug['signature']['start'] = self._io.pos()
        self.signature = self._io.read_bytes(4)
        self._debug['signature']['end'] = self._io.pos()
        self._debug['mo']['start'] = self._io.pos()
        self.mo = self._root.Mo(self._io, self, self._root)
        self.mo._read()
        self._debug['mo']['end'] = self._io.pos()

    class HashLookupIteration(KaitaiStruct):
        SEQ_FIELDS = []
        def __init__(self, idx, collision_step, _io, _parent=None, _root=None):
            self._io = _io
            self._parent = _parent
            self._root = _root if _root else self
            self.idx = idx
            self.collision_step = collision_step
            self._debug = collections.defaultdict(dict)

        def _read(self):
            pass

        @property
        def original(self):
            if hasattr(self, '_m_original'):
                return self._m_original if hasattr(self, '_m_original') else None

            self._m_original = self._root.mo.originals[self.idx].str
            return self._m_original if hasattr(self, '_m_original') else None

        @property
        def translation(self):
            if hasattr(self, '_m_translation'):
                return self._m_translation if hasattr(self, '_m_translation') else None

            self._m_translation = self._root.mo.translations[self.idx].str
            return self._m_translation if hasattr(self, '_m_translation') else None

        @property
        def next_idx(self):
            if hasattr(self, '_m_next_idx'):
                return self._m_next_idx if hasattr(self, '_m_next_idx') else None

            self._m_next_idx = ((self.idx + self.collision_step) - (self._root.mo.num_hashtable_items if self.idx >= (self._root.mo.num_hashtable_items - self.collision_step) else 0))
            return self._m_next_idx if hasattr(self, '_m_next_idx') else None

        @property
        def next(self):
            if hasattr(self, '_m_next'):
                return self._m_next if hasattr(self, '_m_next') else None

            _pos = self._io.pos()
            self._io.seek(0)
            self._debug['_m_next']['start'] = self._io.pos()
            self._m_next = self._root.HashLookupIteration(self._root.mo.hashtable_items[self.next_idx].val, self.collision_step, self._io, self, self._root)
            self._m_next._read()
            self._debug['_m_next']['end'] = self._io.pos()
            self._io.seek(_pos)
            return self._m_next if hasattr(self, '_m_next') else None


    class LookupIteration(KaitaiStruct):
        SEQ_FIELDS = []
        def __init__(self, current, query, _io, _parent=None, _root=None):
            self._io = _io
            self._parent = _parent
            self._root = _root if _root else self
            self.current = current
            self.query = query
            self._debug = collections.defaultdict(dict)

        def _read(self):
            pass

        @property
        def found(self):
            if hasattr(self, '_m_found'):
                return self._m_found if hasattr(self, '_m_found') else None

            self._m_found = self.query == self.current.original
            return self._m_found if hasattr(self, '_m_found') else None

        @property
        def next(self):
            if hasattr(self, '_m_next'):
                return self._m_next if hasattr(self, '_m_next') else None

            if not (self.found):
                _pos = self._io.pos()
                self._io.seek(0)
                self._debug['_m_next']['start'] = self._io.pos()
                self._m_next = self._root.LookupIteration(self.current.next, self.query, self._io, self, self._root)
                self._m_next._read()
                self._debug['_m_next']['end'] = self._io.pos()
                self._io.seek(_pos)

            return self._m_next if hasattr(self, '_m_next') else None


    class HashtableLookup(KaitaiStruct):
        """def lookup(s:str, t:gettext_mo.GettextMo):
          try:
            l=gettext_mo.GettextMo.HashtableLookup(s, string_hash(s), t._io, _parent=t, _root=t)
            e=l.entry
            while(not e.found):
              e=e.next
            return e.current
          except:
            raise Exception("Not found "+s+" in the hashtable!")
        
        lookup(t.mo.originals[145].str, t)
        
        .. seealso::
           Source - https://gitlab.com/worr/libintl/raw/master/src/lib/libintl/gettext.c
        """
        SEQ_FIELDS = []
        def __init__(self, query, hash, _io, _parent=None, _root=None):
            self._io = _io
            self._parent = _parent
            self._root = _root if _root else self
            self.query = query
            self.hash = hash
            self._debug = collections.defaultdict(dict)

        def _read(self):
            pass

        @property
        def collision_step(self):
            if hasattr(self, '_m_collision_step'):
                return self._m_collision_step if hasattr(self, '_m_collision_step') else None

            self._m_collision_step = ((self.hash % (self._root.mo.num_hashtable_items - 2)) + 1)
            return self._m_collision_step if hasattr(self, '_m_collision_step') else None

        @property
        def idx(self):
            if hasattr(self, '_m_idx'):
                return self._m_idx if hasattr(self, '_m_idx') else None

            self._m_idx = (self.hash % self._root.mo.num_hashtable_items)
            return self._m_idx if hasattr(self, '_m_idx') else None

        @property
        def hash_lookup_iteration(self):
            if hasattr(self, '_m_hash_lookup_iteration'):
                return self._m_hash_lookup_iteration if hasattr(self, '_m_hash_lookup_iteration') else None

            _pos = self._io.pos()
            self._io.seek(0)
            self._debug['_m_hash_lookup_iteration']['start'] = self._io.pos()
            self._m_hash_lookup_iteration = self._root.HashLookupIteration(self._root.mo.hashtable_items[self.idx].val, self.collision_step, self._io, self, self._root)
            self._m_hash_lookup_iteration._read()
            self._debug['_m_hash_lookup_iteration']['end'] = self._io.pos()
            self._io.seek(_pos)
            return self._m_hash_lookup_iteration if hasattr(self, '_m_hash_lookup_iteration') else None

        @property
        def entry(self):
            if hasattr(self, '_m_entry'):
                return self._m_entry if hasattr(self, '_m_entry') else None

            _pos = self._io.pos()
            self._io.seek(0)
            self._debug['_m_entry']['start'] = self._io.pos()
            self._m_entry = self._root.LookupIteration(self.hash_lookup_iteration, self.query, self._io, self, self._root)
            self._m_entry._read()
            self._debug['_m_entry']['end'] = self._io.pos()
            self._io.seek(_pos)
            return self._m_entry if hasattr(self, '_m_entry') else None


    class Mo(KaitaiStruct):
        SEQ_FIELDS = ["version", "num_translations", "ofs_originals", "ofs_translations", "num_hashtable_items", "ofs_hashtable_items"]
        def __init__(self, _io, _parent=None, _root=None):
            self._io = _io
            self._parent = _parent
            self._root = _root if _root else self
            self._debug = collections.defaultdict(dict)

        def _read(self):
            _on = self._root.signature
            if _on == b"\xDE\x12\x04\x95":
                self._is_le = True
            elif _on == b"\x95\x04\x12\xDE":
                self._is_le = False

            if self._is_le == True:
                self._read_le()
            elif self._is_le == False:
                self._read_be()
            else:
                raise Exception("Unable to decide endianness")

        def _read_le(self):
            self._debug['version']['start'] = self._io.pos()
            self.version = self._root.Mo.Version(self._io, self, self._root, self._is_le)
            self.version._read()
            self._debug['version']['end'] = self._io.pos()
            self._debug['num_translations']['start'] = self._io.pos()
            self.num_translations = self._io.read_u4le()
            self._debug['num_translations']['end'] = self._io.pos()
            self._debug['ofs_originals']['start'] = self._io.pos()
            self.ofs_originals = self._io.read_u4le()
            self._debug['ofs_originals']['end'] = self._io.pos()
            self._debug['ofs_translations']['start'] = self._io.pos()
            self.ofs_translations = self._io.read_u4le()
            self._debug['ofs_translations']['end'] = self._io.pos()
            self._debug['num_hashtable_items']['start'] = self._io.pos()
            self.num_hashtable_items = self._io.read_u4le()
            self._debug['num_hashtable_items']['end'] = self._io.pos()
            self._debug['ofs_hashtable_items']['start'] = self._io.pos()
            self.ofs_hashtable_items = self._io.read_u4le()
            self._debug['ofs_hashtable_items']['end'] = self._io.pos()

        def _read_be(self):
            self._debug['version']['start'] = self._io.pos()
            self.version = self._root.Mo.Version(self._io, self, self._root, self._is_le)
            self.version._read()
            self._debug['version']['end'] = self._io.pos()
            self._debug['num_translations']['start'] = self._io.pos()
            self.num_translations = self._io.read_u4be()
            self._debug['num_translations']['end'] = self._io.pos()
            self._debug['ofs_originals']['start'] = self._io.pos()
            self.ofs_originals = self._io.read_u4be()
            self._debug['ofs_originals']['end'] = self._io.pos()
            self._debug['ofs_translations']['start'] = self._io.pos()
            self.ofs_translations = self._io.read_u4be()
            self._debug['ofs_translations']['end'] = self._io.pos()
            self._debug['num_hashtable_items']['start'] = self._io.pos()
            self.num_hashtable_items = self._io.read_u4be()
            self._debug['num_hashtable_items']['end'] = self._io.pos()
            self._debug['ofs_hashtable_items']['start'] = self._io.pos()
            self.ofs_hashtable_items = self._io.read_u4be()
            self._debug['ofs_hashtable_items']['end'] = self._io.pos()

        class Version(KaitaiStruct):
            SEQ_FIELDS = ["version_raw"]
            def __init__(self, _io, _parent=None, _root=None, _is_le=None):
                self._io = _io
                self._parent = _parent
                self._root = _root if _root else self
                self._is_le = _is_le
                self._debug = collections.defaultdict(dict)

            def _read(self):

                if self._is_le == True:
                    self._read_le()
                elif self._is_le == False:
                    self._read_be()
                else:
                    raise Exception("Unable to decide endianness")

            def _read_le(self):
                self._debug['version_raw']['start'] = self._io.pos()
                self.version_raw = self._io.read_u4le()
                self._debug['version_raw']['end'] = self._io.pos()

            def _read_be(self):
                self._debug['version_raw']['start'] = self._io.pos()
                self.version_raw = self._io.read_u4be()
                self._debug['version_raw']['end'] = self._io.pos()

            @property
            def major(self):
                if hasattr(self, '_m_major'):
                    return self._m_major if hasattr(self, '_m_major') else None

                self._m_major = (self.version_raw >> 16)
                return self._m_major if hasattr(self, '_m_major') else None

            @property
            def minor(self):
                if hasattr(self, '_m_minor'):
                    return self._m_minor if hasattr(self, '_m_minor') else None

                self._m_minor = (self.version_raw & 65535)
                return self._m_minor if hasattr(self, '_m_minor') else None


        class HashtableItem(KaitaiStruct):
            SEQ_FIELDS = ["raw_val"]
            def __init__(self, _io, _parent=None, _root=None, _is_le=None):
                self._io = _io
                self._parent = _parent
                self._root = _root if _root else self
                self._is_le = _is_le
                self._debug = collections.defaultdict(dict)

            def _read(self):

                if self._is_le == True:
                    self._read_le()
                elif self._is_le == False:
                    self._read_be()
                else:
                    raise Exception("Unable to decide endianness")

            def _read_le(self):
                self._debug['raw_val']['start'] = self._io.pos()
                self.raw_val = self._io.read_u4le()
                self._debug['raw_val']['end'] = self._io.pos()

            def _read_be(self):
                self._debug['raw_val']['start'] = self._io.pos()
                self.raw_val = self._io.read_u4be()
                self._debug['raw_val']['end'] = self._io.pos()

            @property
            def mask(self):
                if hasattr(self, '_m_mask'):
                    return self._m_mask if hasattr(self, '_m_mask') else None

                self._m_mask = 2147483648
                return self._m_mask if hasattr(self, '_m_mask') else None

            @property
            def val_1(self):
                if hasattr(self, '_m_val_1'):
                    return self._m_val_1 if hasattr(self, '_m_val_1') else None

                if self.raw_val != 0:
                    self._m_val_1 = (self.raw_val - 1)

                return self._m_val_1 if hasattr(self, '_m_val_1') else None

            @property
            def is_system_dependent(self):
                if hasattr(self, '_m_is_system_dependent'):
                    return self._m_is_system_dependent if hasattr(self, '_m_is_system_dependent') else None

                if self.raw_val != 0:
                    self._m_is_system_dependent = (self.val_1 & self.mask) == 1

                return self._m_is_system_dependent if hasattr(self, '_m_is_system_dependent') else None

            @property
            def val(self):
                if hasattr(self, '_m_val'):
                    return self._m_val if hasattr(self, '_m_val') else None

                if self.raw_val != 0:
                    self._m_val = (self.val_1 & ~(self.mask))

                return self._m_val if hasattr(self, '_m_val') else None


        class Descriptor(KaitaiStruct):
            SEQ_FIELDS = ["len_str", "ofs_str"]
            def __init__(self, _io, _parent=None, _root=None, _is_le=None):
                self._io = _io
                self._parent = _parent
                self._root = _root if _root else self
                self._is_le = _is_le
                self._debug = collections.defaultdict(dict)

            def _read(self):

                if self._is_le == True:
                    self._read_le()
                elif self._is_le == False:
                    self._read_be()
                else:
                    raise Exception("Unable to decide endianness")

            def _read_le(self):
                self._debug['len_str']['start'] = self._io.pos()
                self.len_str = self._io.read_u4le()
                self._debug['len_str']['end'] = self._io.pos()
                self._debug['ofs_str']['start'] = self._io.pos()
                self.ofs_str = self._io.read_u4le()
                self._debug['ofs_str']['end'] = self._io.pos()

            def _read_be(self):
                self._debug['len_str']['start'] = self._io.pos()
                self.len_str = self._io.read_u4be()
                self._debug['len_str']['end'] = self._io.pos()
                self._debug['ofs_str']['start'] = self._io.pos()
                self.ofs_str = self._io.read_u4be()
                self._debug['ofs_str']['end'] = self._io.pos()

            @property
            def str(self):
                if hasattr(self, '_m_str'):
                    return self._m_str if hasattr(self, '_m_str') else None

                io = self._root._io
                _pos = io.pos()
                io.seek(self.ofs_str)
                self._debug['_m_str']['start'] = io.pos()
                if self._is_le:
                    self._m_str = (KaitaiStream.bytes_terminate(io.read_bytes(self.len_str), 0, False)).decode(u"UTF-8")
                else:
                    self._m_str = (KaitaiStream.bytes_terminate(io.read_bytes(self.len_str), 0, False)).decode(u"UTF-8")
                self._debug['_m_str']['end'] = io.pos()
                io.seek(_pos)
                return self._m_str if hasattr(self, '_m_str') else None


        @property
        def originals(self):
            if hasattr(self, '_m_originals'):
                return self._m_originals if hasattr(self, '_m_originals') else None

            io = self._root._io
            _pos = io.pos()
            io.seek(self.ofs_originals)
            self._debug['_m_originals']['start'] = io.pos()
            if self._is_le:
                self._m_originals = [None] * (self.num_translations)
                for i in range(self.num_translations):
                    if not 'arr' in self._debug['_m_originals']:
                        self._debug['_m_originals']['arr'] = []
                    self._debug['_m_originals']['arr'].append({'start': io.pos()})
                    _t__m_originals = self._root.Mo.Descriptor(io, self, self._root, self._is_le)
                    _t__m_originals._read()
                    self._m_originals[i] = _t__m_originals
                    self._debug['_m_originals']['arr'][i]['end'] = io.pos()

            else:
                self._m_originals = [None] * (self.num_translations)
                for i in range(self.num_translations):
                    if not 'arr' in self._debug['_m_originals']:
                        self._debug['_m_originals']['arr'] = []
                    self._debug['_m_originals']['arr'].append({'start': io.pos()})
                    _t__m_originals = self._root.Mo.Descriptor(io, self, self._root, self._is_le)
                    _t__m_originals._read()
                    self._m_originals[i] = _t__m_originals
                    self._debug['_m_originals']['arr'][i]['end'] = io.pos()

            self._debug['_m_originals']['end'] = io.pos()
            io.seek(_pos)
            return self._m_originals if hasattr(self, '_m_originals') else None

        @property
        def translations(self):
            if hasattr(self, '_m_translations'):
                return self._m_translations if hasattr(self, '_m_translations') else None

            io = self._root._io
            _pos = io.pos()
            io.seek(self.ofs_translations)
            self._debug['_m_translations']['start'] = io.pos()
            if self._is_le:
                self._m_translations = [None] * (self.num_translations)
                for i in range(self.num_translations):
                    if not 'arr' in self._debug['_m_translations']:
                        self._debug['_m_translations']['arr'] = []
                    self._debug['_m_translations']['arr'].append({'start': io.pos()})
                    _t__m_translations = self._root.Mo.Descriptor(io, self, self._root, self._is_le)
                    _t__m_translations._read()
                    self._m_translations[i] = _t__m_translations
                    self._debug['_m_translations']['arr'][i]['end'] = io.pos()

            else:
                self._m_translations = [None] * (self.num_translations)
                for i in range(self.num_translations):
                    if not 'arr' in self._debug['_m_translations']:
                        self._debug['_m_translations']['arr'] = []
                    self._debug['_m_translations']['arr'].append({'start': io.pos()})
                    _t__m_translations = self._root.Mo.Descriptor(io, self, self._root, self._is_le)
                    _t__m_translations._read()
                    self._m_translations[i] = _t__m_translations
                    self._debug['_m_translations']['arr'][i]['end'] = io.pos()

            self._debug['_m_translations']['end'] = io.pos()
            io.seek(_pos)
            return self._m_translations if hasattr(self, '_m_translations') else None

        @property
        def hashtable_items(self):
            if hasattr(self, '_m_hashtable_items'):
                return self._m_hashtable_items if hasattr(self, '_m_hashtable_items') else None

            if self.ofs_hashtable_items != 0:
                io = self._root._io
                _pos = io.pos()
                io.seek(self.ofs_hashtable_items)
                self._debug['_m_hashtable_items']['start'] = io.pos()
                if self._is_le:
                    self._m_hashtable_items = [None] * (self.num_hashtable_items)
                    for i in range(self.num_hashtable_items):
                        if not 'arr' in self._debug['_m_hashtable_items']:
                            self._debug['_m_hashtable_items']['arr'] = []
                        self._debug['_m_hashtable_items']['arr'].append({'start': io.pos()})
                        _t__m_hashtable_items = self._root.Mo.HashtableItem(io, self, self._root, self._is_le)
                        _t__m_hashtable_items._read()
                        self._m_hashtable_items[i] = _t__m_hashtable_items
                        self._debug['_m_hashtable_items']['arr'][i]['end'] = io.pos()

                else:
                    self._m_hashtable_items = [None] * (self.num_hashtable_items)
                    for i in range(self.num_hashtable_items):
                        if not 'arr' in self._debug['_m_hashtable_items']:
                            self._debug['_m_hashtable_items']['arr'] = []
                        self._debug['_m_hashtable_items']['arr'].append({'start': io.pos()})
                        _t__m_hashtable_items = self._root.Mo.HashtableItem(io, self, self._root, self._is_le)
                        _t__m_hashtable_items._read()
                        self._m_hashtable_items[i] = _t__m_hashtable_items
                        self._debug['_m_hashtable_items']['arr'][i]['end'] = io.pos()

                self._debug['_m_hashtable_items']['end'] = io.pos()
                io.seek(_pos)

            return self._m_hashtable_items if hasattr(self, '_m_hashtable_items') else None