-
Notifications
You must be signed in to change notification settings - Fork 49
/
kaitaistream.cpp
1084 lines (929 loc) · 33.1 KB
/
kaitaistream.cpp
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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <kaitai/kaitaistream.h>
#include <kaitai/exceptions.h>
#if defined(__APPLE__)
#include <machine/endian.h>
#include <libkern/OSByteOrder.h>
#define bswap_16(x) OSSwapInt16(x)
#define bswap_32(x) OSSwapInt32(x)
#define bswap_64(x) OSSwapInt64(x)
#define __BYTE_ORDER BYTE_ORDER
#define __BIG_ENDIAN BIG_ENDIAN
#define __LITTLE_ENDIAN LITTLE_ENDIAN
#elif defined(_MSC_VER) // !__APPLE__
#include <stdlib.h>
#define __LITTLE_ENDIAN 1234
#define __BIG_ENDIAN 4321
#define __BYTE_ORDER __LITTLE_ENDIAN
#define bswap_16(x) _byteswap_ushort(x)
#define bswap_32(x) _byteswap_ulong(x)
#define bswap_64(x) _byteswap_uint64(x)
#elif defined(__QNX__) // __QNX__
#include <sys/param.h>
#include <gulliver.h>
#define bswap_16(x) ENDIAN_RET16(x)
#define bswap_32(x) ENDIAN_RET32(x)
#define bswap_64(x) ENDIAN_RET64(x)
#define __BYTE_ORDER BYTE_ORDER
#define __BIG_ENDIAN BIG_ENDIAN
#define __LITTLE_ENDIAN LITTLE_ENDIAN
#else
// At this point it's either Linux or BSD. Both have "sys/param.h", so it's safe to include
#include <sys/param.h> // `BSD` macro // IWYU pragma: keep
#if defined(BSD)
// Supposed to work on FreeBSD: https://man.freebsd.org/cgi/man.cgi?query=bswap16&manpath=FreeBSD+14.0-RELEASE
// Supposed to work on NetBSD: https://man.netbsd.org/NetBSD-10.0/bswap16.3
#include <sys/endian.h>
#include <sys/types.h>
#define bswap_16(x) bswap16(x)
#define bswap_32(x) bswap32(x)
#define bswap_64(x) bswap64(x)
#define __BYTE_ORDER BYTE_ORDER
#define __BIG_ENDIAN BIG_ENDIAN
#define __LITTLE_ENDIAN LITTLE_ENDIAN
#else // !__APPLE__ or !_MSC_VER or !__QNX__ or !BSD
#include <endian.h>
#include <byteswap.h>
#endif
#endif
#include <stdint.h> // int8_t, int16_t, int32_t, int64_t, uint8_t, uint16_t, uint32_t, uint64_t
#include <algorithm> // std::reverse
#include <cerrno> // errno, EINVAL, E2BIG, EILSEQ, ERANGE
#include <cstdlib> // std::size_t, std::strtoll
#include <cstring> // std::memcpy
#include <ios> // std::streamsize
#include <istream> // std::istream // IWYU pragma: keep
#include <limits> // std::numeric_limits
#include <sstream> // std::stringstream, std::ostringstream // IWYU pragma: keep
#include <stdexcept> // std::runtime_error, std::invalid_argument, std::out_of_range
#include <string> // std::string, std::getline
#include <vector> // std::vector
#ifdef KAITAI_STREAM_H_CPP11_SUPPORT
#include <type_traits> // std::enable_if, std::is_trivial
// Taken from https://en.cppreference.com/w/cpp/numeric/bit_cast#Possible_implementation
// (for compatibility with early C++11 compilers like `x86-64 gcc 4.9.4`, `x86-64 clang 3.6` or
// `x86-64 icc 13.0.1`, `std::is_trivially_copyable` was replaced with `std::is_trivial` and the
// `std::is_trivially_default_constructible` assertion was omitted)
template<class To, class From>
typename std::enable_if<
sizeof(To) == sizeof(From) &&
std::is_trivial<From>::value &&
std::is_trivial<To>::value,
To
>::type
// constexpr support needs compiler magic
static bit_cast(const From &src) noexcept
{
// // NOTE: because of `To dst;`, we need the `To` type to be trivially default constructible,
// // which is not true for all trivial types:
// // https://quuxplusone.github.io/blog/2024/04/02/trivial-but-not-default-constructible/
// //
// // However, we don't check this requirement (and just assume it's met), because
// // `std::is_trivially_default_constructible` is not supported by some (very) old compilers
// // with incomplete C++11 support (`x86-64 gcc 4.9.4`, `x86-64 clang 3.6` or
// // `x86-64 icc 13.0.1` at https://godbolt.org/).
// static_assert(std::is_trivially_default_constructible<To>::value,
// "This implementation additionally requires "
// "destination type to be trivially default constructible");
To dst;
std::memcpy(&dst, &src, sizeof(To));
return dst;
}
#else
// The following implementation of `StaticAssert` was inspired by https://stackoverflow.com/a/6765840
// empty default template
template <bool b>
struct StaticAssert;
// template specialized on true
template <>
struct StaticAssert<true> {};
template<class To, class From>
To
static bit_cast(const From &src)
{
StaticAssert<sizeof(To) == sizeof(From)>();
To dst;
std::memcpy(&dst, &src, sizeof(To));
return dst;
}
#endif
kaitai::kstream::kstream(std::istream *io) {
m_io = io;
init();
}
kaitai::kstream::kstream(const std::string &data) : m_io_str(data) {
m_io = &m_io_str;
init();
}
void kaitai::kstream::init() {
exceptions_enable();
align_to_byte();
}
void kaitai::kstream::close() {
// m_io->close();
}
void kaitai::kstream::exceptions_enable() const {
m_io->exceptions(
std::istream::eofbit |
std::istream::failbit |
std::istream::badbit
);
}
// ========================================================================
// Stream positioning
// ========================================================================
bool kaitai::kstream::is_eof() const {
if (m_bits_left > 0) {
return false;
}
char t;
m_io->exceptions(std::istream::badbit);
m_io->get(t);
if (m_io->eof()) {
m_io->clear();
exceptions_enable();
return true;
} else {
m_io->unget();
exceptions_enable();
return false;
}
}
void kaitai::kstream::seek(uint64_t pos) {
m_io->seekg(pos);
}
uint64_t kaitai::kstream::pos() {
return m_io->tellg();
}
uint64_t kaitai::kstream::size() {
std::istream::pos_type cur_pos = m_io->tellg();
m_io->seekg(0, std::istream::end);
std::istream::pos_type len = m_io->tellg();
m_io->seekg(cur_pos);
return len;
}
// ========================================================================
// Integer numbers
// ========================================================================
// ------------------------------------------------------------------------
// Signed
// ------------------------------------------------------------------------
int8_t kaitai::kstream::read_s1() {
char t;
m_io->get(t);
return t;
}
// ........................................................................
// Big-endian
// ........................................................................
int16_t kaitai::kstream::read_s2be() {
int16_t t;
m_io->read(reinterpret_cast<char *>(&t), 2);
#if __BYTE_ORDER == __LITTLE_ENDIAN
t = bswap_16(t);
#endif
return t;
}
int32_t kaitai::kstream::read_s4be() {
int32_t t;
m_io->read(reinterpret_cast<char *>(&t), 4);
#if __BYTE_ORDER == __LITTLE_ENDIAN
t = bswap_32(t);
#endif
return t;
}
int64_t kaitai::kstream::read_s8be() {
int64_t t;
m_io->read(reinterpret_cast<char *>(&t), 8);
#if __BYTE_ORDER == __LITTLE_ENDIAN
t = bswap_64(t);
#endif
return t;
}
// ........................................................................
// Little-endian
// ........................................................................
int16_t kaitai::kstream::read_s2le() {
int16_t t;
m_io->read(reinterpret_cast<char *>(&t), 2);
#if __BYTE_ORDER == __BIG_ENDIAN
t = bswap_16(t);
#endif
return t;
}
int32_t kaitai::kstream::read_s4le() {
int32_t t;
m_io->read(reinterpret_cast<char *>(&t), 4);
#if __BYTE_ORDER == __BIG_ENDIAN
t = bswap_32(t);
#endif
return t;
}
int64_t kaitai::kstream::read_s8le() {
int64_t t;
m_io->read(reinterpret_cast<char *>(&t), 8);
#if __BYTE_ORDER == __BIG_ENDIAN
t = bswap_64(t);
#endif
return t;
}
// ------------------------------------------------------------------------
// Unsigned
// ------------------------------------------------------------------------
uint8_t kaitai::kstream::read_u1() {
char t;
m_io->get(t);
return t;
}
// ........................................................................
// Big-endian
// ........................................................................
uint16_t kaitai::kstream::read_u2be() {
uint16_t t;
m_io->read(reinterpret_cast<char *>(&t), 2);
#if __BYTE_ORDER == __LITTLE_ENDIAN
t = bswap_16(t);
#endif
return t;
}
uint32_t kaitai::kstream::read_u4be() {
uint32_t t;
m_io->read(reinterpret_cast<char *>(&t), 4);
#if __BYTE_ORDER == __LITTLE_ENDIAN
t = bswap_32(t);
#endif
return t;
}
uint64_t kaitai::kstream::read_u8be() {
uint64_t t;
m_io->read(reinterpret_cast<char *>(&t), 8);
#if __BYTE_ORDER == __LITTLE_ENDIAN
t = bswap_64(t);
#endif
return t;
}
// ........................................................................
// Little-endian
// ........................................................................
uint16_t kaitai::kstream::read_u2le() {
uint16_t t;
m_io->read(reinterpret_cast<char *>(&t), 2);
#if __BYTE_ORDER == __BIG_ENDIAN
t = bswap_16(t);
#endif
return t;
}
uint32_t kaitai::kstream::read_u4le() {
uint32_t t;
m_io->read(reinterpret_cast<char *>(&t), 4);
#if __BYTE_ORDER == __BIG_ENDIAN
t = bswap_32(t);
#endif
return t;
}
uint64_t kaitai::kstream::read_u8le() {
uint64_t t;
m_io->read(reinterpret_cast<char *>(&t), 8);
#if __BYTE_ORDER == __BIG_ENDIAN
t = bswap_64(t);
#endif
return t;
}
// ========================================================================
// Floating point numbers
// ========================================================================
// ........................................................................
// Big-endian
// ........................................................................
float kaitai::kstream::read_f4be() {
uint32_t t;
m_io->read(reinterpret_cast<char *>(&t), 4);
#if __BYTE_ORDER == __LITTLE_ENDIAN
t = bswap_32(t);
#endif
return bit_cast<float>(t);
}
double kaitai::kstream::read_f8be() {
uint64_t t;
m_io->read(reinterpret_cast<char *>(&t), 8);
#if __BYTE_ORDER == __LITTLE_ENDIAN
t = bswap_64(t);
#endif
return bit_cast<double>(t);
}
// ........................................................................
// Little-endian
// ........................................................................
float kaitai::kstream::read_f4le() {
uint32_t t;
m_io->read(reinterpret_cast<char *>(&t), 4);
#if __BYTE_ORDER == __BIG_ENDIAN
t = bswap_32(t);
#endif
return bit_cast<float>(t);
}
double kaitai::kstream::read_f8le() {
uint64_t t;
m_io->read(reinterpret_cast<char *>(&t), 8);
#if __BYTE_ORDER == __BIG_ENDIAN
t = bswap_64(t);
#endif
return bit_cast<double>(t);
}
// ========================================================================
// Unaligned bit values
// ========================================================================
void kaitai::kstream::align_to_byte() {
m_bits_left = 0;
m_bits = 0;
}
uint64_t kaitai::kstream::read_bits_int_be(int n) {
uint64_t res = 0;
int bits_needed = n - m_bits_left;
m_bits_left = -bits_needed & 7; // `-bits_needed mod 8`
if (bits_needed > 0) {
// 1 bit => 1 byte
// 8 bits => 1 byte
// 9 bits => 2 bytes
int bytes_needed = ((bits_needed - 1) / 8) + 1; // `ceil(bits_needed / 8)`
if (bytes_needed > 8)
throw std::runtime_error("read_bits_int_be: more than 8 bytes requested");
uint8_t buf[8];
m_io->read(reinterpret_cast<char *>(buf), bytes_needed);
for (int i = 0; i < bytes_needed; i++) {
res = res << 8 | buf[i];
}
uint64_t new_bits = res;
res = res >> m_bits_left | (bits_needed < 64 ? m_bits << bits_needed : 0); // avoid undefined behavior of `x << 64`
m_bits = new_bits; // will be masked at the end of the function
} else {
res = m_bits >> -bits_needed; // shift unneeded bits out
}
uint64_t mask = (static_cast<uint64_t>(1) << m_bits_left) - 1; // `m_bits_left` is in range 0..7, so `(1 << 64)` does not have to be considered
m_bits &= mask;
return res;
}
// Deprecated, use read_bits_int_be() instead.
uint64_t kaitai::kstream::read_bits_int(int n) {
return read_bits_int_be(n);
}
uint64_t kaitai::kstream::read_bits_int_le(int n) {
uint64_t res = 0;
int bits_needed = n - m_bits_left;
if (bits_needed > 0) {
// 1 bit => 1 byte
// 8 bits => 1 byte
// 9 bits => 2 bytes
int bytes_needed = ((bits_needed - 1) / 8) + 1; // `ceil(bits_needed / 8)`
if (bytes_needed > 8)
throw std::runtime_error("read_bits_int_le: more than 8 bytes requested");
uint8_t buf[8];
m_io->read(reinterpret_cast<char *>(buf), bytes_needed);
for (int i = 0; i < bytes_needed; i++) {
res |= static_cast<uint64_t>(buf[i]) << (i * 8);
}
// NB: for bit shift operators in C++, "if the value of the right operand is
// negative or is greater or equal to the number of bits in the promoted left
// operand, the behavior is undefined." (see
// https://en.cppreference.com/w/cpp/language/operator_arithmetic#Bitwise_shift_operators)
// So we define our desired behavior here.
uint64_t new_bits = bits_needed < 64 ? res >> bits_needed : 0;
res = res << m_bits_left | m_bits;
m_bits = new_bits;
} else {
res = m_bits;
m_bits >>= n;
}
m_bits_left = -bits_needed & 7; // `-bits_needed mod 8`
if (n < 64) {
uint64_t mask = (static_cast<uint64_t>(1) << n) - 1;
res &= mask;
}
// if `n == 64`, do nothing
return res;
}
// ========================================================================
// Byte arrays
// ========================================================================
std::string kaitai::kstream::read_bytes(std::streamsize len) {
std::vector<char> result(len);
// NOTE: streamsize type is signed, negative values are only *supposed* to not be used.
// http://en.cppreference.com/w/cpp/io/streamsize
if (len < 0) {
throw std::runtime_error("read_bytes: requested a negative amount");
}
if (len > 0) {
m_io->read(&result[0], len);
}
return std::string(result.begin(), result.end());
}
std::string kaitai::kstream::read_bytes_full() {
std::istream::pos_type p1 = m_io->tellg();
m_io->seekg(0, std::istream::end);
std::istream::pos_type p2 = m_io->tellg();
std::size_t len = p2 - p1;
// Note: this requires a std::string to be backed with a
// contiguous buffer. Officially, it's a only requirement since
// C++11 (C++98 and C++03 didn't have this requirement), but all
// major implementations had contiguous buffers anyway.
std::string result(len, ' ');
m_io->seekg(p1);
m_io->read(&result[0], len);
return result;
}
std::string kaitai::kstream::read_bytes_term(char term, bool include, bool consume, bool eos_error) {
std::string result;
std::getline(*m_io, result, term);
if (m_io->eof()) {
// encountered EOF
if (eos_error) {
throw std::runtime_error("read_bytes_term: encountered EOF");
}
} else {
// encountered terminator
if (include)
result.push_back(term);
if (!consume)
m_io->unget();
}
return result;
}
std::string kaitai::kstream::read_bytes_term_multi(std::string term, bool include, bool consume, bool eos_error) {
std::size_t term_len = term.length();
if (term_len > static_cast<std::size_t>(std::numeric_limits<std::streamsize>::max())) {
throw std::runtime_error("read_bytes_term_multi: terminator too long");
}
std::streamsize unit_size = static_cast<std::streamsize>(term_len);
std::string result;
std::string c(term_len, ' ');
m_io->exceptions(std::istream::badbit);
while (true) {
// Note: this requires std::string to be backed with a
// contiguous buffer. Officially, it's only a requirement since
// C++11 (C++98 and C++03 didn't have this requirement), but all
// major implementations had contiguous buffers anyway.
m_io->read(&c[0], unit_size);
if (m_io->eof()) {
m_io->clear();
exceptions_enable();
if (eos_error) {
throw std::runtime_error("read_bytes_term_multi: encountered EOF");
}
result.append(c, 0, static_cast<std::size_t>(m_io->gcount()));
return result;
}
if (c == term) {
exceptions_enable();
if (include)
result += c;
if (!consume)
m_io->seekg(-unit_size, std::istream::cur);
return result;
}
result += c;
}
}
std::string kaitai::kstream::ensure_fixed_contents(std::string expected) {
std::string actual = read_bytes(expected.length());
if (actual != expected) {
// NOTE: I think printing it outright is not best idea, it could contain non-ASCII characters
// like backspace and beeps and whatnot. It would be better to print hexlified version, and
// also to redirect it to stderr.
throw std::runtime_error("ensure_fixed_contents: actual data does not match expected data");
}
return actual;
}
std::string kaitai::kstream::bytes_strip_right(std::string src, char pad_byte) {
std::size_t new_len = src.length();
while (new_len > 0 && src[new_len - 1] == pad_byte)
new_len--;
return src.substr(0, new_len);
}
std::string kaitai::kstream::bytes_terminate(std::string src, char term, bool include) {
std::size_t new_len = 0;
std::size_t max_len = src.length();
while (new_len < max_len && src[new_len] != term)
new_len++;
if (include && new_len < max_len)
new_len++;
return src.substr(0, new_len);
}
std::string kaitai::kstream::bytes_terminate_multi(std::string src, std::string term, bool include) {
std::size_t unit_size = term.length();
if (unit_size == 0) {
return std::string();
}
std::size_t len = src.length();
std::size_t i_term = 0;
for (std::size_t i_src = 0; i_src < len;) {
if (src[i_src] != term[i_term]) {
i_src += unit_size - i_term;
i_term = 0;
continue;
}
i_src++;
i_term++;
if (i_term == unit_size) {
return src.substr(0, i_src - (include ? 0 : unit_size));
}
}
return src;
}
// ========================================================================
// Byte array processing
// ========================================================================
std::string kaitai::kstream::process_xor_one(std::string data, uint8_t key) {
std::size_t len = data.length();
std::string result(len, ' ');
for (std::size_t i = 0; i < len; i++)
result[i] = data[i] ^ key;
return result;
}
std::string kaitai::kstream::process_xor_many(std::string data, std::string key) {
std::size_t len = data.length();
std::size_t kl = key.length();
std::string result(len, ' ');
std::size_t ki = 0;
for (std::size_t i = 0; i < len; i++) {
result[i] = data[i] ^ key[ki];
ki++;
if (ki >= kl)
ki = 0;
}
return result;
}
std::string kaitai::kstream::process_rotate_left(std::string data, int amount) {
std::size_t len = data.length();
std::string result(len, ' ');
for (std::size_t i = 0; i < len; i++) {
uint8_t bits = data[i];
result[i] = (bits << amount) | (bits >> (8 - amount));
}
return result;
}
#ifdef KS_ZLIB
#include <zlib.h>
// This instructs include-what-you-use not to suggest `#include <zconf.h>` just because it contains
// the definition of `Bytef`. It seems `<zconf.h>` is not a header for public use or at least it's
// not considered necessary to include it on top of `<zlib.h>`, because official usage examples that
// use `Bytef` only include `<zlib.h>`, see
// https://github.com/madler/zlib/blob/0f51fb4933fc9ce18199cb2554dacea8033e7fd3/test/example.c#L71
//
// IWYU pragma: no_include <zconf.h>
std::string kaitai::kstream::process_zlib(std::string data) {
int ret;
unsigned char *src_ptr = reinterpret_cast<unsigned char *>(&data[0]);
std::stringstream dst_strm;
z_stream strm;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
ret = inflateInit(&strm);
if (ret != Z_OK)
throw std::runtime_error("process_zlib: inflateInit error");
strm.next_in = src_ptr;
strm.avail_in = data.length();
unsigned char outbuffer[ZLIB_BUF_SIZE];
std::string outstring;
// get the decompressed bytes blockwise using repeated calls to inflate
do {
strm.next_out = reinterpret_cast<Bytef *>(outbuffer);
strm.avail_out = sizeof(outbuffer);
ret = inflate(&strm, 0);
if (outstring.size() < strm.total_out)
outstring.append(reinterpret_cast<char *>(outbuffer), strm.total_out - outstring.size());
} while (ret == Z_OK);
if (ret != Z_STREAM_END) { // an error occurred that was not EOF
std::ostringstream exc_msg;
exc_msg << "process_zlib: error #" << ret << "): " << strm.msg;
throw std::runtime_error(exc_msg.str());
}
if (inflateEnd(&strm) != Z_OK)
throw std::runtime_error("process_zlib: inflateEnd error");
return outstring;
}
#endif
// ========================================================================
// Misc utility methods
// ========================================================================
int kaitai::kstream::mod(int a, int b) {
if (b <= 0)
throw std::invalid_argument("mod: divisor b <= 0");
int r = a % b;
if (r < 0)
r += b;
return r;
}
void kaitai::kstream::unsigned_to_decimal(uint64_t number, char *buffer) {
// Implementation from https://ideone.com/nrQfA8 by Alf P. Steinbach
// (see https://vitaut.net/posts/2013/integer-to-string-conversion-in-cplusplus/)
if (number == 0) {
*buffer++ = '0';
} else {
char *p_first = buffer;
while (number != 0) {
*buffer++ = static_cast<char>('0' + number % 10);
number /= 10;
}
std::reverse(p_first, buffer);
}
*buffer = '\0';
}
int64_t kaitai::kstream::string_to_int(const std::string& str, int base) {
char *str_end;
errno = 0;
int64_t res = std::strtoll(str.c_str(), &str_end, base);
// Check for successful conversion and throw an exception if the entire string was not converted
if (str_end != str.c_str() + str.size()) {
throw std::invalid_argument("string_to_int");
}
if (errno == ERANGE) {
throw std::out_of_range("string_to_int");
}
return res;
}
std::string kaitai::kstream::reverse(std::string val) {
std::reverse(val.begin(), val.end());
return val;
}
uint8_t kaitai::kstream::byte_array_min(const std::string val) {
uint8_t min = 0xff; // UINT8_MAX
std::string::const_iterator end = val.end();
for (std::string::const_iterator it = val.begin(); it != end; ++it) {
uint8_t cur = static_cast<uint8_t>(*it);
if (cur < min) {
min = cur;
}
}
return min;
}
uint8_t kaitai::kstream::byte_array_max(const std::string val) {
uint8_t max = 0; // UINT8_MIN
std::string::const_iterator end = val.end();
for (std::string::const_iterator it = val.begin(); it != end; ++it) {
uint8_t cur = static_cast<uint8_t>(*it);
if (cur > max) {
max = cur;
}
}
return max;
}
// ========================================================================
// Other internal methods
// ========================================================================
#ifndef KS_STR_DEFAULT_ENCODING
#define KS_STR_DEFAULT_ENCODING "UTF-8"
#endif
#ifdef KS_STR_ENCODING_ICONV
#include <iconv.h>
std::string kaitai::kstream::bytes_to_str(const std::string src, const char *src_enc) {
iconv_t cd = iconv_open(KS_STR_DEFAULT_ENCODING, src_enc);
if (cd == (iconv_t)-1) {
if (errno == EINVAL) {
throw unknown_encoding(src_enc);
} else {
throw bytes_to_str_error("error opening iconv");
}
}
std::size_t src_len = src.length();
std::size_t src_left = src_len;
// Start with a buffer length of double the source length.
std::size_t dst_len = src_len * 2;
std::string dst(dst_len, ' ');
std::size_t dst_left = dst_len;
// NB: this should be const char *, but for some reason iconv() requires non-const in its 2nd argument,
// so we force it with a cast.
char *src_ptr = const_cast<char*>(src.data());
char *dst_ptr = &dst[0];
while (true) {
std::size_t res = iconv(cd, &src_ptr, &src_left, &dst_ptr, &dst_left);
if (res == (std::size_t)-1) {
if (errno == E2BIG) {
// dst buffer is not enough to accomodate whole string
// enlarge the buffer and try again
std::size_t dst_used = dst_len - dst_left;
dst_left += dst_len;
dst_len += dst_len;
dst.resize(dst_len);
// dst.resize might have allocated destination buffer in another area
// of memory, thus our previous pointer "dst" will be invalid; re-point
// it using "dst_used".
dst_ptr = &dst[dst_used];
} else if (errno == EILSEQ) {
throw illegal_seq_in_encoding("EILSEQ");
} else if (errno == EINVAL) {
throw illegal_seq_in_encoding("EINVAL");
} else {
throw bytes_to_str_error(to_string(errno));
}
} else {
// conversion successful
dst.resize(dst_len - dst_left);
break;
}
}
if (iconv_close(cd) != 0) {
throw bytes_to_str_error("iconv close error");
}
return dst;
}
#elif defined(KS_STR_ENCODING_NONE)
std::string kaitai::kstream::bytes_to_str(const std::string src, const char *src_enc) {
return src;
}
#elif defined(KS_STR_ENCODING_WIN32API)
#include <windows.h>
// Unbreak std::numeric_limits<T>::max, as otherwise MSVC substitutes "useful" max() macro.
#undef max
int kaitai::kstream::encoding_to_win_codepage(const char *src_enc) {
std::string enc(src_enc);
// See https://learn.microsoft.com/en-us/windows/win32/intl/code-page-identifiers
//
// This method should handle at least all canonical encoding names listed in
// <https://github.com/kaitai-io/kaitai_struct_compiler/blob/5832a81a48e10c3c207748486e09bd58b9aa4000/shared/src/main/scala/io/kaitai/struct/EncodingList.scala>,
// preferably in the same order so that both sets of encodings can be easily compared.
if (enc == "ASCII")
return 20127;
if (enc == "UTF-8")
return CP_UTF8;
if (enc == "UTF-16BE")
return KAITAI_CP_UTF16BE;
if (enc == "UTF-16LE")
return KAITAI_CP_UTF16LE;
if (enc == "UTF-32BE") {
// It has a code page number 12001 assigned to it, but it's "available only to
// managed applications", so we can't use it.
return KAITAI_CP_UNSUPPORTED;
}
if (enc == "UTF-32LE") {
// It has a code page number 12000 assigned to it, but it's "available only to
// managed applications", so we can't use it.
return KAITAI_CP_UNSUPPORTED;
}
if (enc == "ISO-8859-1")
return 28591;
if (enc == "ISO-8859-2")
return 28592;
if (enc == "ISO-8859-3")
return 28593;
if (enc == "ISO-8859-4")
return 28594;
if (enc == "ISO-8859-5")
return 28595;
if (enc == "ISO-8859-6")
return 28596;
if (enc == "ISO-8859-7")
return 28597;
if (enc == "ISO-8859-8")
return 28598;
if (enc == "ISO-8859-9")
return 28599;
if (enc == "ISO-8859-10") {
// According to <https://docs.rs/encoding_rs/latest/encoding_rs/static.ISO_8859_10.html>:
// > The Windows code page number for this encoding is 28600, but kernel32.dll
// > does not support this encoding.
return KAITAI_CP_UNSUPPORTED;
}
if (enc == "ISO-8859-11") {
// The Windows code page 874 (`windows-874`) is the best match we can use here,
// although it's actually an extension of ISO-8859-11, see
// https://en.wikipedia.org/wiki/ISO/IEC_8859-11#Code_page_874_(Microsoft)_/_1162
return 874;
}
if (enc == "ISO-8859-13")
return 28603;
if (enc == "ISO-8859-14") {
// According to <https://docs.rs/encoding_rs/latest/encoding_rs/static.ISO_8859_14.html>:
// > The Windows code page number for this encoding is 28604, but kernel32.dll
// > does not support this encoding.
return KAITAI_CP_UNSUPPORTED;
}
if (enc == "ISO-8859-15")
return 28605;
if (enc == "ISO-8859-16") {
// According to <https://docs.rs/encoding_rs/latest/encoding_rs/static.ISO_8859_16.html>:
// > The Windows code page number for this encoding is 28606, but kernel32.dll
// > does not support this encoding.
return KAITAI_CP_UNSUPPORTED;
}
if (enc == "windows-1250")
return 1250;
if (enc == "windows-1251")
return 1251;
if (enc == "windows-1252")
return 1252;
if (enc == "windows-1253")
return 1253;
if (enc == "windows-1254")
return 1254;
if (enc == "windows-1255")
return 1255;
if (enc == "windows-1256")
return 1256;
if (enc == "windows-1257")
return 1257;
if (enc == "windows-1258")
return 1258;
if (enc == "IBM437")
return 437;
if (enc == "IBM850")
return 850;
if (enc == "IBM866")
return 866;
if (enc == "Shift_JIS")
return 932;
if (enc == "GB2312")
return 936;
if (enc == "Big5")
return 950;
if (enc == "EUC-JP")
return 20932;
if (enc == "EUC-KR")
return 51949;
return KAITAI_CP_UNSUPPORTED;
}
std::string kaitai::kstream::bytes_to_str(const std::string src, const char *src_enc) {
// Step 1: convert encoding name to codepage number
int codepage = encoding_to_win_codepage(src_enc);
if (codepage == KAITAI_CP_UNSUPPORTED) {
throw unknown_encoding(src_enc);
}
return bytes_to_str(src, codepage);
}
std::string kaitai::kstream::bytes_to_str(const std::string src, int codepage) {
// Shortcut: if we're already in UTF-8, no need to convert anything
if (codepage == CP_UTF8) {
return src;
}
// If `src` is empty, no conversion is needed either (in fact, the Win32 functions we use, i.e.
// MultiByteToWideChar and WideCharToMultiByte, fail with ERROR_INVALID_PARAMETER when they