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