-
Notifications
You must be signed in to change notification settings - Fork 561
/
Copy pathpp_pack.c
3171 lines (2970 loc) · 107 KB
/
pp_pack.c
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
/* pp_pack.c
*
* Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
* 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 by Larry Wall and others
*
* You may distribute under the terms of either the GNU General Public
* License or the Artistic License, as specified in the README file.
*
*/
/*
* He still hopefully carried some of his gear in his pack: a small tinder-box,
* two small shallow pans, the smaller fitting into the larger; inside them a
* wooden spoon, a short two-pronged fork and some skewers were stowed; and
* hidden at the bottom of the pack in a flat wooden box a dwindling treasure,
* some salt.
*
* [p.653 of _The Lord of the Rings_, IV/iv: "Of Herbs and Stewed Rabbit"]
*/
/* This file contains pp ("push/pop") functions that
* execute the opcodes that make up a perl program. A typical pp function
* expects to find its arguments on the stack, and usually pushes its
* results onto the stack, hence the 'pp' terminology. Each OP structure
* contains a pointer to the relevant pp_foo() function.
*
* This particular file just contains pp_pack() and pp_unpack(). See the
* other pp*.c files for the rest of the pp_ functions.
*/
#include "EXTERN.h"
#define PERL_IN_PP_PACK_C
#include "perl.h"
/* Types used by pack/unpack */
typedef enum {
e_no_len, /* no length */
e_number, /* number, [] */
e_star /* asterisk */
} howlen_t;
typedef struct tempsym {
const char* patptr; /* current template char */
const char* patend; /* one after last char */
const char* grpbeg; /* 1st char of ()-group */
const char* grpend; /* end of ()-group */
I32 code; /* template code (!<>) */
U32 flags; /* /=4, comma=2, pack=1 */
/* and group modifiers */
SSize_t length; /* length/repeat count */
howlen_t howlen; /* how length is given */
int level; /* () nesting level */
STRLEN strbeg; /* offset of group start */
struct tempsym *previous; /* previous group */
} tempsym_t;
#define TEMPSYM_INIT(symptr, p, e, f) \
STMT_START { \
(symptr)->patptr = (p); \
(symptr)->patend = (e); \
(symptr)->grpbeg = NULL; \
(symptr)->grpend = NULL; \
(symptr)->grpend = NULL; \
(symptr)->code = 0; \
(symptr)->length = 0; \
(symptr)->howlen = e_no_len; \
(symptr)->level = 0; \
(symptr)->flags = (f); \
(symptr)->strbeg = 0; \
(symptr)->previous = NULL; \
} STMT_END
typedef union {
NV nv;
U8 bytes[sizeof(NV)];
} NV_bytes;
#if defined(HAS_LONG_DOUBLE)
typedef union {
long double ld;
U8 bytes[sizeof(long double)];
} ld_bytes;
#endif
#ifndef CHAR_BIT
# define CHAR_BIT 8
#endif
/* Maximum number of bytes to which a byte can grow due to upgrade */
#define UTF8_EXPAND 2
/*
* Offset for integer pack/unpack.
*
* On architectures where I16 and I32 aren't really 16 and 32 bits,
* which for now are all Crays, pack and unpack have to play games.
*/
/*
* These values are required for portability of pack() output.
* If they're not right on your machine, then pack() and unpack()
* wouldn't work right anyway; you'll need to apply the Cray hack.
* (I'd like to check them with #if, but you can't use sizeof() in
* the preprocessor.) --???
*/
/*
The appropriate SHORTSIZE, INTSIZE, LONGSIZE, and LONGLONGSIZE
defines are now in config.h. --Andy Dougherty April 1998
*/
#define SIZE16 2
#define SIZE32 4
/* CROSSCOMPILE and MULTIARCH are going to affect pp_pack() and pp_unpack().
--jhi Feb 1999 */
#if U16SIZE <= SIZE16 && U32SIZE <= SIZE32
# define OFF16(p) ((char *) (p))
# define OFF32(p) ((char *) (p))
#elif BYTEORDER == 0x1234 || BYTEORDER == 0x12345678 /* little-endian */
# define OFF16(p) ((char*)(p))
# define OFF32(p) ((char*)(p))
#elif BYTEORDER == 0x4321 || BYTEORDER == 0x87654321 /* big-endian */
# define OFF16(p) ((char*)(p) + (sizeof(U16) - SIZE16))
# define OFF32(p) ((char*)(p) + (sizeof(U32) - SIZE32))
#else
# error "bad cray byte order"
#endif
#define PUSH16(utf8, cur, p, needs_swap) \
PUSH_BYTES(utf8, cur, OFF16(p), SIZE16, needs_swap)
#define PUSH32(utf8, cur, p, needs_swap) \
PUSH_BYTES(utf8, cur, OFF32(p), SIZE32, needs_swap)
#if BYTEORDER == 0x4321 || BYTEORDER == 0x87654321 /* big-endian */
# define NEEDS_SWAP(d) (TYPE_ENDIANNESS(d) == TYPE_IS_LITTLE_ENDIAN)
#elif BYTEORDER == 0x1234 || BYTEORDER == 0x12345678 /* little-endian */
# define NEEDS_SWAP(d) (TYPE_ENDIANNESS(d) == TYPE_IS_BIG_ENDIAN)
#else
# error "Unsupported byteorder"
/* Need to add code here to re-instate mixed endian support.
NEEDS_SWAP would need to hold a flag indicating which action to
take, and S_reverse_copy and the code in S_utf8_to_bytes would need
logic adding to deal with any mixed-endian transformations needed.
*/
#endif
/* Only to be used inside a loop (see the break) */
#define SHIFT_BYTES(utf8, s, strend, buf, len, datumtype, needs_swap) \
STMT_START { \
if (UNLIKELY(utf8)) { \
if (!S_utf8_to_bytes(aTHX_ &s, strend, \
(char *) (buf), len, datumtype)) break; \
} else { \
if (UNLIKELY(needs_swap)) \
S_reverse_copy(s, (char *) (buf), len); \
else \
Copy(s, (char *) (buf), len, char); \
s += len; \
} \
} STMT_END
#define SHIFT16(utf8, s, strend, p, datumtype, needs_swap) \
SHIFT_BYTES(utf8, s, strend, OFF16(p), SIZE16, datumtype, needs_swap)
#define SHIFT32(utf8, s, strend, p, datumtype, needs_swap) \
SHIFT_BYTES(utf8, s, strend, OFF32(p), SIZE32, datumtype, needs_swap)
#define SHIFT_VAR(utf8, s, strend, var, datumtype, needs_swap) \
SHIFT_BYTES(utf8, s, strend, &(var), sizeof(var), datumtype, needs_swap)
#define PUSH_VAR(utf8, aptr, var, needs_swap) \
PUSH_BYTES(utf8, aptr, &(var), sizeof(var), needs_swap)
/* Avoid stack overflow due to pathological templates. 100 should be plenty. */
#define MAX_SUB_TEMPLATE_LEVEL 100
/* flags (note that type modifiers can also be used as flags!) */
#define FLAG_WAS_UTF8 0x40
#define FLAG_PARSE_UTF8 0x20 /* Parse as utf8 */
#define FLAG_UNPACK_ONLY_ONE 0x10
#define FLAG_DO_UTF8 0x08 /* The underlying string is utf8 */
#define FLAG_SLASH 0x04
#define FLAG_COMMA 0x02
#define FLAG_PACK 0x01
STATIC SV *
S_mul128(pTHX_ SV *sv, U8 m)
{
STRLEN len;
char *s = SvPV(sv, len);
char *t;
PERL_ARGS_ASSERT_MUL128;
if (! memBEGINs(s, len, "0000")) { /* need to grow sv */
SV * const tmpNew = newSVpvs("0000000000");
sv_catsv(tmpNew, sv);
SvREFCNT_dec(sv); /* free old sv */
sv = tmpNew;
s = SvPV(sv, len);
}
t = s + len - 1;
while (!*t) /* trailing '\0'? */
t--;
while (t > s) {
const U32 i = ((*t - '0') << 7) + m;
*(t--) = '0' + (char)(i % 10);
m = (char)(i / 10);
}
return (sv);
}
/* Explosives and implosives. */
#define ISUUCHAR(ch) inRANGE(NATIVE_TO_LATIN1(ch), \
NATIVE_TO_LATIN1(' '), \
NATIVE_TO_LATIN1('a') - 1)
/* type modifiers */
#define TYPE_IS_SHRIEKING 0x100
#define TYPE_IS_BIG_ENDIAN 0x200
#define TYPE_IS_LITTLE_ENDIAN 0x400
#define TYPE_IS_PACK 0x800
#define TYPE_ENDIANNESS_MASK (TYPE_IS_BIG_ENDIAN|TYPE_IS_LITTLE_ENDIAN)
#define TYPE_MODIFIERS(t) ((t) & ~0xFF)
#define TYPE_NO_MODIFIERS(t) ((U8) (t))
# define TYPE_ENDIANNESS(t) ((t) & TYPE_ENDIANNESS_MASK)
# define TYPE_NO_ENDIANNESS(t) ((t) & ~TYPE_ENDIANNESS_MASK)
# define ENDIANNESS_ALLOWED_TYPES "sSiIlLqQjJfFdDpP("
#define PACK_SIZE_CANNOT_CSUM 0x80
#define PACK_SIZE_UNPREDICTABLE 0x40 /* Not a fixed size element */
#define PACK_SIZE_MASK 0x3F
#include "packsizetables.inc"
static void
S_reverse_copy(const char *src, char *dest, STRLEN len)
{
dest += len;
while (len--)
*--dest = *src++;
}
STATIC U8
utf8_to_byte(pTHX_ const char **s, const char *end, I32 datumtype)
{
STRLEN retlen;
UV val;
if (*s >= end) {
goto croak;
}
val = utf8n_to_uvchr((U8 *) *s, end-*s, &retlen,
ckWARN(WARN_UTF8) ? 0 : UTF8_ALLOW_ANY);
if (retlen == (STRLEN) -1)
croak:
Perl_croak(aTHX_ "Malformed UTF-8 string in '%c' format in unpack",
(int) TYPE_NO_MODIFIERS(datumtype));
if (val >= 0x100) {
Perl_ck_warner(aTHX_ packWARN(WARN_UNPACK),
"Character in '%c' format wrapped in unpack",
(int) TYPE_NO_MODIFIERS(datumtype));
val = (U8) val;
}
*s += retlen;
return (U8)val;
}
#define SHIFT_BYTE(utf8, s, strend, datumtype) ((utf8) ? \
utf8_to_byte(aTHX_ &(s), (strend), (datumtype)) : \
*(U8 *)(s)++)
STATIC bool
S_utf8_to_bytes(pTHX_ const char **s, const char *end, const char *buf, SSize_t buf_len, I32 datumtype)
{
UV val;
STRLEN retlen;
const char *from = *s;
int bad = 0;
const U32 flags = ckWARN(WARN_UTF8) ?
UTF8_CHECK_ONLY : (UTF8_CHECK_ONLY | UTF8_ALLOW_ANY);
const bool needs_swap = NEEDS_SWAP(datumtype);
if (UNLIKELY(needs_swap))
buf += buf_len;
for (;buf_len > 0; buf_len--) {
if (from >= end) return FALSE;
val = utf8n_to_uvchr((U8 *) from, end-from, &retlen, flags);
if (retlen == (STRLEN) -1) {
from += UTF8_SAFE_SKIP(from, end);
bad |= 1;
} else from += retlen;
if (val >= 0x100) {
bad |= 2;
val = (U8) val;
}
if (UNLIKELY(needs_swap))
*(U8 *)--buf = (U8)val;
else
*(U8 *)buf++ = (U8)val;
}
/* We have enough characters for the buffer. Did we have problems ? */
if (bad) {
if (bad & 1) {
/* Rewalk the string fragment while warning */
const char *ptr;
const U32 flags = ckWARN(WARN_UTF8) ? 0 : UTF8_ALLOW_ANY;
for (ptr = *s; ptr < from; ptr += UTF8SKIP(ptr)) {
if (ptr >= end) break;
utf8n_to_uvchr((U8 *) ptr, end-ptr, &retlen, flags);
}
if (from > end) from = end;
}
if ((bad & 2))
Perl_ck_warner(aTHX_ packWARN(datumtype & TYPE_IS_PACK ?
WARN_PACK : WARN_UNPACK),
"Character(s) in '%c' format wrapped in %s",
(int) TYPE_NO_MODIFIERS(datumtype),
datumtype & TYPE_IS_PACK ? "pack" : "unpack");
}
*s = from;
return TRUE;
}
STATIC char *
S_my_bytes_to_utf8(const U8 *start, STRLEN len, char *dest, const bool needs_swap) {
PERL_ARGS_ASSERT_MY_BYTES_TO_UTF8;
if (UNLIKELY(needs_swap)) {
const U8 *p = start + len;
while (p-- > start) {
append_utf8_from_native_byte(*p, (U8 **) & dest);
}
} else {
const U8 * const end = start + len;
while (start < end) {
append_utf8_from_native_byte(*start, (U8 **) & dest);
start++;
}
}
return dest;
}
#define PUSH_BYTES(utf8, cur, buf, len, needs_swap) \
STMT_START { \
if (UNLIKELY(utf8)) \
(cur) = my_bytes_to_utf8((U8 *) buf, len, (cur), needs_swap); \
else { \
if (UNLIKELY(needs_swap)) \
S_reverse_copy((char *)(buf), cur, len); \
else \
Copy(buf, cur, len, char); \
(cur) += (len); \
} \
} STMT_END
#define SAFE_UTF8_EXPAND(var) \
STMT_START { \
if ((var) > SSize_t_MAX / UTF8_EXPAND) \
Perl_croak(aTHX_ "%s", "Out of memory during pack()"); \
(var) = (var) * UTF8_EXPAND; \
} STMT_END
#define GROWING2(utf8, cat, start, cur, item_size, item_count) \
STMT_START { \
if (SSize_t_MAX / (item_size) < (item_count)) \
Perl_croak(aTHX_ "%s", "Out of memory during pack()"); \
GROWING((utf8), (cat), (start), (cur), (item_size) * (item_count)); \
} STMT_END
#define GROWING(utf8, cat, start, cur, in_len) \
STMT_START { \
STRLEN glen = (in_len); \
STRLEN catcur = (STRLEN)((cur) - (start)); \
if (utf8) SAFE_UTF8_EXPAND(glen); \
if (SSize_t_MAX - glen < catcur) \
Perl_croak(aTHX_ "%s", "Out of memory during pack()"); \
if (catcur + glen >= SvLEN(cat)) { \
(start) = sv_exp_grow(cat, glen); \
(cur) = (start) + SvCUR(cat); \
} \
} STMT_END
#define PUSH_GROWING_BYTES(utf8, cat, start, cur, buf, in_len) \
STMT_START { \
const STRLEN glen = (in_len); \
STRLEN gl = glen; \
if (utf8) SAFE_UTF8_EXPAND(gl); \
if ((cur) + gl >= (start) + SvLEN(cat)) { \
*cur = '\0'; \
SvCUR_set((cat), (cur) - (start)); \
(start) = sv_exp_grow(cat, gl); \
(cur) = (start) + SvCUR(cat); \
} \
PUSH_BYTES(utf8, cur, buf, glen, 0); \
} STMT_END
#define PUSH_BYTE(utf8, s, byte) \
STMT_START { \
if (utf8) { \
const U8 au8 = (byte); \
(s) = my_bytes_to_utf8(&au8, 1, (s), 0);\
} else *(U8 *)(s)++ = (byte); \
} STMT_END
/* Only to be used inside a loop (see the break) */
#define NEXT_UNI_VAL(val, cur, str, end, utf8_flags) \
STMT_START { \
STRLEN retlen; \
if (str >= end) break; \
val = utf8n_to_uvchr((U8 *) str, end-str, &retlen, utf8_flags); \
if (retlen == (STRLEN) -1) { \
*cur = '\0'; \
Perl_croak(aTHX_ "Malformed UTF-8 string in pack"); \
} \
str += retlen; \
} STMT_END
static const char *_action( const tempsym_t* symptr )
{
return (const char *)(( symptr->flags & FLAG_PACK ) ? "pack" : "unpack");
}
/* Returns the sizeof() struct described by pat */
STATIC SSize_t
S_measure_struct(pTHX_ tempsym_t* symptr)
{
SSize_t total = 0;
PERL_ARGS_ASSERT_MEASURE_STRUCT;
while (next_symbol(symptr)) {
SSize_t len, size;
switch (symptr->howlen) {
case e_star:
Perl_croak(aTHX_ "Within []-length '*' not allowed in %s",
_action( symptr ) );
default:
/* e_no_len and e_number */
len = symptr->length;
break;
}
size = packprops[TYPE_NO_ENDIANNESS(symptr->code)] & PACK_SIZE_MASK;
if (!size) {
SSize_t star;
/* endianness doesn't influence the size of a type */
switch(TYPE_NO_ENDIANNESS(symptr->code)) {
default:
/* diag_listed_as: Invalid type '%s' in %s */
Perl_croak(aTHX_ "Invalid type '%c' in %s",
(int)TYPE_NO_MODIFIERS(symptr->code),
_action( symptr ) );
case '.' | TYPE_IS_SHRIEKING:
case '@' | TYPE_IS_SHRIEKING:
case '@':
case '.':
case '/':
case 'U': /* XXXX Is it correct? */
case 'w':
case 'u':
Perl_croak(aTHX_ "Within []-length '%c' not allowed in %s",
(int) TYPE_NO_MODIFIERS(symptr->code),
_action( symptr ) );
case '%':
size = 0;
break;
case '(':
{
tempsym_t savsym = *symptr;
symptr->patptr = savsym.grpbeg;
symptr->patend = savsym.grpend;
/* XXXX Theoretically, we need to measure many times at
different positions, since the subexpression may contain
alignment commands, but be not of aligned length.
Need to detect this and croak(). */
size = measure_struct(symptr);
*symptr = savsym;
break;
}
case 'X' | TYPE_IS_SHRIEKING:
/* XXXX Is this useful? Then need to treat MEASURE_BACKWARDS.
*/
if (!len) /* Avoid division by 0 */
len = 1;
len = total % len; /* Assumed: the start is aligned. */
/* FALLTHROUGH */
case 'X':
size = -1;
if (total < len)
Perl_croak(aTHX_ "'X' outside of string in %s", _action( symptr ) );
break;
case 'x' | TYPE_IS_SHRIEKING:
if (!len) /* Avoid division by 0 */
len = 1;
star = total % len; /* Assumed: the start is aligned. */
if (star) /* Other portable ways? */
len = len - star;
else
len = 0;
/* FALLTHROUGH */
case 'x':
case 'A':
case 'Z':
case 'a':
size = 1;
break;
case 'B':
case 'b':
len = (len + 7)/8;
size = 1;
break;
case 'H':
case 'h':
len = (len + 1)/2;
size = 1;
break;
case 'P':
len = 1;
size = sizeof(char*);
break;
}
}
total += len * size;
}
return total;
}
/* locate matching closing parenthesis or bracket
* returns char pointer to char after match, or NULL
*/
STATIC const char *
S_group_end(pTHX_ const char *patptr, const char *patend, char ender)
{
PERL_ARGS_ASSERT_GROUP_END;
Size_t opened = 0; /* number of pending opened brackets */
while (patptr < patend) {
const char c = *patptr++;
if (opened == 0 && c == ender)
return patptr-1;
else if (c == '#') {
while (patptr < patend && *patptr != '\n')
patptr++;
continue;
} else if (c == '(' || c == '[')
++opened;
else if (c == ')' || c == ']') {
if (opened == 0)
Perl_croak(aTHX_ "Mismatched brackets in template");
--opened;
}
}
Perl_croak(aTHX_ "No group ending character '%c' found in template",
ender);
NOT_REACHED; /* NOTREACHED */
}
/* Convert unsigned decimal number to binary.
* Expects a pointer to the first digit and address of length variable
* Advances char pointer to 1st non-digit char and returns number
*/
STATIC const char *
S_get_num(pTHX_ const char *patptr, SSize_t *lenptr )
{
SSize_t len = *patptr++ - '0';
PERL_ARGS_ASSERT_GET_NUM;
while (isDIGIT(*patptr)) {
SSize_t nlen = (len * 10) + (*patptr++ - '0');
if (nlen < 0 || nlen/10 != len)
Perl_croak(aTHX_ "pack/unpack repeat count overflow");
len = nlen;
}
*lenptr = len;
return patptr;
}
/* The marvellous template parsing routine: Using state stored in *symptr,
* locates next template code and count
*/
STATIC bool
S_next_symbol(pTHX_ tempsym_t* symptr )
{
const char* patptr = symptr->patptr;
const char* const patend = symptr->patend;
PERL_ARGS_ASSERT_NEXT_SYMBOL;
symptr->flags &= ~FLAG_SLASH;
while (patptr < patend) {
if (isSPACE(*patptr))
patptr++;
else if (*patptr == '#') {
patptr++;
while (patptr < patend && *patptr != '\n')
patptr++;
if (patptr < patend)
patptr++;
} else {
/* We should have found a template code */
I32 code = (U8) *patptr++;
U32 inherited_modifiers = 0;
/* unrecognised characters in pack/unpack formats were made fatal in
* 5.004, with an exception added in 5.004_04 for ',' to "just" warn: */
if (code == ','){
if (((symptr->flags & FLAG_COMMA) == 0) && ckWARN(WARN_UNPACK)){
symptr->flags |= FLAG_COMMA;
/* diag_listed_as: Invalid type '%s' in %s */
Perl_warner(aTHX_ packWARN(WARN_UNPACK),
"Invalid type ',' in %s", _action( symptr ) );
}
continue;
}
/* for '(', skip to ')' */
if (code == '(') {
if( isDIGIT(*patptr) || *patptr == '*' || *patptr == '[' )
Perl_croak(aTHX_ "()-group starts with a count in %s",
_action( symptr ) );
symptr->grpbeg = patptr;
patptr = 1 + ( symptr->grpend = group_end(patptr, patend, ')') );
if( symptr->level >= MAX_SUB_TEMPLATE_LEVEL )
Perl_croak(aTHX_ "Too deeply nested ()-groups in %s",
_action( symptr ) );
}
/* look for group modifiers to inherit */
if (TYPE_ENDIANNESS(symptr->flags)) {
if (strchr(ENDIANNESS_ALLOWED_TYPES, TYPE_NO_MODIFIERS(code)))
inherited_modifiers |= TYPE_ENDIANNESS(symptr->flags);
}
/* look for modifiers */
while (patptr < patend) {
const char *allowed;
I32 modifier;
switch (*patptr) {
case '!':
modifier = TYPE_IS_SHRIEKING;
allowed = "sSiIlLxXnNvV@.";
break;
case '>':
modifier = TYPE_IS_BIG_ENDIAN;
allowed = ENDIANNESS_ALLOWED_TYPES;
break;
case '<':
modifier = TYPE_IS_LITTLE_ENDIAN;
allowed = ENDIANNESS_ALLOWED_TYPES;
break;
default:
allowed = "";
modifier = 0;
break;
}
if (modifier == 0)
break;
if (!strchr(allowed, TYPE_NO_MODIFIERS(code)))
Perl_croak(aTHX_ "'%c' allowed only after types %s in %s", *patptr,
allowed, _action( symptr ) );
if (TYPE_ENDIANNESS(code | modifier) == TYPE_ENDIANNESS_MASK)
Perl_croak(aTHX_ "Can't use both '<' and '>' after type '%c' in %s",
(int) TYPE_NO_MODIFIERS(code), _action( symptr ) );
else if (TYPE_ENDIANNESS(code | modifier | inherited_modifiers) ==
TYPE_ENDIANNESS_MASK)
Perl_croak(aTHX_ "Can't use '%c' in a group with different byte-order in %s",
*patptr, _action( symptr ) );
if ((code & modifier)) {
Perl_ck_warner(aTHX_ packWARN(WARN_UNPACK),
"Duplicate modifier '%c' after '%c' in %s",
*patptr, (int) TYPE_NO_MODIFIERS(code),
_action( symptr ) );
}
code |= modifier;
patptr++;
}
/* inherit modifiers */
code |= inherited_modifiers;
/* look for count and/or / */
if (patptr < patend) {
if (isDIGIT(*patptr)) {
patptr = get_num( patptr, &symptr->length );
symptr->howlen = e_number;
} else if (*patptr == '*') {
patptr++;
symptr->howlen = e_star;
} else if (*patptr == '[') {
const char* lenptr = ++patptr;
symptr->howlen = e_number;
patptr = group_end( patptr, patend, ']' ) + 1;
/* what kind of [] is it? */
if (isDIGIT(*lenptr)) {
lenptr = get_num( lenptr, &symptr->length );
if( *lenptr != ']' )
Perl_croak(aTHX_ "Malformed integer in [] in %s",
_action( symptr ) );
} else {
tempsym_t savsym = *symptr;
symptr->patend = patptr-1;
symptr->patptr = lenptr;
savsym.length = measure_struct(symptr);
*symptr = savsym;
}
} else {
symptr->howlen = e_no_len;
symptr->length = 1;
}
/* try to find / */
while (patptr < patend) {
if (isSPACE(*patptr))
patptr++;
else if (*patptr == '#') {
patptr++;
while (patptr < patend && *patptr != '\n')
patptr++;
if (patptr < patend)
patptr++;
} else {
if (*patptr == '/') {
symptr->flags |= FLAG_SLASH;
patptr++;
if (patptr < patend &&
(isDIGIT(*patptr) || *patptr == '*' || *patptr == '['))
Perl_croak(aTHX_ "'/' does not take a repeat count in %s",
_action( symptr ) );
}
break;
}
}
} else {
/* at end - no count, no / */
symptr->howlen = e_no_len;
symptr->length = 1;
}
symptr->code = code;
symptr->patptr = patptr;
return TRUE;
}
}
symptr->patptr = patptr;
return FALSE;
}
/*
There is no way to cleanly handle the case where we should process the
string per byte in its upgraded form while it's really in downgraded form
(e.g. estimates like strend-s as an upper bound for the number of
characters left wouldn't work). So if we foresee the need of this
(pattern starts with U or contains U0), we want to work on the encoded
version of the string. Users are advised to upgrade their pack string
themselves if they need to do a lot of unpacks like this on it
*/
STATIC bool
need_utf8(const char *pat, const char *patend)
{
bool first = TRUE;
PERL_ARGS_ASSERT_NEED_UTF8;
while (pat < patend) {
if (pat[0] == '#') {
pat++;
pat = (const char *) memchr(pat, '\n', patend-pat);
if (!pat) return FALSE;
} else if (pat[0] == 'U') {
if (first || pat[1] == '0') return TRUE;
} else first = FALSE;
pat++;
}
return FALSE;
}
STATIC char
first_symbol(const char *pat, const char *patend) {
PERL_ARGS_ASSERT_FIRST_SYMBOL;
while (pat < patend) {
if (pat[0] != '#') return pat[0];
pat++;
pat = (const char *) memchr(pat, '\n', patend-pat);
if (!pat) return 0;
pat++;
}
return 0;
}
/*
=for apidoc unpackstring
The engine implementing the C<unpack()> Perl function.
Using the template C<pat..patend>, this function unpacks the string
C<s..strend> into a number of mortal SVs, which it pushes onto the perl
argument (C<@_>) stack (so you will need to issue a C<PUTBACK> before and
C<SPAGAIN> after the call to this function). It returns the number of
pushed elements.
The C<strend> and C<patend> pointers should point to the byte following the
last character of each string.
Although this function returns its values on the perl argument stack, it
doesn't take any parameters from that stack (and thus in particular
there's no need to do a C<PUSHMARK> before calling it, unlike L</call_pv> for
example).
=cut */
SSize_t
Perl_unpackstring(pTHX_ const char *pat, const char *patend, const char *s, const char *strend, U32 flags)
{
tempsym_t sym;
PERL_ARGS_ASSERT_UNPACKSTRING;
if (flags & FLAG_DO_UTF8) flags |= FLAG_WAS_UTF8;
else if (need_utf8(pat, patend)) {
/* We probably should try to avoid this in case a scalar context call
wouldn't get to the "U0" */
STRLEN len = strend - s;
s = (char *) bytes_to_utf8_temp_pv((U8 *) s, &len);
strend = s + len;
flags |= FLAG_DO_UTF8;
}
if (first_symbol(pat, patend) != 'U' && (flags & FLAG_DO_UTF8))
flags |= FLAG_PARSE_UTF8;
TEMPSYM_INIT(&sym, pat, patend, flags);
return unpack_rec(&sym, s, s, strend, NULL );
}
STATIC SSize_t
S_unpack_rec(pTHX_ tempsym_t* symptr, const char *s, const char *strbeg, const char *strend, const char **new_s )
{
dSP;
SV *sv = NULL;
const SSize_t start_sp_offset = SP - PL_stack_base;
howlen_t howlen;
SSize_t checksum = 0;
UV cuv = 0;
NV cdouble = 0.0;
const SSize_t bits_in_uv = CHAR_BIT * sizeof(cuv);
bool beyond = FALSE;
bool explicit_length;
const bool unpack_only_one = (symptr->flags & FLAG_UNPACK_ONLY_ONE) != 0;
bool utf8 = (symptr->flags & FLAG_PARSE_UTF8) ? 1 : 0;
PERL_ARGS_ASSERT_UNPACK_REC;
symptr->strbeg = s - strbeg;
while (next_symbol(symptr)) {
packprops_t props;
SSize_t len;
I32 datumtype = symptr->code;
bool needs_swap;
/* do first one only unless in list context
/ is implemented by unpacking the count, then popping it from the
stack, so must check that we're not in the middle of a / */
if ( unpack_only_one
&& (SP - PL_stack_base == start_sp_offset + 1)
&& (datumtype != '/') ) /* XXX can this be omitted */
break;
switch (howlen = symptr->howlen) {
case e_star:
len = strend - strbeg; /* long enough */
break;
default:
/* e_no_len and e_number */
len = symptr->length;
break;
}
explicit_length = TRUE;
redo_switch:
beyond = s >= strend;
props = packprops[TYPE_NO_ENDIANNESS(datumtype)];
if (props) {
/* props nonzero means we can process this letter. */
const SSize_t size = props & PACK_SIZE_MASK;
const SSize_t howmany = (strend - s) / size;
if (len > howmany)
len = howmany;
if (!checksum || (props & PACK_SIZE_CANNOT_CSUM)) {
if (len && unpack_only_one) len = 1;
EXTEND(SP, len);
EXTEND_MORTAL(len);
}
}
needs_swap = NEEDS_SWAP(datumtype);
switch(TYPE_NO_ENDIANNESS(datumtype)) {
default:
/* diag_listed_as: Invalid type '%s' in %s */
Perl_croak(aTHX_ "Invalid type '%c' in unpack", (int)TYPE_NO_MODIFIERS(datumtype) );
case '%':
if (howlen == e_no_len)
len = 16; /* len is not specified */
checksum = len;
cuv = 0;
cdouble = 0;
continue;
case '(':
{
tempsym_t savsym = *symptr;
const U32 group_modifiers = TYPE_MODIFIERS(datumtype & ~symptr->flags);
symptr->flags |= group_modifiers;
symptr->patend = savsym.grpend;
/* cppcheck-suppress autoVariables */
symptr->previous = &savsym;
symptr->level++;
PUTBACK;
if (len && unpack_only_one) len = 1;
while (len--) {
symptr->patptr = savsym.grpbeg;
if (utf8) symptr->flags |= FLAG_PARSE_UTF8;
else symptr->flags &= ~FLAG_PARSE_UTF8;
unpack_rec(symptr, s, strbeg, strend, &s);
if (s == strend && savsym.howlen == e_star)
break; /* No way to continue */
}
SPAGAIN;
savsym.flags = symptr->flags & ~group_modifiers;
*symptr = savsym;
break;
}
case '.' | TYPE_IS_SHRIEKING:
case '.': {
const char *from;
SV *sv;
const bool u8 = utf8 && !(datumtype & TYPE_IS_SHRIEKING);
if (howlen == e_star) from = strbeg;
else if (len <= 0) from = s;
else {
tempsym_t *group = symptr;
while (--len && group) group = group->previous;
from = group ? strbeg + group->strbeg : strbeg;
}
sv = from <= s ?
newSVuv( u8 ? (UV) utf8_length((const U8*)from, (const U8*)s) : (UV) (s-from)) :
newSViv(-(u8 ? (IV) utf8_length((const U8*)s, (const U8*)from) : (IV) (from-s)));
mXPUSHs(sv);
break;
}
case '@' | TYPE_IS_SHRIEKING:
case '@':
s = strbeg + symptr->strbeg;
if (utf8 && !(datumtype & TYPE_IS_SHRIEKING)) {
s = (char *) utf8_hop_forward((U8 *) s, len, (U8 *) strend);
if (s >= strend)
Perl_croak(aTHX_ "'@' outside of string in unpack");
} else {
if (strend-s < len)
Perl_croak(aTHX_ "'@' outside of string in unpack");
s += len;
}
break;
case 'X' | TYPE_IS_SHRIEKING:
if (!len) /* Avoid division by 0 */
len = 1;
if (utf8) {
const char *hop, *last;
SSize_t l = len;
hop = last = strbeg;
while (hop < s) {
hop += UTF8SKIP(hop);
if (--l == 0) {