This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Change names of some OPpTRANS flags
[perl5.git] / doop.c
1 /*    doop.c
2  *
3  *    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
4  *    2001, 2002, 2004, 2005, 2006, 2007, 2008, 2009 by Larry Wall and others
5  *
6  *    You may distribute under the terms of either the GNU General Public
7  *    License or the Artistic License, as specified in the README file.
8  *
9  */
10
11 /*
12  *  'So that was the job I felt I had to do when I started,' thought Sam.
13  *
14  *     [p.934 of _The Lord of the Rings_, VI/iii: "Mount Doom"]
15  */
16
17 /* This file contains some common functions needed to carry out certain
18  * ops. For example, both pp_sprintf() and pp_prtf() call the function
19  * do_sprintf() found in this file.
20  */
21
22 #include "EXTERN.h"
23 #define PERL_IN_DOOP_C
24 #include "perl.h"
25
26 #ifndef PERL_MICRO
27 #include <signal.h>
28 #endif
29
30
31 /* Helper function for do_trans().
32  * Handles cases where the search and replacement charlists aren't UTF-8,
33  * aren't identical, and neither the /d nor /s flag is present.
34  *
35  * sv may or may not be utf8.  Note that no code point above 255 can possibly
36  * be in the to-translate set
37  */
38
39 STATIC Size_t
40 S_do_trans_simple(pTHX_ SV * const sv, const OPtrans_map * const tbl)
41 {
42     Size_t matches = 0;
43     STRLEN len;
44     U8 *s = (U8*)SvPV_nomg(sv,len);
45     U8 * const send = s+len;
46
47     PERL_ARGS_ASSERT_DO_TRANS_SIMPLE;
48
49     /* First, take care of non-UTF-8 input strings, because they're easy */
50     if (!SvUTF8(sv)) {
51         while (s < send) {
52             const short ch = tbl->map[*s];
53             if (ch >= 0) {
54                 matches++;
55                 *s = (U8)ch;
56             }
57             s++;
58         }
59         SvSETMAGIC(sv);
60     }
61     else {
62         const bool grows = cBOOL(PL_op->op_private & OPpTRANS_GROWS);
63         U8 *d;
64         U8 *dstart;
65
66         /* Allow for worst-case expansion: Each input byte can become 2.  For a
67          * given input character, this happens when it occupies a single byte
68          * under UTF-8, but is to be translated to something that occupies two:
69          * $_="a".chr(400); tr/a/\xFE/, FE needs encoding. */
70         if (grows)
71             Newx(d, len*2+1, U8);
72         else
73             d = s;
74         dstart = d;
75         while (s < send) {
76             STRLEN ulen;
77             short ch;
78
79             /* Need to check this, otherwise 128..255 won't match */
80             const UV c = utf8n_to_uvchr(s, send - s, &ulen, UTF8_ALLOW_DEFAULT);
81             if (c < 0x100 && (ch = tbl->map[c]) >= 0) {
82                 matches++;
83                 d = uvchr_to_utf8(d, (UV)ch);
84                 s += ulen;
85             }
86             else { /* No match -> copy */
87                 Move(s, d, ulen, U8);
88                 d += ulen;
89                 s += ulen;
90             }
91         }
92         if (grows) {
93             sv_setpvn(sv, (char*)dstart, d - dstart);
94             Safefree(dstart);
95         }
96         else {
97             *d = '\0';
98             SvCUR_set(sv, d - dstart);
99         }
100         SvUTF8_on(sv);
101         SvSETMAGIC(sv);
102     }
103     return matches;
104 }
105
106
107 /* Helper function for do_trans().
108  * Handles cases where the search and replacement charlists are identical and
109  * non-utf8: so the string isn't modified, and only a count of modifiable
110  * chars is needed.
111  *
112  * Note that it doesn't handle /d or /s, since these modify the string even if
113  * the replacement list is empty.
114  *
115  * sv may or may not be utf8.  Note that no code point above 255 can possibly
116  * be in the to-translate set
117  */
118
119 STATIC Size_t
120 S_do_trans_count(pTHX_ SV * const sv, const OPtrans_map * const tbl)
121 {
122     STRLEN len;
123     const U8 *s = (const U8*)SvPV_nomg_const(sv, len);
124     const U8 * const send = s + len;
125     Size_t matches = 0;
126
127     PERL_ARGS_ASSERT_DO_TRANS_COUNT;
128
129     if (!SvUTF8(sv)) {
130         while (s < send) {
131             if (tbl->map[*s++] >= 0)
132                 matches++;
133         }
134     }
135     else {
136         const bool complement = cBOOL(PL_op->op_private & OPpTRANS_COMPLEMENT);
137         while (s < send) {
138             STRLEN ulen;
139             const UV c = utf8n_to_uvchr(s, send - s, &ulen, UTF8_ALLOW_DEFAULT);
140             if (c < 0x100) {
141                 if (tbl->map[c] >= 0)
142                     matches++;
143             } else if (complement)
144                 matches++;
145             s += ulen;
146         }
147     }
148
149     return matches;
150 }
151
152
153 /* Helper function for do_trans().
154  * Handles cases where the search and replacement charlists aren't identical
155  * and both are non-utf8, and one or both of /d, /s is specified.
156  *
157  * sv may or may not be utf8.  Note that no code point above 255 can possibly
158  * be in the to-translate set
159  */
160
161 STATIC Size_t
162 S_do_trans_complex(pTHX_ SV * const sv, const OPtrans_map * const tbl)
163 {
164     STRLEN len;
165     U8 *s = (U8*)SvPV_nomg(sv, len);
166     U8 * const send = s+len;
167     Size_t matches = 0;
168     const bool complement = cBOOL(PL_op->op_private & OPpTRANS_COMPLEMENT);
169
170     PERL_ARGS_ASSERT_DO_TRANS_COMPLEX;
171
172     if (!SvUTF8(sv)) {
173         U8 *d = s;
174         U8 * const dstart = d;
175
176         if (PL_op->op_private & OPpTRANS_SQUASH) {
177
178             /* What the mapping of the previous character was to.  If the new
179              * character has the same mapping, it is squashed from the output
180              * (but still is included in the count) */
181             short previous_map = (short) TR_OOB;
182
183             while (s < send) {
184                 const short this_map = tbl->map[*s];
185                 if (this_map >= 0) {
186                     matches++;
187                     if (this_map != previous_map) {
188                         *d++ = (U8)this_map;
189                         previous_map = this_map;
190                     }
191                 }
192                 else {
193                     if (this_map == (short) TR_UNMAPPED)
194                         *d++ = *s;
195                     else {
196                         assert(this_map == (short) TR_DELETE);
197                         matches++;
198                     }
199                     previous_map = (short) TR_OOB;
200                 }
201
202                 s++;
203             }
204         }
205         else {  /* Not to squash */
206             while (s < send) {
207                 const short this_map = tbl->map[*s];
208                 if (this_map >= 0) {
209                     matches++;
210                     *d++ = (U8)this_map;
211                 }
212                 else if (this_map == (short) TR_UNMAPPED)
213                     *d++ = *s;
214                 else if (this_map == (short) TR_DELETE)
215                     matches++;
216                 s++;
217             }
218         }
219         *d = '\0';
220         SvCUR_set(sv, d - dstart);
221     }
222     else { /* is utf8 */
223         const bool squash = cBOOL(PL_op->op_private & OPpTRANS_SQUASH);
224         const bool grows  = cBOOL(PL_op->op_private & OPpTRANS_GROWS);
225         U8 *d;
226         U8 *dstart;
227         Size_t size = tbl->size;
228
229         /* What the mapping of the previous character was to.  If the new
230          * character has the same mapping, it is squashed from the output (but
231          * still is included in the count) */
232         UV pch = TR_OOB;
233
234         if (grows)
235             /* Allow for worst-case expansion: Each input byte can become 2.
236              * For a given input character, this happens when it occupies a
237              * single byte under UTF-8, but is to be translated to something
238              * that occupies two: */
239             Newx(d, len*2+1, U8);
240         else
241             d = s;
242         dstart = d;
243
244         while (s < send) {
245             STRLEN len;
246             const UV comp = utf8n_to_uvchr(s, send - s, &len,
247                                            UTF8_ALLOW_DEFAULT);
248             UV     ch;
249             short sch;
250
251             sch = (comp < size)
252                   ? tbl->map[comp]
253                   : (! complement)
254                     ? (short) TR_UNMAPPED
255                     : tbl->map[size];
256
257             if (sch >= 0) {
258                 ch = (UV)sch;
259               replace:
260                 matches++;
261                 if (LIKELY(!squash || ch != pch)) {
262                     d = uvchr_to_utf8(d, ch);
263                     pch = ch;
264                 }
265                 s += len;
266                 continue;
267             }
268             else if (sch == (short) TR_UNMAPPED) {
269                 Move(s, d, len, U8);
270                 d += len;
271             }
272             else if (sch == (short) TR_DELETE)
273                 matches++;
274             else {
275                 assert(sch == (short) TR_R_EMPTY);  /* empty replacement */
276                 ch = comp;
277                 goto replace;
278             }
279
280             s += len;
281             pch = TR_OOB;
282         }
283
284         if (grows) {
285             sv_setpvn(sv, (char*)dstart, d - dstart);
286             Safefree(dstart);
287         }
288         else {
289             *d = '\0';
290             SvCUR_set(sv, d - dstart);
291         }
292         SvUTF8_on(sv);
293     }
294     SvSETMAGIC(sv);
295     return matches;
296 }
297
298
299 /* Helper function for do_trans().
300  * Handles utf8 cases(*) not involving the /c, /d, /s flags,
301  * and where search and replacement charlists aren't identical.
302  * (*) i.e. where the search or replacement charlists are utf8. sv may
303  * or may not be utf8.
304  */
305
306 STATIC Size_t
307 S_do_trans_simple_utf8(pTHX_ SV * const sv)
308 {
309     U8 *s;
310     U8 *send;
311     U8 *d;
312     U8 *start;
313     U8 *dstart, *dend;
314     Size_t matches = 0;
315     const bool grows = cBOOL(PL_op->op_private & OPpTRANS_GROWS);
316     STRLEN len;
317     SV* const  rv =
318 #ifdef USE_ITHREADS
319                     PAD_SVl(cPADOP->op_padix);
320 #else
321                     MUTABLE_SV(cSVOP->op_sv);
322 #endif
323     HV* const  hv = MUTABLE_HV(SvRV(rv));
324     SV* const * svp = hv_fetchs(hv, "NONE", FALSE);
325     const UV none = svp ? SvUV(*svp) : 0x7fffffff;
326     const UV extra = none + 1;
327     UV final = 0;
328     U8 hibit = 0;
329
330     PERL_ARGS_ASSERT_DO_TRANS_SIMPLE_UTF8;
331
332     s = (U8*)SvPV_nomg(sv, len);
333     if (!SvUTF8(sv)) {
334         hibit = ! is_utf8_invariant_string(s, len);
335         if (hibit) {
336             s = bytes_to_utf8(s, &len);
337         }
338     }
339     send = s + len;
340     start = s;
341
342     svp = hv_fetchs(hv, "FINAL", FALSE);
343     if (svp)
344         final = SvUV(*svp);
345
346     if (grows) {
347         /* d needs to be bigger than s, in case e.g. upgrading is required */
348         Newx(d, len * 3 + UTF8_MAXBYTES, U8);
349         dend = d + len * 3;
350         dstart = d;
351     }
352     else {
353         dstart = d = s;
354         dend = d + len;
355     }
356
357     while (s < send) {
358         const UV uv = swash_fetch(rv, s, TRUE);
359         if (uv < none) {
360             s += UTF8SKIP(s);
361             matches++;
362             d = uvchr_to_utf8(d, uv);
363         }
364         else if (uv == none) {
365             const int i = UTF8SKIP(s);
366             Move(s, d, i, U8);
367             d += i;
368             s += i;
369         }
370         else if (uv == extra) {
371             s += UTF8SKIP(s);
372             matches++;
373             d = uvchr_to_utf8(d, final);
374         }
375         else
376             s += UTF8SKIP(s);
377
378         if (d > dend) {
379             const STRLEN clen = d - dstart;
380             const STRLEN nlen = dend - dstart + len + UTF8_MAXBYTES;
381             if (!grows)
382                 Perl_croak(aTHX_ "panic: do_trans_simple_utf8 line %d",__LINE__);
383             Renew(dstart, nlen + UTF8_MAXBYTES, U8);
384             d = dstart + clen;
385             dend = dstart + nlen;
386         }
387     }
388     if (grows || hibit) {
389         sv_setpvn(sv, (char*)dstart, d - dstart);
390         Safefree(dstart);
391         if (grows && hibit)
392             Safefree(start);
393     }
394     else {
395         *d = '\0';
396         SvCUR_set(sv, d - dstart);
397     }
398     SvSETMAGIC(sv);
399     SvUTF8_on(sv);
400
401     return matches;
402 }
403
404
405 /* Helper function for do_trans().
406  * Handles utf8 cases(*) where search and replacement charlists are
407  * identical: so the string isn't modified, and only a count of modifiable
408  * chars is needed.
409  * Note that it doesn't handle /d or /s, since these modify the string
410  * even if the replacement charlist is empty.
411  * (*) i.e. where the search or replacement charlists are utf8. sv may
412  * or may not be utf8.
413  */
414
415 STATIC Size_t
416 S_do_trans_count_utf8(pTHX_ SV * const sv)
417 {
418     const U8 *s;
419     const U8 *start = NULL;
420     const U8 *send;
421     Size_t matches = 0;
422     STRLEN len;
423     SV* const  rv =
424 #ifdef USE_ITHREADS
425                     PAD_SVl(cPADOP->op_padix);
426 #else
427                     MUTABLE_SV(cSVOP->op_sv);
428 #endif
429     HV* const hv = MUTABLE_HV(SvRV(rv));
430     SV* const * const svp = hv_fetchs(hv, "NONE", FALSE);
431     const UV none = svp ? SvUV(*svp) : 0x7fffffff;
432     const UV extra = none + 1;
433     U8 hibit = 0;
434
435     PERL_ARGS_ASSERT_DO_TRANS_COUNT_UTF8;
436
437     s = (const U8*)SvPV_nomg_const(sv, len);
438     if (!SvUTF8(sv)) {
439         hibit = ! is_utf8_invariant_string(s, len);
440         if (hibit) {
441             start = s = bytes_to_utf8(s, &len);
442         }
443     }
444     send = s + len;
445
446     while (s < send) {
447         const UV uv = swash_fetch(rv, s, TRUE);
448         if (uv < none || uv == extra)
449             matches++;
450         s += UTF8SKIP(s);
451     }
452     if (hibit)
453         Safefree(start);
454
455     return matches;
456 }
457
458
459 /* Helper function for do_trans().
460  * Handles utf8 cases(*) involving the /c, /d, /s flags,
461  * and where search and replacement charlists aren't identical.
462  * (*) i.e. where the search or replacement charlists are utf8. sv may
463  * or may not be utf8.
464  */
465
466 STATIC Size_t
467 S_do_trans_complex_utf8(pTHX_ SV * const sv)
468 {
469     U8 *start, *send;
470     U8 *d;
471     Size_t matches = 0;
472     const bool squash   = cBOOL(PL_op->op_private & OPpTRANS_SQUASH);
473     const bool del      = cBOOL(PL_op->op_private & OPpTRANS_DELETE);
474     const bool grows    = cBOOL(PL_op->op_private & OPpTRANS_GROWS);
475     SV* const  rv =
476 #ifdef USE_ITHREADS
477                     PAD_SVl(cPADOP->op_padix);
478 #else
479                     MUTABLE_SV(cSVOP->op_sv);
480 #endif
481     HV * const hv = MUTABLE_HV(SvRV(rv));
482     SV * const *svp = hv_fetchs(hv, "NONE", FALSE);
483     const UV none = svp ? SvUV(*svp) : 0x7fffffff;
484     const UV extra = none + 1;
485     UV final = 0;
486     bool havefinal = FALSE;
487     STRLEN len;
488     U8 *dstart, *dend;
489     U8 hibit = 0;
490     U8 *s = (U8*)SvPV_nomg(sv, len);
491
492     PERL_ARGS_ASSERT_DO_TRANS_COMPLEX_UTF8;
493
494     if (!SvUTF8(sv)) {
495         hibit = ! is_utf8_invariant_string(s, len);
496         if (hibit) {
497             s = bytes_to_utf8(s, &len);
498         }
499     }
500     send = s + len;
501     start = s;
502
503     svp = hv_fetchs(hv, "FINAL", FALSE);
504     if (svp) {
505         final = SvUV(*svp);
506         havefinal = TRUE;
507     }
508
509     if (grows) {
510         /* d needs to be bigger than s, in case e.g. upgrading is required */
511         Newx(d, len * 3 + UTF8_MAXBYTES, U8);
512         dend = d + len * 3;
513         dstart = d;
514     }
515     else {
516         dstart = d = s;
517         dend = d + len;
518     }
519
520     if (squash) {
521         UV puv = 0xfeedface;
522         while (s < send) {
523             UV uv = swash_fetch(rv, s, TRUE);
524
525             if (d > dend) {
526                 const STRLEN clen = d - dstart;
527                 const STRLEN nlen = dend - dstart + len + UTF8_MAXBYTES;
528                 if (!grows)
529                     Perl_croak(aTHX_ "panic: do_trans_complex_utf8 line %d",__LINE__);
530                 Renew(dstart, nlen + UTF8_MAXBYTES, U8);
531                 d = dstart + clen;
532                 dend = dstart + nlen;
533             }
534             if (uv < none) {
535                 matches++;
536                 s += UTF8SKIP(s);
537                 if (uv != puv) {
538                     d = uvchr_to_utf8(d, uv);
539                     puv = uv;
540                 }
541                 continue;
542             }
543             else if (uv == none) {      /* "none" is unmapped character */
544                 const int i = UTF8SKIP(s);
545                 Move(s, d, i, U8);
546                 d += i;
547                 s += i;
548                 puv = 0xfeedface;
549                 continue;
550             }
551             else if (uv == extra && !del) {
552                 matches++;
553                 if (havefinal) {
554                     s += UTF8SKIP(s);
555                     if (puv != final) {
556                         d = uvchr_to_utf8(d, final);
557                         puv = final;
558                     }
559                 }
560                 else {
561                     STRLEN len;
562                     uv = utf8n_to_uvchr(s, send - s, &len, UTF8_ALLOW_DEFAULT);
563                     if (uv != puv) {
564                         Move(s, d, len, U8);
565                         d += len;
566                         puv = uv;
567                     }
568                     s += len;
569                 }
570                 continue;
571             }
572             matches++;                  /* "none+1" is delete character */
573             s += UTF8SKIP(s);
574         }
575     }
576     else {
577         while (s < send) {
578             const UV uv = swash_fetch(rv, s, TRUE);
579             if (d > dend) {
580                 const STRLEN clen = d - dstart;
581                 const STRLEN nlen = dend - dstart + len + UTF8_MAXBYTES;
582                 if (!grows)
583                     Perl_croak(aTHX_ "panic: do_trans_complex_utf8 line %d",__LINE__);
584                 Renew(dstart, nlen + UTF8_MAXBYTES, U8);
585                 d = dstart + clen;
586                 dend = dstart + nlen;
587             }
588             if (uv < none) {
589                 matches++;
590                 s += UTF8SKIP(s);
591                 d = uvchr_to_utf8(d, uv);
592                 continue;
593             }
594             else if (uv == none) {      /* "none" is unmapped character */
595                 const int i = UTF8SKIP(s);
596                 Move(s, d, i, U8);
597                 d += i;
598                 s += i;
599                 continue;
600             }
601             else if (uv == extra && !del) {
602                 matches++;
603                 s += UTF8SKIP(s);
604                 d = uvchr_to_utf8(d, final);
605                 continue;
606             }
607             matches++;                  /* "none+1" is delete character */
608             s += UTF8SKIP(s);
609         }
610     }
611     if (grows || hibit) {
612         sv_setpvn(sv, (char*)dstart, d - dstart);
613         Safefree(dstart);
614         if (grows && hibit)
615             Safefree(start);
616     }
617     else {
618         *d = '\0';
619         SvCUR_set(sv, d - dstart);
620     }
621     SvUTF8_on(sv);
622     SvSETMAGIC(sv);
623
624     return matches;
625 }
626
627
628 /* Execute a tr//. sv is the value to be translated, while PL_op
629  * should be an OP_TRANS or OP_TRANSR op, whose op_pv field contains a
630  * translation table or whose op_sv field contains a swash.
631  * Returns a count of number of characters translated
632  */
633
634 Size_t
635 Perl_do_trans(pTHX_ SV *sv)
636 {
637     STRLEN len;
638     const U8 flags = PL_op->op_private;
639     const U8 hasutf = flags & (OPpTRANS_FROM_UTF | OPpTRANS_TO_UTF);
640
641     PERL_ARGS_ASSERT_DO_TRANS;
642
643     if (SvREADONLY(sv) && !(flags & OPpTRANS_IDENTICAL)) {
644         Perl_croak_no_modify();
645     }
646     (void)SvPV_const(sv, len);
647     if (!len)
648         return 0;
649     if (!(flags & OPpTRANS_IDENTICAL)) {
650         if (!SvPOKp(sv) || SvTHINKFIRST(sv))
651             (void)SvPV_force_nomg(sv, len);
652         (void)SvPOK_only_UTF8(sv);
653     }
654
655     /* If we use only OPpTRANS_IDENTICAL to bypass the READONLY check,
656      * we must also rely on it to choose the readonly strategy.
657      */
658     if (flags & OPpTRANS_IDENTICAL) {
659         return hasutf ? do_trans_count_utf8(sv) : do_trans_count(sv, (OPtrans_map*)cPVOP->op_pv);
660     } else if (flags & (OPpTRANS_SQUASH|OPpTRANS_DELETE|OPpTRANS_COMPLEMENT)) {
661         return hasutf ? do_trans_complex_utf8(sv) : do_trans_complex(sv, (OPtrans_map*)cPVOP->op_pv);
662     } else {
663         return hasutf ? do_trans_simple_utf8(sv) : do_trans_simple(sv, (OPtrans_map*)cPVOP->op_pv);
664     }
665 }
666
667 void
668 Perl_do_join(pTHX_ SV *sv, SV *delim, SV **mark, SV **sp)
669 {
670     SV ** const oldmark = mark;
671     I32 items = sp - mark;
672     STRLEN len;
673     STRLEN delimlen;
674     const char * const delims = SvPV_const(delim, delimlen);
675
676     PERL_ARGS_ASSERT_DO_JOIN;
677
678     mark++;
679     len = (items > 0 ? (delimlen * (items - 1) ) : 0);
680     SvUPGRADE(sv, SVt_PV);
681     if (SvLEN(sv) < len + items) {      /* current length is way too short */
682         while (items-- > 0) {
683             if (*mark && !SvGAMAGIC(*mark) && SvOK(*mark)) {
684                 STRLEN tmplen;
685                 SvPV_const(*mark, tmplen);
686                 len += tmplen;
687             }
688             mark++;
689         }
690         SvGROW(sv, len + 1);            /* so try to pre-extend */
691
692         mark = oldmark;
693         items = sp - mark;
694         ++mark;
695     }
696
697     SvPVCLEAR(sv);
698     /* sv_setpv retains old UTF8ness [perl #24846] */
699     SvUTF8_off(sv);
700
701     if (TAINTING_get && SvMAGICAL(sv))
702         SvTAINTED_off(sv);
703
704     if (items-- > 0) {
705         if (*mark)
706             sv_catsv(sv, *mark);
707         mark++;
708     }
709
710     if (delimlen) {
711         const U32 delimflag = DO_UTF8(delim) ? SV_CATUTF8 : SV_CATBYTES;
712         for (; items > 0; items--,mark++) {
713             STRLEN len;
714             const char *s;
715             sv_catpvn_flags(sv,delims,delimlen,delimflag);
716             s = SvPV_const(*mark,len);
717             sv_catpvn_flags(sv,s,len,
718                             DO_UTF8(*mark) ? SV_CATUTF8 : SV_CATBYTES);
719         }
720     }
721     else {
722         for (; items > 0; items--,mark++)
723         {
724             STRLEN len;
725             const char *s = SvPV_const(*mark,len);
726             sv_catpvn_flags(sv,s,len,
727                             DO_UTF8(*mark) ? SV_CATUTF8 : SV_CATBYTES);
728         }
729     }
730     SvSETMAGIC(sv);
731 }
732
733 void
734 Perl_do_sprintf(pTHX_ SV *sv, SSize_t len, SV **sarg)
735 {
736     STRLEN patlen;
737     const char * const pat = SvPV_const(*sarg, patlen);
738     bool do_taint = FALSE;
739
740     PERL_ARGS_ASSERT_DO_SPRINTF;
741     assert(len >= 1);
742
743     if (SvTAINTED(*sarg))
744         TAINT_PROPER(
745                 (PL_op && PL_op->op_type < OP_max)
746                     ? (PL_op->op_type == OP_PRTF)
747                         ? "printf"
748                         : PL_op_name[PL_op->op_type]
749                     : "(unknown)"
750         );
751     SvUTF8_off(sv);
752     if (DO_UTF8(*sarg))
753         SvUTF8_on(sv);
754     sv_vsetpvfn(sv, pat, patlen, NULL, sarg + 1, (Size_t)(len - 1), &do_taint);
755     SvSETMAGIC(sv);
756     if (do_taint)
757         SvTAINTED_on(sv);
758 }
759
760 /* currently converts input to bytes if possible, but doesn't sweat failure */
761 UV
762 Perl_do_vecget(pTHX_ SV *sv, STRLEN offset, int size)
763 {
764     STRLEN srclen, len, avail, uoffset, bitoffs = 0;
765     const I32 svpv_flags = ((PL_op->op_flags & OPf_MOD || LVRET)
766                                           ? SV_UNDEF_RETURNS_NULL : 0);
767     unsigned char *s = (unsigned char *)
768                             SvPV_flags(sv, srclen, (svpv_flags|SV_GMAGIC));
769     UV retnum = 0;
770
771     if (!s) {
772       s = (unsigned char *)"";
773     }
774
775     PERL_ARGS_ASSERT_DO_VECGET;
776
777     if (size < 1 || (size & (size-1))) /* size < 1 or not a power of two */
778         Perl_croak(aTHX_ "Illegal number of bits in vec");
779
780     if (SvUTF8(sv)) {
781         if (Perl_sv_utf8_downgrade_flags(aTHX_ sv, TRUE, 0)) {
782             /* PVX may have changed */
783             s = (unsigned char *) SvPV_flags(sv, srclen, svpv_flags);
784         }
785         else {
786                 Perl_croak(aTHX_ "Use of strings with code points over 0xFF as arguments to vec is forbidden");
787         }
788     }
789
790     if (size < 8) {
791         bitoffs = ((offset%8)*size)%8;
792         uoffset = offset/(8/size);
793     }
794     else if (size > 8) {
795         int n = size/8;
796         if (offset > Size_t_MAX / n - 1) /* would overflow */
797             return 0;
798         uoffset = offset*n;
799     }
800     else
801         uoffset = offset;
802
803     if (uoffset >= srclen)
804         return 0;
805
806     len   = (bitoffs + size + 7)/8; /* required number of bytes */
807     avail = srclen - uoffset;       /* available number of bytes */
808
809     /* Does the byte range overlap the end of the string? If so,
810      * handle specially. */
811     if (avail < len) {
812         if (size <= 8)
813             retnum = 0;
814         else {
815             if (size == 16) {
816                 assert(avail == 1);
817                 retnum = (UV) s[uoffset] <<  8;
818             }
819             else if (size == 32) {
820                 assert(avail >= 1 && avail <= 3);
821                 if (avail == 1)
822                     retnum =
823                         ((UV) s[uoffset    ] << 24);
824                 else if (avail == 2)
825                     retnum =
826                         ((UV) s[uoffset    ] << 24) +
827                         ((UV) s[uoffset + 1] << 16);
828                 else
829                     retnum =
830                         ((UV) s[uoffset    ] << 24) +
831                         ((UV) s[uoffset + 1] << 16) +
832                         (     s[uoffset + 2] <<  8);
833             }
834 #ifdef UV_IS_QUAD
835             else if (size == 64) {
836                 Perl_ck_warner(aTHX_ packWARN(WARN_PORTABLE),
837                                "Bit vector size > 32 non-portable");
838                 assert(avail >= 1 && avail <= 7);
839                 if (avail == 1)
840                     retnum =
841                         (UV) s[uoffset     ] << 56;
842                 else if (avail == 2)
843                     retnum =
844                         ((UV) s[uoffset    ] << 56) +
845                         ((UV) s[uoffset + 1] << 48);
846                 else if (avail == 3)
847                     retnum =
848                         ((UV) s[uoffset    ] << 56) +
849                         ((UV) s[uoffset + 1] << 48) +
850                         ((UV) s[uoffset + 2] << 40);
851                 else if (avail == 4)
852                     retnum =
853                         ((UV) s[uoffset    ] << 56) +
854                         ((UV) s[uoffset + 1] << 48) +
855                         ((UV) s[uoffset + 2] << 40) +
856                         ((UV) s[uoffset + 3] << 32);
857                 else if (avail == 5)
858                     retnum =
859                         ((UV) s[uoffset    ] << 56) +
860                         ((UV) s[uoffset + 1] << 48) +
861                         ((UV) s[uoffset + 2] << 40) +
862                         ((UV) s[uoffset + 3] << 32) +
863                         ((UV) s[uoffset + 4] << 24);
864                 else if (avail == 6)
865                     retnum =
866                         ((UV) s[uoffset    ] << 56) +
867                         ((UV) s[uoffset + 1] << 48) +
868                         ((UV) s[uoffset + 2] << 40) +
869                         ((UV) s[uoffset + 3] << 32) +
870                         ((UV) s[uoffset + 4] << 24) +
871                         ((UV) s[uoffset + 5] << 16);
872                 else
873                     retnum =
874                         ((UV) s[uoffset    ] << 56) +
875                         ((UV) s[uoffset + 1] << 48) +
876                         ((UV) s[uoffset + 2] << 40) +
877                         ((UV) s[uoffset + 3] << 32) +
878                         ((UV) s[uoffset + 4] << 24) +
879                         ((UV) s[uoffset + 5] << 16) +
880                         ((UV) s[uoffset + 6] <<  8);
881             }
882 #endif
883         }
884     }
885     else if (size < 8)
886         retnum = (s[uoffset] >> bitoffs) & ((1 << size) - 1);
887     else {
888         if (size == 8)
889             retnum = s[uoffset];
890         else if (size == 16)
891             retnum =
892                 ((UV) s[uoffset] <<      8) +
893                       s[uoffset + 1];
894         else if (size == 32)
895             retnum =
896                 ((UV) s[uoffset    ] << 24) +
897                 ((UV) s[uoffset + 1] << 16) +
898                 (     s[uoffset + 2] <<  8) +
899                       s[uoffset + 3];
900 #ifdef UV_IS_QUAD
901         else if (size == 64) {
902             Perl_ck_warner(aTHX_ packWARN(WARN_PORTABLE),
903                            "Bit vector size > 32 non-portable");
904             retnum =
905                 ((UV) s[uoffset    ] << 56) +
906                 ((UV) s[uoffset + 1] << 48) +
907                 ((UV) s[uoffset + 2] << 40) +
908                 ((UV) s[uoffset + 3] << 32) +
909                 ((UV) s[uoffset + 4] << 24) +
910                 ((UV) s[uoffset + 5] << 16) +
911                 (     s[uoffset + 6] <<  8) +
912                       s[uoffset + 7];
913         }
914 #endif
915     }
916
917     return retnum;
918 }
919
920 /* currently converts input to bytes if possible but doesn't sweat failures,
921  * although it does ensure that the string it clobbers is not marked as
922  * utf8-valid any more
923  */
924 void
925 Perl_do_vecset(pTHX_ SV *sv)
926 {
927     STRLEN offset, bitoffs = 0;
928     int size;
929     unsigned char *s;
930     UV lval;
931     I32 mask;
932     STRLEN targlen;
933     STRLEN len;
934     SV * const targ = LvTARG(sv);
935     char errflags = LvFLAGS(sv);
936
937     PERL_ARGS_ASSERT_DO_VECSET;
938
939     /* some out-of-range errors have been deferred if/until the LV is
940      * actually written to: f(vec($s,-1,8)) is not always fatal */
941     if (errflags) {
942         assert(!(errflags & ~(LVf_NEG_OFF|LVf_OUT_OF_RANGE)));
943         if (errflags & LVf_NEG_OFF)
944             Perl_croak_nocontext("Negative offset to vec in lvalue context");
945         Perl_croak_nocontext("Out of memory!");
946     }
947
948     if (!targ)
949         return;
950     s = (unsigned char*)SvPV_force_flags(targ, targlen,
951                                          SV_GMAGIC | SV_UNDEF_RETURNS_NULL);
952     if (SvUTF8(targ)) {
953         /* This is handled by the SvPOK_only below...
954         if (!Perl_sv_utf8_downgrade_flags(aTHX_ targ, TRUE, 0))
955             SvUTF8_off(targ);
956          */
957         (void) Perl_sv_utf8_downgrade_flags(aTHX_ targ, TRUE, 0);
958     }
959
960     (void)SvPOK_only(targ);
961     lval = SvUV(sv);
962     offset = LvTARGOFF(sv);
963     size = LvTARGLEN(sv);
964
965     if (size < 1 || (size & (size-1))) /* size < 1 or not a power of two */
966         Perl_croak(aTHX_ "Illegal number of bits in vec");
967
968     if (size < 8) {
969         bitoffs = ((offset%8)*size)%8;
970         offset /= 8/size;
971     }
972     else if (size > 8) {
973         int n = size/8;
974         if (offset > Size_t_MAX / n - 1) /* would overflow */
975             Perl_croak_nocontext("Out of memory!");
976         offset *= n;
977     }
978
979     len = (bitoffs + size + 7)/8;       /* required number of bytes */
980     if (targlen < offset || targlen - offset < len) {
981         STRLEN newlen = offset > Size_t_MAX - len - 1 ? /* avoid overflow */
982                                         Size_t_MAX : offset + len + 1;
983         s = (unsigned char*)SvGROW(targ, newlen);
984         (void)memzero((char *)(s + targlen), newlen - targlen);
985         SvCUR_set(targ, newlen - 1);
986     }
987
988     if (size < 8) {
989         mask = (1 << size) - 1;
990         lval &= mask;
991         s[offset] &= ~(mask << bitoffs);
992         s[offset] |= lval << bitoffs;
993     }
994     else {
995         if (size == 8)
996             s[offset  ] = (U8)( lval        & 0xff);
997         else if (size == 16) {
998             s[offset  ] = (U8)((lval >>  8) & 0xff);
999             s[offset+1] = (U8)( lval        & 0xff);
1000         }
1001         else if (size == 32) {
1002             s[offset  ] = (U8)((lval >> 24) & 0xff);
1003             s[offset+1] = (U8)((lval >> 16) & 0xff);
1004             s[offset+2] = (U8)((lval >>  8) & 0xff);
1005             s[offset+3] = (U8)( lval        & 0xff);
1006         }
1007 #ifdef UV_IS_QUAD
1008         else if (size == 64) {
1009             Perl_ck_warner(aTHX_ packWARN(WARN_PORTABLE),
1010                            "Bit vector size > 32 non-portable");
1011             s[offset  ] = (U8)((lval >> 56) & 0xff);
1012             s[offset+1] = (U8)((lval >> 48) & 0xff);
1013             s[offset+2] = (U8)((lval >> 40) & 0xff);
1014             s[offset+3] = (U8)((lval >> 32) & 0xff);
1015             s[offset+4] = (U8)((lval >> 24) & 0xff);
1016             s[offset+5] = (U8)((lval >> 16) & 0xff);
1017             s[offset+6] = (U8)((lval >>  8) & 0xff);
1018             s[offset+7] = (U8)( lval        & 0xff);
1019         }
1020 #endif
1021     }
1022     SvSETMAGIC(targ);
1023 }
1024
1025 void
1026 Perl_do_vop(pTHX_ I32 optype, SV *sv, SV *left, SV *right)
1027 {
1028     long *dl;
1029     long *ll;
1030     long *rl;
1031     char *dc;
1032     STRLEN leftlen;
1033     STRLEN rightlen;
1034     const char *lc;
1035     const char *rc;
1036     STRLEN len = 0;
1037     STRLEN lensave;
1038     const char *lsave;
1039     const char *rsave;
1040     STRLEN needlen = 0;
1041     bool result_needs_to_be_utf8 = FALSE;
1042     bool left_utf8 = FALSE;
1043     bool right_utf8 = FALSE;
1044     U8 * left_non_downgraded = NULL;
1045     U8 * right_non_downgraded = NULL;
1046     Size_t left_non_downgraded_len = 0;
1047     Size_t right_non_downgraded_len = 0;
1048     char * non_downgraded = NULL;
1049     Size_t non_downgraded_len = 0;
1050
1051     PERL_ARGS_ASSERT_DO_VOP;
1052
1053     if (sv != left || (optype != OP_BIT_AND && !SvOK(sv)))
1054         SvPVCLEAR(sv);        /* avoid undef warning on |= and ^= */
1055     if (sv == left) {
1056         lc = SvPV_force_nomg(left, leftlen);
1057     }
1058     else {
1059         lc = SvPV_nomg_const(left, leftlen);
1060         SvPV_force_nomg_nolen(sv);
1061     }
1062     rc = SvPV_nomg_const(right, rightlen);
1063
1064     /* This needs to come after SvPV to ensure that string overloading has
1065        fired off.  */
1066
1067     /* Create downgraded temporaries of any UTF-8 encoded operands */
1068     if (DO_UTF8(left)) {
1069         const U8 * save_lc = (U8 *) lc;
1070
1071         left_utf8 = TRUE;
1072         result_needs_to_be_utf8 = TRUE;
1073
1074         left_non_downgraded_len = leftlen;
1075         lc = (char *) bytes_from_utf8_loc((const U8 *) lc, &leftlen,
1076                                           &left_utf8,
1077                                           (const U8 **) &left_non_downgraded);
1078         /* Calculate the number of trailing unconvertible bytes.  This quantity
1079          * is the original length minus the length of the converted portion. */
1080         left_non_downgraded_len -= left_non_downgraded - save_lc;
1081         SAVEFREEPV(lc);
1082     }
1083     if (DO_UTF8(right)) {
1084         const U8 * save_rc = (U8 *) rc;
1085
1086         right_utf8 = TRUE;
1087         result_needs_to_be_utf8 = TRUE;
1088
1089         right_non_downgraded_len = rightlen;
1090         rc = (char *) bytes_from_utf8_loc((const U8 *) rc, &rightlen,
1091                                           &right_utf8,
1092                                           (const U8 **) &right_non_downgraded);
1093         right_non_downgraded_len -= right_non_downgraded - save_rc;
1094         SAVEFREEPV(rc);
1095     }
1096
1097     /* We set 'len' to the length that the operation actually operates on.  The
1098      * dangling part of the longer operand doesn't actually participate in the
1099      * operation.  What happens is that we pretend that the shorter operand has
1100      * been extended to the right by enough imaginary zeros to match the length
1101      * of the longer one.  But we know in advance the result of the operation
1102      * on zeros without having to do it.  In the case of '&', the result is
1103      * zero, and the dangling portion is simply discarded.  For '|' and '^', the
1104      * result is the same as the other operand, so the dangling part is just
1105      * appended to the final result, unchanged.  As of perl-5.32, we no longer
1106      * accept above-FF code points in the dangling portion.
1107      */
1108     if (left_utf8 || right_utf8) {
1109         Perl_croak(aTHX_ FATAL_ABOVE_FF_MSG, PL_op_desc[optype]);
1110     }
1111     else {  /* Neither is UTF-8 */
1112         len = MIN(leftlen, rightlen);
1113     }
1114
1115     lensave = len;
1116     lsave = lc;
1117     rsave = rc;
1118
1119     SvCUR_set(sv, len);
1120     (void)SvPOK_only(sv);
1121     if (SvOK(sv) || SvTYPE(sv) > SVt_PVMG) {
1122         dc = SvPV_force_nomg_nolen(sv);
1123         if (SvLEN(sv) < len + 1) {
1124             dc = SvGROW(sv, len + 1);
1125             (void)memzero(dc + SvCUR(sv), len - SvCUR(sv) + 1);
1126         }
1127     }
1128     else {
1129         needlen = optype == OP_BIT_AND
1130                     ? len : (leftlen > rightlen ? leftlen : rightlen);
1131         Newxz(dc, needlen + 1, char);
1132         sv_usepvn_flags(sv, dc, needlen, SV_HAS_TRAILING_NUL);
1133         dc = SvPVX(sv);         /* sv_usepvn() calls Renew() */
1134     }
1135
1136     if (len >= sizeof(long)*4 &&
1137         !(PTR2nat(dc) % sizeof(long)) &&
1138         !(PTR2nat(lc) % sizeof(long)) &&
1139         !(PTR2nat(rc) % sizeof(long)))  /* It's almost always aligned... */
1140     {
1141         const STRLEN remainder = len % (sizeof(long)*4);
1142         len /= (sizeof(long)*4);
1143
1144         dl = (long*)dc;
1145         ll = (long*)lc;
1146         rl = (long*)rc;
1147
1148         switch (optype) {
1149         case OP_BIT_AND:
1150             while (len--) {
1151                 *dl++ = *ll++ & *rl++;
1152                 *dl++ = *ll++ & *rl++;
1153                 *dl++ = *ll++ & *rl++;
1154                 *dl++ = *ll++ & *rl++;
1155             }
1156             break;
1157         case OP_BIT_XOR:
1158             while (len--) {
1159                 *dl++ = *ll++ ^ *rl++;
1160                 *dl++ = *ll++ ^ *rl++;
1161                 *dl++ = *ll++ ^ *rl++;
1162                 *dl++ = *ll++ ^ *rl++;
1163             }
1164             break;
1165         case OP_BIT_OR:
1166             while (len--) {
1167                 *dl++ = *ll++ | *rl++;
1168                 *dl++ = *ll++ | *rl++;
1169                 *dl++ = *ll++ | *rl++;
1170                 *dl++ = *ll++ | *rl++;
1171             }
1172         }
1173
1174         dc = (char*)dl;
1175         lc = (char*)ll;
1176         rc = (char*)rl;
1177
1178         len = remainder;
1179     }
1180
1181     switch (optype) {
1182     case OP_BIT_AND:
1183         while (len--)
1184             *dc++ = *lc++ & *rc++;
1185         *dc = '\0';
1186         break;
1187     case OP_BIT_XOR:
1188         while (len--)
1189             *dc++ = *lc++ ^ *rc++;
1190         goto mop_up;
1191     case OP_BIT_OR:
1192         while (len--)
1193             *dc++ = *lc++ | *rc++;
1194       mop_up:
1195         len = lensave;
1196         if (rightlen > len) {
1197             if (dc == rc)
1198                 SvCUR_set(sv, rightlen);
1199             else
1200                 sv_catpvn_nomg(sv, rsave + len, rightlen - len);
1201         }
1202         else if (leftlen > len) {
1203             if (dc == lc)
1204                 SvCUR_set(sv, leftlen);
1205             else
1206                 sv_catpvn_nomg(sv, lsave + len, leftlen - len);
1207         }
1208         *SvEND(sv) = '\0';
1209
1210         /* If there is trailing stuff that couldn't be converted from UTF-8, it
1211          * is appended as-is for the ^ and | operators.  This preserves
1212          * backwards compatibility */
1213         if (right_non_downgraded) {
1214             non_downgraded = (char *) right_non_downgraded;
1215             non_downgraded_len = right_non_downgraded_len;
1216         }
1217         else if (left_non_downgraded) {
1218             non_downgraded = (char *) left_non_downgraded;
1219             non_downgraded_len = left_non_downgraded_len;
1220         }
1221
1222         break;
1223     }
1224
1225     if (result_needs_to_be_utf8) {
1226         sv_utf8_upgrade_nomg(sv);
1227
1228         /* Append any trailing UTF-8 as-is. */
1229         if (non_downgraded) {
1230             sv_catpvn_nomg(sv, non_downgraded, non_downgraded_len);
1231         }
1232     }
1233
1234     SvTAINT(sv);
1235 }
1236
1237
1238 /* Perl_do_kv() may be:
1239  *  * called directly as the pp function for pp_keys() and pp_values();
1240  *  * It may also be called directly when the op is OP_AVHVSWITCH, to
1241  *       implement CORE::keys(), CORE::values().
1242  *
1243  * In all cases it expects an HV on the stack and returns a list of keys,
1244  * values, or key-value pairs, depending on PL_op.
1245  */
1246
1247 OP *
1248 Perl_do_kv(pTHX)
1249 {
1250     dSP;
1251     HV * const keys = MUTABLE_HV(POPs);
1252     const U8 gimme = GIMME_V;
1253
1254     const I32 dokeys   =     (PL_op->op_type == OP_KEYS)
1255                           || (    PL_op->op_type == OP_AVHVSWITCH
1256                               && (PL_op->op_private & OPpAVHVSWITCH_MASK)
1257                                     + OP_EACH == OP_KEYS);
1258
1259     const I32 dovalues =     (PL_op->op_type == OP_VALUES)
1260                           || (    PL_op->op_type == OP_AVHVSWITCH
1261                               && (PL_op->op_private & OPpAVHVSWITCH_MASK)
1262                                      + OP_EACH == OP_VALUES);
1263
1264     assert(   PL_op->op_type == OP_KEYS
1265            || PL_op->op_type == OP_VALUES
1266            || PL_op->op_type == OP_AVHVSWITCH);
1267
1268     assert(!(    PL_op->op_type == OP_VALUES
1269              && (PL_op->op_private & OPpMAYBE_LVSUB)));
1270
1271     (void)hv_iterinit(keys);    /* always reset iterator regardless */
1272
1273     if (gimme == G_VOID)
1274         RETURN;
1275
1276     if (gimme == G_SCALAR) {
1277         if (PL_op->op_flags & OPf_MOD || LVRET) {       /* lvalue */
1278             SV * const ret = sv_2mortal(newSV_type(SVt_PVLV));  /* Not TARG RT#67838 */
1279             sv_magic(ret, NULL, PERL_MAGIC_nkeys, NULL, 0);
1280             LvTYPE(ret) = 'k';
1281             LvTARG(ret) = SvREFCNT_inc_simple(keys);
1282             PUSHs(ret);
1283         }
1284         else {
1285             IV i;
1286             dTARGET;
1287
1288             /* note that in 'scalar(keys %h)' the OP_KEYS is usually
1289              * optimised away and the action is performed directly by the
1290              * padhv or rv2hv op. We now only get here via OP_AVHVSWITCH
1291              * and \&CORE::keys
1292              */
1293             if (! SvTIED_mg((const SV *)keys, PERL_MAGIC_tied) ) {
1294                 i = HvUSEDKEYS(keys);
1295             }
1296             else {
1297                 i = 0;
1298                 while (hv_iternext(keys)) i++;
1299             }
1300             PUSHi( i );
1301         }
1302         RETURN;
1303     }
1304
1305     if (UNLIKELY(PL_op->op_private & OPpMAYBE_LVSUB)) {
1306         const I32 flags = is_lvalue_sub();
1307         if (flags && !(flags & OPpENTERSUB_INARGS))
1308             /* diag_listed_as: Can't modify %s in %s */
1309             Perl_croak(aTHX_ "Can't modify keys in list assignment");
1310     }
1311
1312     PUTBACK;
1313     hv_pushkv(keys, (dokeys | (dovalues << 1)));
1314     return NORMAL;
1315 }
1316
1317 /*
1318  * ex: set ts=8 sts=4 sw=4 et:
1319  */