This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Document gv_fetch[ps]v and kin
[perl5.git] / utf8.c
1 /*    utf8.c
2  *
3  *    Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
4  *    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  * 'What a fix!' said Sam.  'That's the one place in all the lands we've ever
13  *  heard of that we don't want to see any closer; and that's the one place
14  *  we're trying to get to!  And that's just where we can't get, nohow.'
15  *
16  *     [p.603 of _The Lord of the Rings_, IV/I: "The Taming of Sméagol"]
17  *
18  * 'Well do I understand your speech,' he answered in the same language;
19  * 'yet few strangers do so.  Why then do you not speak in the Common Tongue,
20  *  as is the custom in the West, if you wish to be answered?'
21  *                           --Gandalf, addressing Théoden's door wardens
22  *
23  *     [p.508 of _The Lord of the Rings_, III/vi: "The King of the Golden Hall"]
24  *
25  * ...the travellers perceived that the floor was paved with stones of many
26  * hues; branching runes and strange devices intertwined beneath their feet.
27  *
28  *     [p.512 of _The Lord of the Rings_, III/vi: "The King of the Golden Hall"]
29  */
30
31 #include "EXTERN.h"
32 #define PERL_IN_UTF8_C
33 #include "perl.h"
34 #include "invlist_inline.h"
35
36 static const char malformed_text[] = "Malformed UTF-8 character";
37 static const char unees[] =
38                         "Malformed UTF-8 character (unexpected end of string)";
39
40 /*
41 =head1 Unicode Support
42 These are various utility functions for manipulating UTF8-encoded
43 strings.  For the uninitiated, this is a method of representing arbitrary
44 Unicode characters as a variable number of bytes, in such a way that
45 characters in the ASCII range are unmodified, and a zero byte never appears
46 within non-zero characters.
47
48 =cut
49 */
50
51 /* helper for Perl__force_out_malformed_utf8_message(). Like
52  * SAVECOMPILEWARNINGS(), but works with PL_curcop rather than
53  * PL_compiling */
54
55 static void
56 S_restore_cop_warnings(pTHX_ void *p)
57 {
58     free_and_set_cop_warnings(PL_curcop, (STRLEN*) p);
59 }
60
61
62 void
63 Perl__force_out_malformed_utf8_message(pTHX_
64             const U8 *const p,      /* First byte in UTF-8 sequence */
65             const U8 * const e,     /* Final byte in sequence (may include
66                                        multiple chars */
67             const U32 flags,        /* Flags to pass to utf8n_to_uvchr(),
68                                        usually 0, or some DISALLOW flags */
69             const bool die_here)    /* If TRUE, this function does not return */
70 {
71     /* This core-only function is to be called when a malformed UTF-8 character
72      * is found, in order to output the detailed information about the
73      * malformation before dieing.  The reason it exists is for the occasions
74      * when such a malformation is fatal, but warnings might be turned off, so
75      * that normally they would not be actually output.  This ensures that they
76      * do get output.  Because a sequence may be malformed in more than one
77      * way, multiple messages may be generated, so we can't make them fatal, as
78      * that would cause the first one to die.
79      *
80      * Instead we pretend -W was passed to perl, then die afterwards.  The
81      * flexibility is here to return to the caller so they can finish up and
82      * die themselves */
83     U32 errors;
84
85     PERL_ARGS_ASSERT__FORCE_OUT_MALFORMED_UTF8_MESSAGE;
86
87     ENTER;
88     SAVEI8(PL_dowarn);
89     SAVESPTR(PL_curcop);
90
91     PL_dowarn = G_WARN_ALL_ON|G_WARN_ON;
92     if (PL_curcop) {
93         /* this is like SAVECOMPILEWARNINGS() except with PL_curcop rather
94          * than PL_compiling */
95         SAVEDESTRUCTOR_X(S_restore_cop_warnings,
96                 (void*)PL_curcop->cop_warnings);
97         PL_curcop->cop_warnings = pWARN_ALL;
98     }
99
100     (void) utf8n_to_uvchr_error(p, e - p, NULL, flags & ~UTF8_CHECK_ONLY, &errors);
101
102     LEAVE;
103
104     if (! errors) {
105         Perl_croak(aTHX_ "panic: _force_out_malformed_utf8_message should"
106                          " be called only when there are errors found");
107     }
108
109     if (die_here) {
110         Perl_croak(aTHX_ "Malformed UTF-8 character (fatal)");
111     }
112 }
113
114 STATIC HV *
115 S_new_msg_hv(pTHX_ const char * const message, /* The message text */
116                    U32 categories,  /* Packed warning categories */
117                    U32 flag)        /* Flag associated with this message */
118 {
119     /* Creates, populates, and returns an HV* that describes an error message
120      * for the translators between UTF8 and code point */
121
122     SV* msg_sv = newSVpv(message, 0);
123     SV* category_sv = newSVuv(categories);
124     SV* flag_bit_sv = newSVuv(flag);
125
126     HV* msg_hv = newHV();
127
128     PERL_ARGS_ASSERT_NEW_MSG_HV;
129
130     (void) hv_stores(msg_hv, "text", msg_sv);
131     (void) hv_stores(msg_hv, "warn_categories",  category_sv);
132     (void) hv_stores(msg_hv, "flag_bit", flag_bit_sv);
133
134     return msg_hv;
135 }
136
137 /*
138 =for apidoc uvoffuni_to_utf8_flags
139
140 THIS FUNCTION SHOULD BE USED IN ONLY VERY SPECIALIZED CIRCUMSTANCES.
141 Instead, B<Almost all code should use L<perlapi/uvchr_to_utf8> or
142 L<perlapi/uvchr_to_utf8_flags>>.
143
144 This function is like them, but the input is a strict Unicode
145 (as opposed to native) code point.  Only in very rare circumstances should code
146 not be using the native code point.
147
148 For details, see the description for L<perlapi/uvchr_to_utf8_flags>.
149
150 =cut
151 */
152
153 U8 *
154 Perl_uvoffuni_to_utf8_flags(pTHX_ U8 *d, UV uv, const UV flags)
155 {
156     PERL_ARGS_ASSERT_UVOFFUNI_TO_UTF8_FLAGS;
157
158     return uvoffuni_to_utf8_flags_msgs(d, uv, flags, NULL);
159 }
160
161 /* All these formats take a single UV code point argument */
162 const char surrogate_cp_format[] = "UTF-16 surrogate U+%04" UVXf;
163 const char nonchar_cp_format[]   = "Unicode non-character U+%04" UVXf
164                                    " is not recommended for open interchange";
165 const char super_cp_format[]     = "Code point 0x%" UVXf " is not Unicode,"
166                                    " may not be portable";
167
168 #define HANDLE_UNICODE_SURROGATE(uv, flags, msgs)                   \
169     STMT_START {                                                    \
170         if (flags & UNICODE_WARN_SURROGATE) {                       \
171             U32 category = packWARN(WARN_SURROGATE);                \
172             const char * format = surrogate_cp_format;              \
173             if (msgs) {                                             \
174                 *msgs = new_msg_hv(Perl_form(aTHX_ format, uv),     \
175                                    category,                        \
176                                    UNICODE_GOT_SURROGATE);          \
177             }                                                       \
178             else {                                                  \
179                 Perl_ck_warner_d(aTHX_ category, format, uv);       \
180             }                                                       \
181         }                                                           \
182         if (flags & UNICODE_DISALLOW_SURROGATE) {                   \
183             return NULL;                                            \
184         }                                                           \
185     } STMT_END;
186
187 #define HANDLE_UNICODE_NONCHAR(uv, flags, msgs)                     \
188     STMT_START {                                                    \
189         if (flags & UNICODE_WARN_NONCHAR) {                         \
190             U32 category = packWARN(WARN_NONCHAR);                  \
191             const char * format = nonchar_cp_format;                \
192             if (msgs) {                                             \
193                 *msgs = new_msg_hv(Perl_form(aTHX_ format, uv),     \
194                                    category,                        \
195                                    UNICODE_GOT_NONCHAR);            \
196             }                                                       \
197             else {                                                  \
198                 Perl_ck_warner_d(aTHX_ category, format, uv);       \
199             }                                                       \
200         }                                                           \
201         if (flags & UNICODE_DISALLOW_NONCHAR) {                     \
202             return NULL;                                            \
203         }                                                           \
204     } STMT_END;
205
206 /*  Use shorter names internally in this file */
207 #define SHIFT   UTF_ACCUMULATION_SHIFT
208 #undef  MARK
209 #define MARK    UTF_CONTINUATION_MARK
210 #define MASK    UTF_CONTINUATION_MASK
211
212 /*
213 =for apidoc uvchr_to_utf8_flags_msgs
214
215 THIS FUNCTION SHOULD BE USED IN ONLY VERY SPECIALIZED CIRCUMSTANCES.
216
217 Most code should use C<L</uvchr_to_utf8_flags>()> rather than call this directly.
218
219 This function is for code that wants any warning and/or error messages to be
220 returned to the caller rather than be displayed.  All messages that would have
221 been displayed if all lexical warnings are enabled will be returned.
222
223 It is just like C<L</uvchr_to_utf8_flags>> but it takes an extra parameter
224 placed after all the others, C<msgs>.  If this parameter is 0, this function
225 behaves identically to C<L</uvchr_to_utf8_flags>>.  Otherwise, C<msgs> should
226 be a pointer to an C<HV *> variable, in which this function creates a new HV to
227 contain any appropriate messages.  The hash has three key-value pairs, as
228 follows:
229
230 =over 4
231
232 =item C<text>
233
234 The text of the message as a C<SVpv>.
235
236 =item C<warn_categories>
237
238 The warning category (or categories) packed into a C<SVuv>.
239
240 =item C<flag>
241
242 A single flag bit associated with this message, in a C<SVuv>.
243 The bit corresponds to some bit in the C<*errors> return value,
244 such as C<UNICODE_GOT_SURROGATE>.
245
246 =back
247
248 It's important to note that specifying this parameter as non-null will cause
249 any warnings this function would otherwise generate to be suppressed, and
250 instead be placed in C<*msgs>.  The caller can check the lexical warnings state
251 (or not) when choosing what to do with the returned messages.
252
253 The caller, of course, is responsible for freeing any returned HV.
254
255 =cut
256 */
257
258 /* Undocumented; we don't want people using this.  Instead they should use
259  * uvchr_to_utf8_flags_msgs() */
260 U8 *
261 Perl_uvoffuni_to_utf8_flags_msgs(pTHX_ U8 *d, UV uv, const UV flags, HV** msgs)
262 {
263     PERL_ARGS_ASSERT_UVOFFUNI_TO_UTF8_FLAGS_MSGS;
264
265     if (msgs) {
266         *msgs = NULL;
267     }
268
269     if (OFFUNI_IS_INVARIANT(uv)) {
270         *d++ = LATIN1_TO_NATIVE(uv);
271         return d;
272     }
273
274     if (uv <= MAX_UTF8_TWO_BYTE) {
275         *d++ = I8_TO_NATIVE_UTF8(( uv >> SHIFT) | UTF_START_MARK(2));
276         *d++ = I8_TO_NATIVE_UTF8(( uv           & MASK) |   MARK);
277         return d;
278     }
279
280     /* Not 2-byte; test for and handle 3-byte result.   In the test immediately
281      * below, the 16 is for start bytes E0-EF (which are all the possible ones
282      * for 3 byte characters).  The 2 is for 2 continuation bytes; these each
283      * contribute SHIFT bits.  This yields 0x4000 on EBCDIC platforms, 0x1_0000
284      * on ASCII; so 3 bytes covers the range 0x400-0x3FFF on EBCDIC;
285      * 0x800-0xFFFF on ASCII */
286     if (uv < (16 * (1U << (2 * SHIFT)))) {
287         *d++ = I8_TO_NATIVE_UTF8(( uv >> ((3 - 1) * SHIFT)) | UTF_START_MARK(3));
288         *d++ = I8_TO_NATIVE_UTF8(((uv >> ((2 - 1) * SHIFT)) & MASK) |   MARK);
289         *d++ = I8_TO_NATIVE_UTF8(( uv  /* (1 - 1) */        & MASK) |   MARK);
290
291 #ifndef EBCDIC  /* These problematic code points are 4 bytes on EBCDIC, so
292                    aren't tested here */
293         /* The most likely code points in this range are below the surrogates.
294          * Do an extra test to quickly exclude those. */
295         if (UNLIKELY(uv >= UNICODE_SURROGATE_FIRST)) {
296             if (UNLIKELY(   UNICODE_IS_32_CONTIGUOUS_NONCHARS(uv)
297                          || UNICODE_IS_END_PLANE_NONCHAR_GIVEN_NOT_SUPER(uv)))
298             {
299                 HANDLE_UNICODE_NONCHAR(uv, flags, msgs);
300             }
301             else if (UNLIKELY(UNICODE_IS_SURROGATE(uv))) {
302                 HANDLE_UNICODE_SURROGATE(uv, flags, msgs);
303             }
304         }
305 #endif
306         return d;
307     }
308
309     /* Not 3-byte; that means the code point is at least 0x1_0000 on ASCII
310      * platforms, and 0x4000 on EBCDIC.  There are problematic cases that can
311      * happen starting with 4-byte characters on ASCII platforms.  We unify the
312      * code for these with EBCDIC, even though some of them require 5-bytes on
313      * those, because khw believes the code saving is worth the very slight
314      * performance hit on these high EBCDIC code points. */
315
316     if (UNLIKELY(UNICODE_IS_SUPER(uv))) {
317         if (UNLIKELY(      uv > MAX_LEGAL_CP
318                      && ! (flags & UNICODE_ALLOW_ABOVE_IV_MAX)))
319         {
320             Perl_croak(aTHX_ "%s", form_cp_too_large_msg(16, NULL, 0, uv));
321         }
322         if (       (flags & UNICODE_WARN_SUPER)
323             || (   (flags & UNICODE_WARN_PERL_EXTENDED)
324                 && UNICODE_IS_PERL_EXTENDED(uv)))
325         {
326             const char * format = super_cp_format;
327             U32 category = packWARN(WARN_NON_UNICODE);
328             U32 flag = UNICODE_GOT_SUPER;
329
330             /* Choose the more dire applicable warning */
331             if (UNICODE_IS_PERL_EXTENDED(uv)) {
332                 format = PL_extended_cp_format;
333                 category = packWARN2(WARN_NON_UNICODE, WARN_PORTABLE);
334                 if (flags & (UNICODE_WARN_PERL_EXTENDED
335                             |UNICODE_DISALLOW_PERL_EXTENDED))
336                 {
337                     flag = UNICODE_GOT_PERL_EXTENDED;
338                 }
339             }
340
341             if (msgs) {
342                 *msgs = new_msg_hv(Perl_form(aTHX_ format, uv),
343                                    category, flag);
344             }
345             else if (    ckWARN_d(WARN_NON_UNICODE)
346                      || (   (flag & UNICODE_GOT_PERL_EXTENDED)
347                          && ckWARN(WARN_PORTABLE)))
348             {
349                 Perl_warner(aTHX_ category, format, uv);
350             }
351         }
352         if (       (flags & UNICODE_DISALLOW_SUPER)
353             || (   (flags & UNICODE_DISALLOW_PERL_EXTENDED)
354                 &&  UNICODE_IS_PERL_EXTENDED(uv)))
355         {
356             return NULL;
357         }
358     }
359     else if (UNLIKELY(UNICODE_IS_END_PLANE_NONCHAR_GIVEN_NOT_SUPER(uv))) {
360         HANDLE_UNICODE_NONCHAR(uv, flags, msgs);
361     }
362
363     /* Test for and handle 4-byte result.   In the test immediately below, the
364      * 8 is for start bytes F0-F7 (which are all the possible ones for 4 byte
365      * characters).  The 3 is for 3 continuation bytes; these each contribute
366      * SHIFT bits.  This yields 0x4_0000 on EBCDIC platforms, 0x20_0000 on
367      * ASCII, so 4 bytes covers the range 0x4000-0x3_FFFF on EBCDIC;
368      * 0x1_0000-0x1F_FFFF on ASCII */
369     if (uv < (8 * (1U << (3 * SHIFT)))) {
370         *d++ = I8_TO_NATIVE_UTF8(( uv >> ((4 - 1) * SHIFT)) | UTF_START_MARK(4));
371         *d++ = I8_TO_NATIVE_UTF8(((uv >> ((3 - 1) * SHIFT)) & MASK) |   MARK);
372         *d++ = I8_TO_NATIVE_UTF8(((uv >> ((2 - 1) * SHIFT)) & MASK) |   MARK);
373         *d++ = I8_TO_NATIVE_UTF8(( uv  /* (1 - 1) */        & MASK) |   MARK);
374
375 #ifdef EBCDIC   /* These were handled on ASCII platforms in the code for 3-byte
376                    characters.  The end-plane non-characters for EBCDIC were
377                    handled just above */
378         if (UNLIKELY(UNICODE_IS_32_CONTIGUOUS_NONCHARS(uv))) {
379             HANDLE_UNICODE_NONCHAR(uv, flags, msgs);
380         }
381         else if (UNLIKELY(UNICODE_IS_SURROGATE(uv))) {
382             HANDLE_UNICODE_SURROGATE(uv, flags, msgs);
383         }
384 #endif
385
386         return d;
387     }
388
389     /* Not 4-byte; that means the code point is at least 0x20_0000 on ASCII
390      * platforms, and 0x4000 on EBCDIC.  At this point we switch to a loop
391      * format.  The unrolled version above turns out to not save all that much
392      * time, and at these high code points (well above the legal Unicode range
393      * on ASCII platforms, and well above anything in common use in EBCDIC),
394      * khw believes that less code outweighs slight performance gains. */
395
396     {
397         STRLEN len  = OFFUNISKIP(uv);
398         U8 *p = d+len-1;
399         while (p > d) {
400             *p-- = I8_TO_NATIVE_UTF8((uv & MASK) | MARK);
401             uv >>= SHIFT;
402         }
403         *p = I8_TO_NATIVE_UTF8((uv & UTF_START_MASK(len)) | UTF_START_MARK(len));
404         return d+len;
405     }
406 }
407
408 /*
409 =for apidoc uvchr_to_utf8
410
411 Adds the UTF-8 representation of the native code point C<uv> to the end
412 of the string C<d>; C<d> should have at least C<UVCHR_SKIP(uv)+1> (up to
413 C<UTF8_MAXBYTES+1>) free bytes available.  The return value is the pointer to
414 the byte after the end of the new character.  In other words,
415
416     d = uvchr_to_utf8(d, uv);
417
418 is the recommended wide native character-aware way of saying
419
420     *(d++) = uv;
421
422 This function accepts any code point from 0..C<IV_MAX> as input.
423 C<IV_MAX> is typically 0x7FFF_FFFF in a 32-bit word.
424
425 It is possible to forbid or warn on non-Unicode code points, or those that may
426 be problematic by using L</uvchr_to_utf8_flags>.
427
428 =cut
429 */
430
431 /* This is also a macro */
432 PERL_CALLCONV U8*       Perl_uvchr_to_utf8(pTHX_ U8 *d, UV uv);
433
434 U8 *
435 Perl_uvchr_to_utf8(pTHX_ U8 *d, UV uv)
436 {
437     return uvchr_to_utf8(d, uv);
438 }
439
440 /*
441 =for apidoc uvchr_to_utf8_flags
442
443 Adds the UTF-8 representation of the native code point C<uv> to the end
444 of the string C<d>; C<d> should have at least C<UVCHR_SKIP(uv)+1> (up to
445 C<UTF8_MAXBYTES+1>) free bytes available.  The return value is the pointer to
446 the byte after the end of the new character.  In other words,
447
448     d = uvchr_to_utf8_flags(d, uv, flags);
449
450 or, in most cases,
451
452     d = uvchr_to_utf8_flags(d, uv, 0);
453
454 This is the Unicode-aware way of saying
455
456     *(d++) = uv;
457
458 If C<flags> is 0, this function accepts any code point from 0..C<IV_MAX> as
459 input.  C<IV_MAX> is typically 0x7FFF_FFFF in a 32-bit word.
460
461 Specifying C<flags> can further restrict what is allowed and not warned on, as
462 follows:
463
464 If C<uv> is a Unicode surrogate code point and C<UNICODE_WARN_SURROGATE> is set,
465 the function will raise a warning, provided UTF8 warnings are enabled.  If
466 instead C<UNICODE_DISALLOW_SURROGATE> is set, the function will fail and return
467 NULL.  If both flags are set, the function will both warn and return NULL.
468
469 Similarly, the C<UNICODE_WARN_NONCHAR> and C<UNICODE_DISALLOW_NONCHAR> flags
470 affect how the function handles a Unicode non-character.
471
472 And likewise, the C<UNICODE_WARN_SUPER> and C<UNICODE_DISALLOW_SUPER> flags
473 affect the handling of code points that are above the Unicode maximum of
474 0x10FFFF.  Languages other than Perl may not be able to accept files that
475 contain these.
476
477 The flag C<UNICODE_WARN_ILLEGAL_INTERCHANGE> selects all three of
478 the above WARN flags; and C<UNICODE_DISALLOW_ILLEGAL_INTERCHANGE> selects all
479 three DISALLOW flags.  C<UNICODE_DISALLOW_ILLEGAL_INTERCHANGE> restricts the
480 allowed inputs to the strict UTF-8 traditionally defined by Unicode.
481 Similarly, C<UNICODE_WARN_ILLEGAL_C9_INTERCHANGE> and
482 C<UNICODE_DISALLOW_ILLEGAL_C9_INTERCHANGE> are shortcuts to select the
483 above-Unicode and surrogate flags, but not the non-character ones, as
484 defined in
485 L<Unicode Corrigendum #9|https://www.unicode.org/versions/corrigendum9.html>.
486 See L<perlunicode/Noncharacter code points>.
487
488 Extremely high code points were never specified in any standard, and require an
489 extension to UTF-8 to express, which Perl does.  It is likely that programs
490 written in something other than Perl would not be able to read files that
491 contain these; nor would Perl understand files written by something that uses a
492 different extension.  For these reasons, there is a separate set of flags that
493 can warn and/or disallow these extremely high code points, even if other
494 above-Unicode ones are accepted.  They are the C<UNICODE_WARN_PERL_EXTENDED>
495 and C<UNICODE_DISALLOW_PERL_EXTENDED> flags.  For more information see
496 C<L</UTF8_GOT_PERL_EXTENDED>>.  Of course C<UNICODE_DISALLOW_SUPER> will
497 treat all above-Unicode code points, including these, as malformations.  (Note
498 that the Unicode standard considers anything above 0x10FFFF to be illegal, but
499 there are standards predating it that allow up to 0x7FFF_FFFF (2**31 -1))
500
501 A somewhat misleadingly named synonym for C<UNICODE_WARN_PERL_EXTENDED> is
502 retained for backward compatibility: C<UNICODE_WARN_ABOVE_31_BIT>.  Similarly,
503 C<UNICODE_DISALLOW_ABOVE_31_BIT> is usable instead of the more accurately named
504 C<UNICODE_DISALLOW_PERL_EXTENDED>.  The names are misleading because on EBCDIC
505 platforms,these flags can apply to code points that actually do fit in 31 bits.
506 The new names accurately describe the situation in all cases.
507
508 =cut
509 */
510
511 /* This is also a macro */
512 PERL_CALLCONV U8*       Perl_uvchr_to_utf8_flags(pTHX_ U8 *d, UV uv, UV flags);
513
514 U8 *
515 Perl_uvchr_to_utf8_flags(pTHX_ U8 *d, UV uv, UV flags)
516 {
517     return uvchr_to_utf8_flags(d, uv, flags);
518 }
519
520 #ifndef UV_IS_QUAD
521
522 STATIC int
523 S_is_utf8_cp_above_31_bits(const U8 * const s,
524                            const U8 * const e,
525                            const bool consider_overlongs)
526 {
527     /* Returns TRUE if the first code point represented by the Perl-extended-
528      * UTF-8-encoded string starting at 's', and looking no further than 'e -
529      * 1' doesn't fit into 31 bytes.  That is, that if it is >= 2**31.
530      *
531      * The function handles the case where the input bytes do not include all
532      * the ones necessary to represent a full character.  That is, they may be
533      * the intial bytes of the representation of a code point, but possibly
534      * the final ones necessary for the complete representation may be beyond
535      * 'e - 1'.
536      *
537      * The function also can handle the case where the input is an overlong
538      * sequence.  If 'consider_overlongs' is 0, the function assumes the
539      * input is not overlong, without checking, and will return based on that
540      * assumption.  If this parameter is 1, the function will go to the trouble
541      * of figuring out if it actually evaluates to above or below 31 bits.
542      *
543      * The sequence is otherwise assumed to be well-formed, without checking.
544      */
545
546     const STRLEN len = e - s;
547     int is_overlong;
548
549     PERL_ARGS_ASSERT_IS_UTF8_CP_ABOVE_31_BITS;
550
551     assert(! UTF8_IS_INVARIANT(*s) && e > s);
552
553 #ifdef EBCDIC
554
555     PERL_UNUSED_ARG(consider_overlongs);
556
557     /* On the EBCDIC code pages we handle, only the native start byte 0xFE can
558      * mean a 32-bit or larger code point (0xFF is an invariant).  0xFE can
559      * also be the start byte for a 31-bit code point; we need at least 2
560      * bytes, and maybe up through 8 bytes, to determine that.  (It can also be
561      * the start byte for an overlong sequence, but for 30-bit or smaller code
562      * points, so we don't have to worry about overlongs on EBCDIC.) */
563     if (*s != 0xFE) {
564         return 0;
565     }
566
567     if (len == 1) {
568         return -1;
569     }
570
571 #else
572
573     /* On ASCII, FE and FF are the only start bytes that can evaluate to
574      * needing more than 31 bits. */
575     if (LIKELY(*s < 0xFE)) {
576         return 0;
577     }
578
579     /* What we have left are FE and FF.  Both of these require more than 31
580      * bits unless they are for overlongs. */
581     if (! consider_overlongs) {
582         return 1;
583     }
584
585     /* Here, we have FE or FF.  If the input isn't overlong, it evaluates to
586      * above 31 bits.  But we need more than one byte to discern this, so if
587      * passed just the start byte, it could be an overlong evaluating to
588      * smaller */
589     if (len == 1) {
590         return -1;
591     }
592
593     /* Having excluded len==1, and knowing that FE and FF are both valid start
594      * bytes, we can call the function below to see if the sequence is
595      * overlong.  (We don't need the full generality of the called function,
596      * but for these huge code points, speed shouldn't be a consideration, and
597      * the compiler does have enough information, since it's static to this
598      * file, to optimize to just the needed parts.) */
599     is_overlong = is_utf8_overlong_given_start_byte_ok(s, len);
600
601     /* If it isn't overlong, more than 31 bits are required. */
602     if (is_overlong == 0) {
603         return 1;
604     }
605
606     /* If it is indeterminate if it is overlong, return that */
607     if (is_overlong < 0) {
608         return -1;
609     }
610
611     /* Here is overlong.  Such a sequence starting with FE is below 31 bits, as
612      * the max it can be is 2**31 - 1 */
613     if (*s == 0xFE) {
614         return 0;
615     }
616
617 #endif
618
619     /* Here, ASCII and EBCDIC rejoin:
620     *  On ASCII:   We have an overlong sequence starting with FF
621     *  On EBCDIC:  We have a sequence starting with FE. */
622
623     {   /* For C89, use a block so the declaration can be close to its use */
624
625 #ifdef EBCDIC
626
627         /* U+7FFFFFFF (2 ** 31 - 1)
628          *              [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] 10  11  12  13
629          *   IBM-1047: \xFE\x41\x41\x41\x41\x41\x41\x42\x73\x73\x73\x73\x73\x73
630          *    IBM-037: \xFE\x41\x41\x41\x41\x41\x41\x42\x72\x72\x72\x72\x72\x72
631          *   POSIX-BC: \xFE\x41\x41\x41\x41\x41\x41\x42\x75\x75\x75\x75\x75\x75
632          *         I8: \xFF\xA0\xA0\xA0\xA0\xA0\xA0\xA1\xBF\xBF\xBF\xBF\xBF\xBF
633          * U+80000000 (2 ** 31):
634          *   IBM-1047: \xFE\x41\x41\x41\x41\x41\x41\x43\x41\x41\x41\x41\x41\x41
635          *    IBM-037: \xFE\x41\x41\x41\x41\x41\x41\x43\x41\x41\x41\x41\x41\x41
636          *   POSIX-BC: \xFE\x41\x41\x41\x41\x41\x41\x43\x41\x41\x41\x41\x41\x41
637          *         I8: \xFF\xA0\xA0\xA0\xA0\xA0\xA0\xA2\xA0\xA0\xA0\xA0\xA0\xA0
638          *
639          * and since we know that *s = \xfe, any continuation sequcence
640          * following it that is gt the below is above 31 bits
641                                                 [0] [1] [2] [3] [4] [5] [6] */
642         const U8 conts_for_highest_30_bit[] = "\x41\x41\x41\x41\x41\x41\x42";
643
644 #else
645
646         /* FF overlong for U+7FFFFFFF (2 ** 31 - 1)
647          *      ASCII: \xFF\x80\x80\x80\x80\x80\x80\x81\xBF\xBF\xBF\xBF\xBF
648          * FF overlong for U+80000000 (2 ** 31):
649          *      ASCII: \xFF\x80\x80\x80\x80\x80\x80\x82\x80\x80\x80\x80\x80
650          * and since we know that *s = \xff, any continuation sequcence
651          * following it that is gt the below is above 30 bits
652                                                 [0] [1] [2] [3] [4] [5] [6] */
653         const U8 conts_for_highest_30_bit[] = "\x80\x80\x80\x80\x80\x80\x81";
654
655
656 #endif
657         const STRLEN conts_len = sizeof(conts_for_highest_30_bit) - 1;
658         const STRLEN cmp_len = MIN(conts_len, len - 1);
659
660         /* Now compare the continuation bytes in s with the ones we have
661          * compiled in that are for the largest 30 bit code point.  If we have
662          * enough bytes available to determine the answer, or the bytes we do
663          * have differ from them, we can compare the two to get a definitive
664          * answer (Note that in UTF-EBCDIC, the two lowest possible
665          * continuation bytes are \x41 and \x42.) */
666         if (cmp_len >= conts_len || memNE(s + 1,
667                                           conts_for_highest_30_bit,
668                                           cmp_len))
669         {
670             return cBOOL(memGT(s + 1, conts_for_highest_30_bit, cmp_len));
671         }
672
673         /* Here, all the bytes we have are the same as the highest 30-bit code
674          * point, but we are missing so many bytes that we can't make the
675          * determination */
676         return -1;
677     }
678 }
679
680 #endif
681
682 PERL_STATIC_INLINE int
683 S_is_utf8_overlong_given_start_byte_ok(const U8 * const s, const STRLEN len)
684 {
685     /* Returns an int indicating whether or not the UTF-8 sequence from 's' to
686      * 's' + 'len' - 1 is an overlong.  It returns 1 if it is an overlong; 0 if
687      * it isn't, and -1 if there isn't enough information to tell.  This last
688      * return value can happen if the sequence is incomplete, missing some
689      * trailing bytes that would form a complete character.  If there are
690      * enough bytes to make a definitive decision, this function does so.
691      * Usually 2 bytes sufficient.
692      *
693      * Overlongs can occur whenever the number of continuation bytes changes.
694      * That means whenever the number of leading 1 bits in a start byte
695      * increases from the next lower start byte.  That happens for start bytes
696      * C0, E0, F0, F8, FC, FE, and FF.  On modern perls, the following illegal
697      * start bytes have already been excluded, so don't need to be tested here;
698      * ASCII platforms: C0, C1
699      * EBCDIC platforms C0, C1, C2, C3, C4, E0
700      */
701
702     const U8 s0 = NATIVE_UTF8_TO_I8(s[0]);
703     const U8 s1 = NATIVE_UTF8_TO_I8(s[1]);
704
705     PERL_ARGS_ASSERT_IS_UTF8_OVERLONG_GIVEN_START_BYTE_OK;
706     assert(len > 1 && UTF8_IS_START(*s));
707
708     /* Each platform has overlongs after the start bytes given above (expressed
709      * in I8 for EBCDIC).  What constitutes an overlong varies by platform, but
710      * the logic is the same, except the E0 overlong has already been excluded
711      * on EBCDIC platforms.   The  values below were found by manually
712      * inspecting the UTF-8 patterns.  See the tables in utf8.h and
713      * utfebcdic.h. */
714
715 #       ifdef EBCDIC
716 #           define F0_ABOVE_OVERLONG 0xB0
717 #           define F8_ABOVE_OVERLONG 0xA8
718 #           define FC_ABOVE_OVERLONG 0xA4
719 #           define FE_ABOVE_OVERLONG 0xA2
720 #           define FF_OVERLONG_PREFIX "\xfe\x41\x41\x41\x41\x41\x41\x41"
721                                     /* I8(0xfe) is FF */
722 #       else
723
724     if (s0 == 0xE0 && UNLIKELY(s1 < 0xA0)) {
725         return 1;
726     }
727
728 #           define F0_ABOVE_OVERLONG 0x90
729 #           define F8_ABOVE_OVERLONG 0x88
730 #           define FC_ABOVE_OVERLONG 0x84
731 #           define FE_ABOVE_OVERLONG 0x82
732 #           define FF_OVERLONG_PREFIX "\xff\x80\x80\x80\x80\x80\x80"
733 #       endif
734
735
736     if (   (s0 == 0xF0 && UNLIKELY(s1 < F0_ABOVE_OVERLONG))
737         || (s0 == 0xF8 && UNLIKELY(s1 < F8_ABOVE_OVERLONG))
738         || (s0 == 0xFC && UNLIKELY(s1 < FC_ABOVE_OVERLONG))
739         || (s0 == 0xFE && UNLIKELY(s1 < FE_ABOVE_OVERLONG)))
740     {
741         return 1;
742     }
743
744     /* Check for the FF overlong */
745     return isFF_OVERLONG(s, len);
746 }
747
748 PERL_STATIC_INLINE int
749 S_isFF_OVERLONG(const U8 * const s, const STRLEN len)
750 {
751     /* Returns an int indicating whether or not the UTF-8 sequence from 's' to
752      * 'e' - 1 is an overlong beginning with \xFF.  It returns 1 if it is; 0 if
753      * it isn't, and -1 if there isn't enough information to tell.  This last
754      * return value can happen if the sequence is incomplete, missing some
755      * trailing bytes that would form a complete character.  If there are
756      * enough bytes to make a definitive decision, this function does so. */
757
758     PERL_ARGS_ASSERT_ISFF_OVERLONG;
759
760     /* To be an FF overlong, all the available bytes must match */
761     if (LIKELY(memNE(s, FF_OVERLONG_PREFIX,
762                      MIN(len, sizeof(FF_OVERLONG_PREFIX) - 1))))
763     {
764         return 0;
765     }
766
767     /* To be an FF overlong sequence, all the bytes in FF_OVERLONG_PREFIX must
768      * be there; what comes after them doesn't matter.  See tables in utf8.h,
769      * utfebcdic.h. */
770     if (len >= sizeof(FF_OVERLONG_PREFIX) - 1) {
771         return 1;
772     }
773
774     /* The missing bytes could cause the result to go one way or the other, so
775      * the result is indeterminate */
776     return -1;
777 }
778
779 #if defined(UV_IS_QUAD) /* These assume IV_MAX is 2**63-1 */
780 #  ifdef EBCDIC     /* Actually is I8 */
781 #   define HIGHEST_REPRESENTABLE_UTF8                                       \
782                 "\xFF\xA7\xBF\xBF\xBF\xBF\xBF\xBF\xBF\xBF\xBF\xBF\xBF\xBF"
783 #  else
784 #   define HIGHEST_REPRESENTABLE_UTF8                                       \
785                 "\xFF\x80\x87\xBF\xBF\xBF\xBF\xBF\xBF\xBF\xBF\xBF\xBF"
786 #  endif
787 #endif
788
789 PERL_STATIC_INLINE int
790 S_does_utf8_overflow(const U8 * const s,
791                      const U8 * e,
792                      const bool consider_overlongs)
793 {
794     /* Returns an int indicating whether or not the UTF-8 sequence from 's' to
795      * 'e' - 1 would overflow an IV on this platform; that is if it represents
796      * a code point larger than the highest representable code point.  It
797      * returns 1 if it does overflow; 0 if it doesn't, and -1 if there isn't
798      * enough information to tell.  This last return value can happen if the
799      * sequence is incomplete, missing some trailing bytes that would form a
800      * complete character.  If there are enough bytes to make a definitive
801      * decision, this function does so.
802      *
803      * If 'consider_overlongs' is TRUE, the function checks for the possibility
804      * that the sequence is an overlong that doesn't overflow.  Otherwise, it
805      * assumes the sequence is not an overlong.  This can give different
806      * results only on ASCII 32-bit platforms.
807      *
808      * (For ASCII platforms, we could use memcmp() because we don't have to
809      * convert each byte to I8, but it's very rare input indeed that would
810      * approach overflow, so the loop below will likely only get executed once.)
811      *
812      * 'e' - 1 must not be beyond a full character. */
813
814
815     PERL_ARGS_ASSERT_DOES_UTF8_OVERFLOW;
816     assert(s <= e && s + UTF8SKIP(s) >= e);
817
818 #if ! defined(UV_IS_QUAD)
819
820     return is_utf8_cp_above_31_bits(s, e, consider_overlongs);
821
822 #else
823
824     PERL_UNUSED_ARG(consider_overlongs);
825
826     {
827         const STRLEN len = e - s;
828         const U8 *x;
829         const U8 * y = (const U8 *) HIGHEST_REPRESENTABLE_UTF8;
830
831         for (x = s; x < e; x++, y++) {
832
833             if (UNLIKELY(NATIVE_UTF8_TO_I8(*x) == *y)) {
834                 continue;
835             }
836
837             /* If this byte is larger than the corresponding highest UTF-8
838              * byte, the sequence overflow; otherwise the byte is less than,
839              * and so the sequence doesn't overflow */
840             return NATIVE_UTF8_TO_I8(*x) > *y;
841
842         }
843
844         /* Got to the end and all bytes are the same.  If the input is a whole
845          * character, it doesn't overflow.  And if it is a partial character,
846          * there's not enough information to tell */
847         if (len < sizeof(HIGHEST_REPRESENTABLE_UTF8) - 1) {
848             return -1;
849         }
850
851         return 0;
852     }
853
854 #endif
855
856 }
857
858 #if 0
859
860 /* This is the portions of the above function that deal with UV_MAX instead of
861  * IV_MAX.  They are left here in case we want to combine them so that internal
862  * uses can have larger code points.  The only logic difference is that the
863  * 32-bit EBCDIC platform is treate like the 64-bit, and the 32-bit ASCII has
864  * different logic.
865  */
866
867 /* Anything larger than this will overflow the word if it were converted into a UV */
868 #if defined(UV_IS_QUAD)
869 #  ifdef EBCDIC     /* Actually is I8 */
870 #   define HIGHEST_REPRESENTABLE_UTF8                                       \
871                 "\xFF\xAF\xBF\xBF\xBF\xBF\xBF\xBF\xBF\xBF\xBF\xBF\xBF\xBF"
872 #  else
873 #   define HIGHEST_REPRESENTABLE_UTF8                                       \
874                 "\xFF\x80\x8F\xBF\xBF\xBF\xBF\xBF\xBF\xBF\xBF\xBF\xBF"
875 #  endif
876 #else   /* 32-bit */
877 #  ifdef EBCDIC
878 #   define HIGHEST_REPRESENTABLE_UTF8                                       \
879                 "\xFF\xA0\xA0\xA0\xA0\xA0\xA0\xA3\xBF\xBF\xBF\xBF\xBF\xBF"
880 #  else
881 #   define HIGHEST_REPRESENTABLE_UTF8  "\xFE\x83\xBF\xBF\xBF\xBF\xBF"
882 #  endif
883 #endif
884
885 #if ! defined(UV_IS_QUAD) && ! defined(EBCDIC)
886
887     /* On 32 bit ASCII machines, many overlongs that start with FF don't
888      * overflow */
889     if (consider_overlongs && isFF_OVERLONG(s, len) > 0) {
890
891         /* To be such an overlong, the first bytes of 's' must match
892          * FF_OVERLONG_PREFIX, which is "\xff\x80\x80\x80\x80\x80\x80".  If we
893          * don't have any additional bytes available, the sequence, when
894          * completed might or might not fit in 32 bits.  But if we have that
895          * next byte, we can tell for sure.  If it is <= 0x83, then it does
896          * fit. */
897         if (len <= sizeof(FF_OVERLONG_PREFIX) - 1) {
898             return -1;
899         }
900
901         return s[sizeof(FF_OVERLONG_PREFIX) - 1] > 0x83;
902     }
903
904 /* Starting with the #else, the rest of the function is identical except
905  *      1.  we need to move the 'len' declaration to be global to the function
906  *      2.  the endif move to just after the UNUSED_ARG.
907  * An empty endif is given just below to satisfy the preprocessor
908  */
909 #endif
910
911 #endif
912
913 #undef F0_ABOVE_OVERLONG
914 #undef F8_ABOVE_OVERLONG
915 #undef FC_ABOVE_OVERLONG
916 #undef FE_ABOVE_OVERLONG
917 #undef FF_OVERLONG_PREFIX
918
919 STRLEN
920 Perl_is_utf8_char_helper(const U8 * const s, const U8 * e, const U32 flags)
921 {
922     STRLEN len;
923     const U8 *x;
924
925     /* A helper function that should not be called directly.
926      *
927      * This function returns non-zero if the string beginning at 's' and
928      * looking no further than 'e - 1' is well-formed Perl-extended-UTF-8 for a
929      * code point; otherwise it returns 0.  The examination stops after the
930      * first code point in 's' is validated, not looking at the rest of the
931      * input.  If 'e' is such that there are not enough bytes to represent a
932      * complete code point, this function will return non-zero anyway, if the
933      * bytes it does have are well-formed UTF-8 as far as they go, and aren't
934      * excluded by 'flags'.
935      *
936      * A non-zero return gives the number of bytes required to represent the
937      * code point.  Be aware that if the input is for a partial character, the
938      * return will be larger than 'e - s'.
939      *
940      * This function assumes that the code point represented is UTF-8 variant.
941      * The caller should have excluded the possibility of it being invariant
942      * before calling this function.
943      *
944      * 'flags' can be 0, or any combination of the UTF8_DISALLOW_foo flags
945      * accepted by L</utf8n_to_uvchr>.  If non-zero, this function will return
946      * 0 if the code point represented is well-formed Perl-extended-UTF-8, but
947      * disallowed by the flags.  If the input is only for a partial character,
948      * the function will return non-zero if there is any sequence of
949      * well-formed UTF-8 that, when appended to the input sequence, could
950      * result in an allowed code point; otherwise it returns 0.  Non characters
951      * cannot be determined based on partial character input.  But many  of the
952      * other excluded types can be determined with just the first one or two
953      * bytes.
954      *
955      */
956
957     PERL_ARGS_ASSERT_IS_UTF8_CHAR_HELPER;
958
959     assert(0 == (flags & ~(UTF8_DISALLOW_ILLEGAL_INTERCHANGE
960                           |UTF8_DISALLOW_PERL_EXTENDED)));
961     assert(! UTF8_IS_INVARIANT(*s));
962
963     /* A variant char must begin with a start byte */
964     if (UNLIKELY(! UTF8_IS_START(*s))) {
965         return 0;
966     }
967
968     /* Examine a maximum of a single whole code point */
969     if (e - s > UTF8SKIP(s)) {
970         e = s + UTF8SKIP(s);
971     }
972
973     len = e - s;
974
975     if (flags && isUTF8_POSSIBLY_PROBLEMATIC(*s)) {
976         const U8 s0 = NATIVE_UTF8_TO_I8(s[0]);
977
978         /* Here, we are disallowing some set of largish code points, and the
979          * first byte indicates the sequence is for a code point that could be
980          * in the excluded set.  We generally don't have to look beyond this or
981          * the second byte to see if the sequence is actually for one of the
982          * excluded classes.  The code below is derived from this table:
983          *
984          *              UTF-8            UTF-EBCDIC I8
985          *   U+D800: \xED\xA0\x80      \xF1\xB6\xA0\xA0      First surrogate
986          *   U+DFFF: \xED\xBF\xBF      \xF1\xB7\xBF\xBF      Final surrogate
987          * U+110000: \xF4\x90\x80\x80  \xF9\xA2\xA0\xA0\xA0  First above Unicode
988          *
989          * Keep in mind that legal continuation bytes range between \x80..\xBF
990          * for UTF-8, and \xA0..\xBF for I8.  Anything above those aren't
991          * continuation bytes.  Hence, we don't have to test the upper edge
992          * because if any of those is encountered, the sequence is malformed,
993          * and would fail elsewhere in this function.
994          *
995          * The code here likewise assumes that there aren't other
996          * malformations; again the function should fail elsewhere because of
997          * these.  For example, an overlong beginning with FC doesn't actually
998          * have to be a super; it could actually represent a small code point,
999          * even U+0000.  But, since overlongs (and other malformations) are
1000          * illegal, the function should return FALSE in either case.
1001          */
1002
1003 #ifdef EBCDIC   /* On EBCDIC, these are actually I8 bytes */
1004 #  define FIRST_START_BYTE_THAT_IS_DEFINITELY_SUPER  0xFA
1005 #  define IS_UTF8_2_BYTE_SUPER(s0, s1)           ((s0) == 0xF9 && (s1) >= 0xA2)
1006
1007 #  define IS_UTF8_2_BYTE_SURROGATE(s0, s1)       ((s0) == 0xF1              \
1008                                                        /* B6 and B7 */      \
1009                                               && ((s1) & 0xFE ) == 0xB6)
1010 #  define isUTF8_PERL_EXTENDED(s)   (*s == I8_TO_NATIVE_UTF8(0xFF))
1011 #else
1012 #  define FIRST_START_BYTE_THAT_IS_DEFINITELY_SUPER  0xF5
1013 #  define IS_UTF8_2_BYTE_SUPER(s0, s1)           ((s0) == 0xF4 && (s1) >= 0x90)
1014 #  define IS_UTF8_2_BYTE_SURROGATE(s0, s1)       ((s0) == 0xED && (s1) >= 0xA0)
1015 #  define isUTF8_PERL_EXTENDED(s)   (*s >= 0xFE)
1016 #endif
1017
1018         if (  (flags & UTF8_DISALLOW_SUPER)
1019             && UNLIKELY(s0 >= FIRST_START_BYTE_THAT_IS_DEFINITELY_SUPER))
1020         {
1021             return 0;           /* Above Unicode */
1022         }
1023
1024         if (   (flags & UTF8_DISALLOW_PERL_EXTENDED)
1025             &&  UNLIKELY(isUTF8_PERL_EXTENDED(s)))
1026         {
1027             return 0;
1028         }
1029
1030         if (len > 1) {
1031             const U8 s1 = NATIVE_UTF8_TO_I8(s[1]);
1032
1033             if (   (flags & UTF8_DISALLOW_SUPER)
1034                 &&  UNLIKELY(IS_UTF8_2_BYTE_SUPER(s0, s1)))
1035             {
1036                 return 0;       /* Above Unicode */
1037             }
1038
1039             if (   (flags & UTF8_DISALLOW_SURROGATE)
1040                 &&  UNLIKELY(IS_UTF8_2_BYTE_SURROGATE(s0, s1)))
1041             {
1042                 return 0;       /* Surrogate */
1043             }
1044
1045             if (  (flags & UTF8_DISALLOW_NONCHAR)
1046                 && UNLIKELY(UTF8_IS_NONCHAR(s, e)))
1047             {
1048                 return 0;       /* Noncharacter code point */
1049             }
1050         }
1051     }
1052
1053     /* Make sure that all that follows are continuation bytes */
1054     for (x = s + 1; x < e; x++) {
1055         if (UNLIKELY(! UTF8_IS_CONTINUATION(*x))) {
1056             return 0;
1057         }
1058     }
1059
1060     /* Here is syntactically valid.  Next, make sure this isn't the start of an
1061      * overlong. */
1062     if (len > 1 && is_utf8_overlong_given_start_byte_ok(s, len) > 0) {
1063         return 0;
1064     }
1065
1066     /* And finally, that the code point represented fits in a word on this
1067      * platform */
1068     if (0 < does_utf8_overflow(s, e,
1069                                0 /* Don't consider overlongs */
1070                               ))
1071     {
1072         return 0;
1073     }
1074
1075     return UTF8SKIP(s);
1076 }
1077
1078 char *
1079 Perl__byte_dump_string(pTHX_ const U8 * const start, const STRLEN len, const bool format)
1080 {
1081     /* Returns a mortalized C string that is a displayable copy of the 'len'
1082      * bytes starting at 'start'.  'format' gives how to display each byte.
1083      * Currently, there are only two formats, so it is currently a bool:
1084      *      0   \xab
1085      *      1    ab         (that is a space between two hex digit bytes)
1086      */
1087
1088     const STRLEN output_len = 4 * len + 1;  /* 4 bytes per each input, plus a
1089                                                trailing NUL */
1090     const U8 * s = start;
1091     const U8 * const e = start + len;
1092     char * output;
1093     char * d;
1094
1095     PERL_ARGS_ASSERT__BYTE_DUMP_STRING;
1096
1097     Newx(output, output_len, char);
1098     SAVEFREEPV(output);
1099
1100     d = output;
1101     for (s = start; s < e; s++) {
1102         const unsigned high_nibble = (*s & 0xF0) >> 4;
1103         const unsigned low_nibble =  (*s & 0x0F);
1104
1105         if (format) {
1106             if (s > start) {
1107                 *d++ = ' ';
1108             }
1109         }
1110         else {
1111             *d++ = '\\';
1112             *d++ = 'x';
1113         }
1114
1115         if (high_nibble < 10) {
1116             *d++ = high_nibble + '0';
1117         }
1118         else {
1119             *d++ = high_nibble - 10 + 'a';
1120         }
1121
1122         if (low_nibble < 10) {
1123             *d++ = low_nibble + '0';
1124         }
1125         else {
1126             *d++ = low_nibble - 10 + 'a';
1127         }
1128     }
1129
1130     *d = '\0';
1131     return output;
1132 }
1133
1134 PERL_STATIC_INLINE char *
1135 S_unexpected_non_continuation_text(pTHX_ const U8 * const s,
1136
1137                                          /* Max number of bytes to print */
1138                                          STRLEN print_len,
1139
1140                                          /* Which one is the non-continuation */
1141                                          const STRLEN non_cont_byte_pos,
1142
1143                                          /* How many bytes should there be? */
1144                                          const STRLEN expect_len)
1145 {
1146     /* Return the malformation warning text for an unexpected continuation
1147      * byte. */
1148
1149     const char * const where = (non_cont_byte_pos == 1)
1150                                ? "immediately"
1151                                : Perl_form(aTHX_ "%d bytes",
1152                                                  (int) non_cont_byte_pos);
1153     const U8 * x = s + non_cont_byte_pos;
1154     const U8 * e = s + print_len;
1155
1156     PERL_ARGS_ASSERT_UNEXPECTED_NON_CONTINUATION_TEXT;
1157
1158     /* We don't need to pass this parameter, but since it has already been
1159      * calculated, it's likely faster to pass it; verify under DEBUGGING */
1160     assert(expect_len == UTF8SKIP(s));
1161
1162     /* As a defensive coding measure, don't output anything past a NUL.  Such
1163      * bytes shouldn't be in the middle of a malformation, and could mark the
1164      * end of the allocated string, and what comes after is undefined */
1165     for (; x < e; x++) {
1166         if (*x == '\0') {
1167             x++;            /* Output this particular NUL */
1168             break;
1169         }
1170     }
1171
1172     return Perl_form(aTHX_ "%s: %s (unexpected non-continuation byte 0x%02x,"
1173                            " %s after start byte 0x%02x; need %d bytes, got %d)",
1174                            malformed_text,
1175                            _byte_dump_string(s, x - s, 0),
1176                            *(s + non_cont_byte_pos),
1177                            where,
1178                            *s,
1179                            (int) expect_len,
1180                            (int) non_cont_byte_pos);
1181 }
1182
1183 /*
1184
1185 =for apidoc utf8n_to_uvchr
1186
1187 THIS FUNCTION SHOULD BE USED IN ONLY VERY SPECIALIZED CIRCUMSTANCES.
1188 Most code should use L</utf8_to_uvchr_buf>() rather than call this
1189 directly.
1190
1191 Bottom level UTF-8 decode routine.
1192 Returns the native code point value of the first character in the string C<s>,
1193 which is assumed to be in UTF-8 (or UTF-EBCDIC) encoding, and no longer than
1194 C<curlen> bytes; C<*retlen> (if C<retlen> isn't NULL) will be set to
1195 the length, in bytes, of that character.
1196
1197 The value of C<flags> determines the behavior when C<s> does not point to a
1198 well-formed UTF-8 character.  If C<flags> is 0, encountering a malformation
1199 causes zero to be returned and C<*retlen> is set so that (S<C<s> + C<*retlen>>)
1200 is the next possible position in C<s> that could begin a non-malformed
1201 character.  Also, if UTF-8 warnings haven't been lexically disabled, a warning
1202 is raised.  Some UTF-8 input sequences may contain multiple malformations.
1203 This function tries to find every possible one in each call, so multiple
1204 warnings can be raised for the same sequence.
1205
1206 Various ALLOW flags can be set in C<flags> to allow (and not warn on)
1207 individual types of malformations, such as the sequence being overlong (that
1208 is, when there is a shorter sequence that can express the same code point;
1209 overlong sequences are expressly forbidden in the UTF-8 standard due to
1210 potential security issues).  Another malformation example is the first byte of
1211 a character not being a legal first byte.  See F<utf8.h> for the list of such
1212 flags.  Even if allowed, this function generally returns the Unicode
1213 REPLACEMENT CHARACTER when it encounters a malformation.  There are flags in
1214 F<utf8.h> to override this behavior for the overlong malformations, but don't
1215 do that except for very specialized purposes.
1216
1217 The C<UTF8_CHECK_ONLY> flag overrides the behavior when a non-allowed (by other
1218 flags) malformation is found.  If this flag is set, the routine assumes that
1219 the caller will raise a warning, and this function will silently just set
1220 C<retlen> to C<-1> (cast to C<STRLEN>) and return zero.
1221
1222 Note that this API requires disambiguation between successful decoding a C<NUL>
1223 character, and an error return (unless the C<UTF8_CHECK_ONLY> flag is set), as
1224 in both cases, 0 is returned, and, depending on the malformation, C<retlen> may
1225 be set to 1.  To disambiguate, upon a zero return, see if the first byte of
1226 C<s> is 0 as well.  If so, the input was a C<NUL>; if not, the input had an
1227 error.  Or you can use C<L</utf8n_to_uvchr_error>>.
1228
1229 Certain code points are considered problematic.  These are Unicode surrogates,
1230 Unicode non-characters, and code points above the Unicode maximum of 0x10FFFF.
1231 By default these are considered regular code points, but certain situations
1232 warrant special handling for them, which can be specified using the C<flags>
1233 parameter.  If C<flags> contains C<UTF8_DISALLOW_ILLEGAL_INTERCHANGE>, all
1234 three classes are treated as malformations and handled as such.  The flags
1235 C<UTF8_DISALLOW_SURROGATE>, C<UTF8_DISALLOW_NONCHAR>, and
1236 C<UTF8_DISALLOW_SUPER> (meaning above the legal Unicode maximum) can be set to
1237 disallow these categories individually.  C<UTF8_DISALLOW_ILLEGAL_INTERCHANGE>
1238 restricts the allowed inputs to the strict UTF-8 traditionally defined by
1239 Unicode.  Use C<UTF8_DISALLOW_ILLEGAL_C9_INTERCHANGE> to use the strictness
1240 definition given by
1241 L<Unicode Corrigendum #9|https://www.unicode.org/versions/corrigendum9.html>.
1242 The difference between traditional strictness and C9 strictness is that the
1243 latter does not forbid non-character code points.  (They are still discouraged,
1244 however.)  For more discussion see L<perlunicode/Noncharacter code points>.
1245
1246 The flags C<UTF8_WARN_ILLEGAL_INTERCHANGE>,
1247 C<UTF8_WARN_ILLEGAL_C9_INTERCHANGE>, C<UTF8_WARN_SURROGATE>,
1248 C<UTF8_WARN_NONCHAR>, and C<UTF8_WARN_SUPER> will cause warning messages to be
1249 raised for their respective categories, but otherwise the code points are
1250 considered valid (not malformations).  To get a category to both be treated as
1251 a malformation and raise a warning, specify both the WARN and DISALLOW flags.
1252 (But note that warnings are not raised if lexically disabled nor if
1253 C<UTF8_CHECK_ONLY> is also specified.)
1254
1255 Extremely high code points were never specified in any standard, and require an
1256 extension to UTF-8 to express, which Perl does.  It is likely that programs
1257 written in something other than Perl would not be able to read files that
1258 contain these; nor would Perl understand files written by something that uses a
1259 different extension.  For these reasons, there is a separate set of flags that
1260 can warn and/or disallow these extremely high code points, even if other
1261 above-Unicode ones are accepted.  They are the C<UTF8_WARN_PERL_EXTENDED> and
1262 C<UTF8_DISALLOW_PERL_EXTENDED> flags.  For more information see
1263 C<L</UTF8_GOT_PERL_EXTENDED>>.  Of course C<UTF8_DISALLOW_SUPER> will treat all
1264 above-Unicode code points, including these, as malformations.
1265 (Note that the Unicode standard considers anything above 0x10FFFF to be
1266 illegal, but there are standards predating it that allow up to 0x7FFF_FFFF
1267 (2**31 -1))
1268
1269 A somewhat misleadingly named synonym for C<UTF8_WARN_PERL_EXTENDED> is
1270 retained for backward compatibility: C<UTF8_WARN_ABOVE_31_BIT>.  Similarly,
1271 C<UTF8_DISALLOW_ABOVE_31_BIT> is usable instead of the more accurately named
1272 C<UTF8_DISALLOW_PERL_EXTENDED>.  The names are misleading because these flags
1273 can apply to code points that actually do fit in 31 bits.  This happens on
1274 EBCDIC platforms, and sometimes when the L<overlong
1275 malformation|/C<UTF8_GOT_LONG>> is also present.  The new names accurately
1276 describe the situation in all cases.
1277
1278
1279 All other code points corresponding to Unicode characters, including private
1280 use and those yet to be assigned, are never considered malformed and never
1281 warn.
1282
1283 =for apidoc Amnh||UTF8_CHECK_ONLY
1284 =for apidoc Amnh||UTF8_DISALLOW_ILLEGAL_INTERCHANGE
1285 =for apidoc Amnh||UTF8_DISALLOW_ILLEGAL_C9_INTERCHANGE
1286 =for apidoc Amnh||UTF8_DISALLOW_SURROGATE
1287 =for apidoc Amnh||UTF8_DISALLOW_NONCHAR
1288 =for apidoc Amnh||UTF8_DISALLOW_SUPER
1289 =for apidoc Amnh||UTF8_WARN_ILLEGAL_INTERCHANGE
1290 =for apidoc Amnh||UTF8_WARN_ILLEGAL_C9_INTERCHANGE
1291 =for apidoc Amnh||UTF8_WARN_SURROGATE
1292 =for apidoc Amnh||UTF8_WARN_NONCHAR
1293 =for apidoc Amnh||UTF8_WARN_SUPER
1294 =for apidoc Amnh||UTF8_WARN_PERL_EXTENDED
1295 =for apidoc Amnh||UTF8_DISALLOW_PERL_EXTENDED
1296
1297 =cut
1298
1299 Also implemented as a macro in utf8.h
1300 */
1301
1302 UV
1303 Perl_utf8n_to_uvchr(const U8 *s,
1304                     STRLEN curlen,
1305                     STRLEN *retlen,
1306                     const U32 flags)
1307 {
1308     PERL_ARGS_ASSERT_UTF8N_TO_UVCHR;
1309
1310     return utf8n_to_uvchr_error(s, curlen, retlen, flags, NULL);
1311 }
1312
1313 /*
1314
1315 =for apidoc utf8n_to_uvchr_error
1316
1317 THIS FUNCTION SHOULD BE USED IN ONLY VERY SPECIALIZED CIRCUMSTANCES.
1318 Most code should use L</utf8_to_uvchr_buf>() rather than call this
1319 directly.
1320
1321 This function is for code that needs to know what the precise malformation(s)
1322 are when an error is found.  If you also need to know the generated warning
1323 messages, use L</utf8n_to_uvchr_msgs>() instead.
1324
1325 It is like C<L</utf8n_to_uvchr>> but it takes an extra parameter placed after
1326 all the others, C<errors>.  If this parameter is 0, this function behaves
1327 identically to C<L</utf8n_to_uvchr>>.  Otherwise, C<errors> should be a pointer
1328 to a C<U32> variable, which this function sets to indicate any errors found.
1329 Upon return, if C<*errors> is 0, there were no errors found.  Otherwise,
1330 C<*errors> is the bit-wise C<OR> of the bits described in the list below.  Some
1331 of these bits will be set if a malformation is found, even if the input
1332 C<flags> parameter indicates that the given malformation is allowed; those
1333 exceptions are noted:
1334
1335 =over 4
1336
1337 =item C<UTF8_GOT_PERL_EXTENDED>
1338
1339 The input sequence is not standard UTF-8, but a Perl extension.  This bit is
1340 set only if the input C<flags> parameter contains either the
1341 C<UTF8_DISALLOW_PERL_EXTENDED> or the C<UTF8_WARN_PERL_EXTENDED> flags.
1342
1343 Code points above 0x7FFF_FFFF (2**31 - 1) were never specified in any standard,
1344 and so some extension must be used to express them.  Perl uses a natural
1345 extension to UTF-8 to represent the ones up to 2**36-1, and invented a further
1346 extension to represent even higher ones, so that any code point that fits in a
1347 64-bit word can be represented.  Text using these extensions is not likely to
1348 be portable to non-Perl code.  We lump both of these extensions together and
1349 refer to them as Perl extended UTF-8.  There exist other extensions that people
1350 have invented, incompatible with Perl's.
1351
1352 On EBCDIC platforms starting in Perl v5.24, the Perl extension for representing
1353 extremely high code points kicks in at 0x3FFF_FFFF (2**30 -1), which is lower
1354 than on ASCII.  Prior to that, code points 2**31 and higher were simply
1355 unrepresentable, and a different, incompatible method was used to represent
1356 code points between 2**30 and 2**31 - 1.
1357
1358 On both platforms, ASCII and EBCDIC, C<UTF8_GOT_PERL_EXTENDED> is set if
1359 Perl extended UTF-8 is used.
1360
1361 In earlier Perls, this bit was named C<UTF8_GOT_ABOVE_31_BIT>, which you still
1362 may use for backward compatibility.  That name is misleading, as this flag may
1363 be set when the code point actually does fit in 31 bits.  This happens on
1364 EBCDIC platforms, and sometimes when the L<overlong
1365 malformation|/C<UTF8_GOT_LONG>> is also present.  The new name accurately
1366 describes the situation in all cases.
1367
1368 =item C<UTF8_GOT_CONTINUATION>
1369
1370 The input sequence was malformed in that the first byte was a UTF-8
1371 continuation byte.
1372
1373 =item C<UTF8_GOT_EMPTY>
1374
1375 The input C<curlen> parameter was 0.
1376
1377 =item C<UTF8_GOT_LONG>
1378
1379 The input sequence was malformed in that there is some other sequence that
1380 evaluates to the same code point, but that sequence is shorter than this one.
1381
1382 Until Unicode 3.1, it was legal for programs to accept this malformation, but
1383 it was discovered that this created security issues.
1384
1385 =item C<UTF8_GOT_NONCHAR>
1386
1387 The code point represented by the input UTF-8 sequence is for a Unicode
1388 non-character code point.
1389 This bit is set only if the input C<flags> parameter contains either the
1390 C<UTF8_DISALLOW_NONCHAR> or the C<UTF8_WARN_NONCHAR> flags.
1391
1392 =item C<UTF8_GOT_NON_CONTINUATION>
1393
1394 The input sequence was malformed in that a non-continuation type byte was found
1395 in a position where only a continuation type one should be.  See also
1396 C<L</UTF8_GOT_SHORT>>.
1397
1398 =item C<UTF8_GOT_OVERFLOW>
1399
1400 The input sequence was malformed in that it is for a code point that is not
1401 representable in the number of bits available in an IV on the current platform.
1402
1403 =item C<UTF8_GOT_SHORT>
1404
1405 The input sequence was malformed in that C<curlen> is smaller than required for
1406 a complete sequence.  In other words, the input is for a partial character
1407 sequence.
1408
1409
1410 C<UTF8_GOT_SHORT> and C<UTF8_GOT_NON_CONTINUATION> both indicate a too short
1411 sequence.  The difference is that C<UTF8_GOT_NON_CONTINUATION> indicates always
1412 that there is an error, while C<UTF8_GOT_SHORT> means that an incomplete
1413 sequence was looked at.   If no other flags are present, it means that the
1414 sequence was valid as far as it went.  Depending on the application, this could
1415 mean one of three things:
1416
1417 =over
1418
1419 =item *
1420
1421 The C<curlen> length parameter passed in was too small, and the function was
1422 prevented from examining all the necessary bytes.
1423
1424 =item *
1425
1426 The buffer being looked at is based on reading data, and the data received so
1427 far stopped in the middle of a character, so that the next read will
1428 read the remainder of this character.  (It is up to the caller to deal with the
1429 split bytes somehow.)
1430
1431 =item *
1432
1433 This is a real error, and the partial sequence is all we're going to get.
1434
1435 =back
1436
1437 =item C<UTF8_GOT_SUPER>
1438
1439 The input sequence was malformed in that it is for a non-Unicode code point;
1440 that is, one above the legal Unicode maximum.
1441 This bit is set only if the input C<flags> parameter contains either the
1442 C<UTF8_DISALLOW_SUPER> or the C<UTF8_WARN_SUPER> flags.
1443
1444 =item C<UTF8_GOT_SURROGATE>
1445
1446 The input sequence was malformed in that it is for a -Unicode UTF-16 surrogate
1447 code point.
1448 This bit is set only if the input C<flags> parameter contains either the
1449 C<UTF8_DISALLOW_SURROGATE> or the C<UTF8_WARN_SURROGATE> flags.
1450
1451 =back
1452
1453 To do your own error handling, call this function with the C<UTF8_CHECK_ONLY>
1454 flag to suppress any warnings, and then examine the C<*errors> return.
1455
1456 =cut
1457
1458 Also implemented as a macro in utf8.h
1459 */
1460
1461 UV
1462 Perl_utf8n_to_uvchr_error(const U8 *s,
1463                           STRLEN curlen,
1464                           STRLEN *retlen,
1465                           const U32 flags,
1466                           U32 * errors)
1467 {
1468     PERL_ARGS_ASSERT_UTF8N_TO_UVCHR_ERROR;
1469
1470     return utf8n_to_uvchr_msgs(s, curlen, retlen, flags, errors, NULL);
1471 }
1472
1473 /*
1474
1475 =for apidoc utf8n_to_uvchr_msgs
1476
1477 THIS FUNCTION SHOULD BE USED IN ONLY VERY SPECIALIZED CIRCUMSTANCES.
1478 Most code should use L</utf8_to_uvchr_buf>() rather than call this
1479 directly.
1480
1481 This function is for code that needs to know what the precise malformation(s)
1482 are when an error is found, and wants the corresponding warning and/or error
1483 messages to be returned to the caller rather than be displayed.  All messages
1484 that would have been displayed if all lexcial warnings are enabled will be
1485 returned.
1486
1487 It is just like C<L</utf8n_to_uvchr_error>> but it takes an extra parameter
1488 placed after all the others, C<msgs>.  If this parameter is 0, this function
1489 behaves identically to C<L</utf8n_to_uvchr_error>>.  Otherwise, C<msgs> should
1490 be a pointer to an C<AV *> variable, in which this function creates a new AV to
1491 contain any appropriate messages.  The elements of the array are ordered so
1492 that the first message that would have been displayed is in the 0th element,
1493 and so on.  Each element is a hash with three key-value pairs, as follows:
1494
1495 =over 4
1496
1497 =item C<text>
1498
1499 The text of the message as a C<SVpv>.
1500
1501 =item C<warn_categories>
1502
1503 The warning category (or categories) packed into a C<SVuv>.
1504
1505 =item C<flag>
1506
1507 A single flag bit associated with this message, in a C<SVuv>.
1508 The bit corresponds to some bit in the C<*errors> return value,
1509 such as C<UTF8_GOT_LONG>.
1510
1511 =back
1512
1513 It's important to note that specifying this parameter as non-null will cause
1514 any warnings this function would otherwise generate to be suppressed, and
1515 instead be placed in C<*msgs>.  The caller can check the lexical warnings state
1516 (or not) when choosing what to do with the returned messages.
1517
1518 If the flag C<UTF8_CHECK_ONLY> is passed, no warnings are generated, and hence
1519 no AV is created.
1520
1521 The caller, of course, is responsible for freeing any returned AV.
1522
1523 =cut
1524 */
1525
1526 UV
1527 Perl__utf8n_to_uvchr_msgs_helper(const U8 *s,
1528                                STRLEN curlen,
1529                                STRLEN *retlen,
1530                                const U32 flags,
1531                                U32 * errors,
1532                                AV ** msgs)
1533 {
1534     const U8 * const s0 = s;
1535     const U8 * send = s0 + curlen;
1536     U32 possible_problems;  /* A bit is set here for each potential problem
1537                                found as we go along */
1538     UV uv;
1539     STRLEN expectlen;     /* How long should this sequence be? */
1540     STRLEN avail_len;     /* When input is too short, gives what that is */
1541     U32 discard_errors;   /* Used to save branches when 'errors' is NULL; this
1542                              gets set and discarded */
1543
1544     /* The below are used only if there is both an overlong malformation and a
1545      * too short one.  Otherwise the first two are set to 's0' and 'send', and
1546      * the third not used at all */
1547     U8 * adjusted_s0;
1548     U8 temp_char_buf[UTF8_MAXBYTES + 1]; /* Used to avoid a Newx in this
1549                                             routine; see [perl #130921] */
1550     UV uv_so_far;
1551     dTHX;
1552
1553     PERL_ARGS_ASSERT__UTF8N_TO_UVCHR_MSGS_HELPER;
1554
1555     /* Here, is one of: a) malformed; b) a problematic code point (surrogate,
1556      * non-unicode, or nonchar); or c) on ASCII platforms, one of the Hangul
1557      * syllables that the dfa doesn't properly handle.  Quickly dispose of the
1558      * final case. */
1559
1560 #ifndef EBCDIC
1561
1562     /* Each of the affected Hanguls starts with \xED */
1563
1564     if (is_HANGUL_ED_utf8_safe(s0, send)) {
1565         if (retlen) {
1566             *retlen = 3;
1567         }
1568         if (errors) {
1569             *errors = 0;
1570         }
1571         if (msgs) {
1572             *msgs = NULL;
1573         }
1574
1575         return ((0xED & UTF_START_MASK(3)) << (2 * UTF_ACCUMULATION_SHIFT))
1576              | ((s0[1] & UTF_CONTINUATION_MASK) << UTF_ACCUMULATION_SHIFT)
1577              |  (s0[2] & UTF_CONTINUATION_MASK);
1578     }
1579
1580 #endif
1581
1582     /* In conjunction with the exhaustive tests that can be enabled in
1583      * APItest/t/utf8_warn_base.pl, this can make sure the dfa does precisely
1584      * what it is intended to do, and that no flaws in it are masked by
1585      * dropping down and executing the code below
1586     assert(! isUTF8_CHAR(s0, send)
1587           || UTF8_IS_SURROGATE(s0, send)
1588           || UTF8_IS_SUPER(s0, send)
1589           || UTF8_IS_NONCHAR(s0,send));
1590     */
1591
1592     s = s0;
1593     uv = *s0;
1594     possible_problems = 0;
1595     expectlen = 0;
1596     avail_len = 0;
1597     discard_errors = 0;
1598     adjusted_s0 = (U8 *) s0;
1599     uv_so_far = 0;
1600
1601     if (errors) {
1602         *errors = 0;
1603     }
1604     else {
1605         errors = &discard_errors;
1606     }
1607
1608     /* The order of malformation tests here is important.  We should consume as
1609      * few bytes as possible in order to not skip any valid character.  This is
1610      * required by the Unicode Standard (section 3.9 of Unicode 6.0); see also
1611      * https://unicode.org/reports/tr36 for more discussion as to why.  For
1612      * example, once we've done a UTF8SKIP, we can tell the expected number of
1613      * bytes, and could fail right off the bat if the input parameters indicate
1614      * that there are too few available.  But it could be that just that first
1615      * byte is garbled, and the intended character occupies fewer bytes.  If we
1616      * blindly assumed that the first byte is correct, and skipped based on
1617      * that number, we could skip over a valid input character.  So instead, we
1618      * always examine the sequence byte-by-byte.
1619      *
1620      * We also should not consume too few bytes, otherwise someone could inject
1621      * things.  For example, an input could be deliberately designed to
1622      * overflow, and if this code bailed out immediately upon discovering that,
1623      * returning to the caller C<*retlen> pointing to the very next byte (one
1624      * which is actually part of the overflowing sequence), that could look
1625      * legitimate to the caller, which could discard the initial partial
1626      * sequence and process the rest, inappropriately.
1627      *
1628      * Some possible input sequences are malformed in more than one way.  This
1629      * function goes to lengths to try to find all of them.  This is necessary
1630      * for correctness, as the inputs may allow one malformation but not
1631      * another, and if we abandon searching for others after finding the
1632      * allowed one, we could allow in something that shouldn't have been.
1633      */
1634
1635     if (UNLIKELY(curlen == 0)) {
1636         possible_problems |= UTF8_GOT_EMPTY;
1637         curlen = 0;
1638         uv = UNICODE_REPLACEMENT;
1639         goto ready_to_handle_errors;
1640     }
1641
1642     expectlen = UTF8SKIP(s);
1643
1644     /* A well-formed UTF-8 character, as the vast majority of calls to this
1645      * function will be for, has this expected length.  For efficiency, set
1646      * things up here to return it.  It will be overriden only in those rare
1647      * cases where a malformation is found */
1648     if (retlen) {
1649         *retlen = expectlen;
1650     }
1651
1652     /* A continuation character can't start a valid sequence */
1653     if (UNLIKELY(UTF8_IS_CONTINUATION(uv))) {
1654         possible_problems |= UTF8_GOT_CONTINUATION;
1655         curlen = 1;
1656         uv = UNICODE_REPLACEMENT;
1657         goto ready_to_handle_errors;
1658     }
1659
1660     /* Here is not a continuation byte, nor an invariant.  The only thing left
1661      * is a start byte (possibly for an overlong).  (We can't use UTF8_IS_START
1662      * because it excludes start bytes like \xC0 that always lead to
1663      * overlongs.) */
1664
1665     /* Convert to I8 on EBCDIC (no-op on ASCII), then remove the leading bits
1666      * that indicate the number of bytes in the character's whole UTF-8
1667      * sequence, leaving just the bits that are part of the value.  */
1668     uv = NATIVE_UTF8_TO_I8(uv) & UTF_START_MASK(expectlen);
1669
1670     /* Setup the loop end point, making sure to not look past the end of the
1671      * input string, and flag it as too short if the size isn't big enough. */
1672     if (UNLIKELY(curlen < expectlen)) {
1673         possible_problems |= UTF8_GOT_SHORT;
1674         avail_len = curlen;
1675     }
1676     else {
1677         send = (U8*) s0 + expectlen;
1678     }
1679
1680     /* Now, loop through the remaining bytes in the character's sequence,
1681      * accumulating each into the working value as we go. */
1682     for (s = s0 + 1; s < send; s++) {
1683         if (LIKELY(UTF8_IS_CONTINUATION(*s))) {
1684             uv = UTF8_ACCUMULATE(uv, *s);
1685             continue;
1686         }
1687
1688         /* Here, found a non-continuation before processing all expected bytes.
1689          * This byte indicates the beginning of a new character, so quit, even
1690          * if allowing this malformation. */
1691         possible_problems |= UTF8_GOT_NON_CONTINUATION;
1692         break;
1693     } /* End of loop through the character's bytes */
1694
1695     /* Save how many bytes were actually in the character */
1696     curlen = s - s0;
1697
1698     /* Note that there are two types of too-short malformation.  One is when
1699      * there is actual wrong data before the normal termination of the
1700      * sequence.  The other is that the sequence wasn't complete before the end
1701      * of the data we are allowed to look at, based on the input 'curlen'.
1702      * This means that we were passed data for a partial character, but it is
1703      * valid as far as we saw.  The other is definitely invalid.  This
1704      * distinction could be important to a caller, so the two types are kept
1705      * separate.
1706      *
1707      * A convenience macro that matches either of the too-short conditions.  */
1708 #   define UTF8_GOT_TOO_SHORT (UTF8_GOT_SHORT|UTF8_GOT_NON_CONTINUATION)
1709
1710     if (UNLIKELY(possible_problems & UTF8_GOT_TOO_SHORT)) {
1711         uv_so_far = uv;
1712         uv = UNICODE_REPLACEMENT;
1713     }
1714
1715     /* Check for overflow.  The algorithm requires us to not look past the end
1716      * of the current character, even if partial, so the upper limit is 's' */
1717     if (UNLIKELY(0 < does_utf8_overflow(s0, s,
1718                                          1 /* Do consider overlongs */
1719                                         )))
1720     {
1721         possible_problems |= UTF8_GOT_OVERFLOW;
1722         uv = UNICODE_REPLACEMENT;
1723     }
1724
1725     /* Check for overlong.  If no problems so far, 'uv' is the correct code
1726      * point value.  Simply see if it is expressible in fewer bytes.  Otherwise
1727      * we must look at the UTF-8 byte sequence itself to see if it is for an
1728      * overlong */
1729     if (     (   LIKELY(! possible_problems)
1730               && UNLIKELY(expectlen > (STRLEN) OFFUNISKIP(uv)))
1731         || (       UNLIKELY(possible_problems)
1732             && (   UNLIKELY(! UTF8_IS_START(*s0))
1733                 || (   curlen > 1
1734                     && UNLIKELY(0 < is_utf8_overlong_given_start_byte_ok(s0,
1735                                                                 s - s0))))))
1736     {
1737         possible_problems |= UTF8_GOT_LONG;
1738
1739         if (   UNLIKELY(   possible_problems & UTF8_GOT_TOO_SHORT)
1740
1741                           /* The calculation in the 'true' branch of this 'if'
1742                            * below won't work if overflows, and isn't needed
1743                            * anyway.  Further below we handle all overflow
1744                            * cases */
1745             &&   LIKELY(! (possible_problems & UTF8_GOT_OVERFLOW)))
1746         {
1747             UV min_uv = uv_so_far;
1748             STRLEN i;
1749
1750             /* Here, the input is both overlong and is missing some trailing
1751              * bytes.  There is no single code point it could be for, but there
1752              * may be enough information present to determine if what we have
1753              * so far is for an unallowed code point, such as for a surrogate.
1754              * The code further below has the intelligence to determine this,
1755              * but just for non-overlong UTF-8 sequences.  What we do here is
1756              * calculate the smallest code point the input could represent if
1757              * there were no too short malformation.  Then we compute and save
1758              * the UTF-8 for that, which is what the code below looks at
1759              * instead of the raw input.  It turns out that the smallest such
1760              * code point is all we need. */
1761             for (i = curlen; i < expectlen; i++) {
1762                 min_uv = UTF8_ACCUMULATE(min_uv,
1763                                      I8_TO_NATIVE_UTF8(UTF_CONTINUATION_MARK));
1764             }
1765
1766             adjusted_s0 = temp_char_buf;
1767             (void) uvoffuni_to_utf8_flags(adjusted_s0, min_uv, 0);
1768         }
1769     }
1770
1771     /* Here, we have found all the possible problems, except for when the input
1772      * is for a problematic code point not allowed by the input parameters. */
1773
1774                                 /* uv is valid for overlongs */
1775     if (   (   (      LIKELY(! (possible_problems & ~UTF8_GOT_LONG))
1776
1777                       /* isn't problematic if < this */
1778                    && uv >= UNICODE_SURROGATE_FIRST)
1779             || (   UNLIKELY(possible_problems)
1780
1781                           /* if overflow, we know without looking further
1782                            * precisely which of the problematic types it is,
1783                            * and we deal with those in the overflow handling
1784                            * code */
1785                 && LIKELY(! (possible_problems & UTF8_GOT_OVERFLOW))
1786                 && (   isUTF8_POSSIBLY_PROBLEMATIC(*adjusted_s0)
1787                     || UNLIKELY(isUTF8_PERL_EXTENDED(s0)))))
1788         && ((flags & ( UTF8_DISALLOW_NONCHAR
1789                       |UTF8_DISALLOW_SURROGATE
1790                       |UTF8_DISALLOW_SUPER
1791                       |UTF8_DISALLOW_PERL_EXTENDED
1792                       |UTF8_WARN_NONCHAR
1793                       |UTF8_WARN_SURROGATE
1794                       |UTF8_WARN_SUPER
1795                       |UTF8_WARN_PERL_EXTENDED))))
1796     {
1797         /* If there were no malformations, or the only malformation is an
1798          * overlong, 'uv' is valid */
1799         if (LIKELY(! (possible_problems & ~UTF8_GOT_LONG))) {
1800             if (UNLIKELY(UNICODE_IS_SURROGATE(uv))) {
1801                 possible_problems |= UTF8_GOT_SURROGATE;
1802             }
1803             else if (UNLIKELY(uv > PERL_UNICODE_MAX)) {
1804                 possible_problems |= UTF8_GOT_SUPER;
1805             }
1806             else if (UNLIKELY(UNICODE_IS_NONCHAR(uv))) {
1807                 possible_problems |= UTF8_GOT_NONCHAR;
1808             }
1809         }
1810         else {  /* Otherwise, need to look at the source UTF-8, possibly
1811                    adjusted to be non-overlong */
1812
1813             if (UNLIKELY(NATIVE_UTF8_TO_I8(*adjusted_s0)
1814                                 >= FIRST_START_BYTE_THAT_IS_DEFINITELY_SUPER))
1815             {
1816                 possible_problems |= UTF8_GOT_SUPER;
1817             }
1818             else if (curlen > 1) {
1819                 if (UNLIKELY(IS_UTF8_2_BYTE_SUPER(
1820                                       NATIVE_UTF8_TO_I8(*adjusted_s0),
1821                                       NATIVE_UTF8_TO_I8(*(adjusted_s0 + 1)))))
1822                 {
1823                     possible_problems |= UTF8_GOT_SUPER;
1824                 }
1825                 else if (UNLIKELY(IS_UTF8_2_BYTE_SURROGATE(
1826                                       NATIVE_UTF8_TO_I8(*adjusted_s0),
1827                                       NATIVE_UTF8_TO_I8(*(adjusted_s0 + 1)))))
1828                 {
1829                     possible_problems |= UTF8_GOT_SURROGATE;
1830                 }
1831             }
1832
1833             /* We need a complete well-formed UTF-8 character to discern
1834              * non-characters, so can't look for them here */
1835         }
1836     }
1837
1838   ready_to_handle_errors:
1839
1840     /* At this point:
1841      * curlen               contains the number of bytes in the sequence that
1842      *                      this call should advance the input by.
1843      * avail_len            gives the available number of bytes passed in, but
1844      *                      only if this is less than the expected number of
1845      *                      bytes, based on the code point's start byte.
1846      * possible_problems'   is 0 if there weren't any problems; otherwise a bit
1847      *                      is set in it for each potential problem found.
1848      * uv                   contains the code point the input sequence
1849      *                      represents; or if there is a problem that prevents
1850      *                      a well-defined value from being computed, it is
1851      *                      some subsitute value, typically the REPLACEMENT
1852      *                      CHARACTER.
1853      * s0                   points to the first byte of the character
1854      * s                    points to just after were we left off processing
1855      *                      the character
1856      * send                 points to just after where that character should
1857      *                      end, based on how many bytes the start byte tells
1858      *                      us should be in it, but no further than s0 +
1859      *                      avail_len
1860      */
1861
1862     if (UNLIKELY(possible_problems)) {
1863         bool disallowed = FALSE;
1864         const U32 orig_problems = possible_problems;
1865
1866         if (msgs) {
1867             *msgs = NULL;
1868         }
1869
1870         while (possible_problems) { /* Handle each possible problem */
1871             U32 pack_warn = 0;
1872             char * message = NULL;
1873             U32 this_flag_bit = 0;
1874
1875             /* Each 'if' clause handles one problem.  They are ordered so that
1876              * the first ones' messages will be displayed before the later
1877              * ones; this is kinda in decreasing severity order.  But the
1878              * overlong must come last, as it changes 'uv' looked at by the
1879              * others */
1880             if (possible_problems & UTF8_GOT_OVERFLOW) {
1881
1882                 /* Overflow means also got a super and are using Perl's
1883                  * extended UTF-8, but we handle all three cases here */
1884                 possible_problems
1885                   &= ~(UTF8_GOT_OVERFLOW|UTF8_GOT_SUPER|UTF8_GOT_PERL_EXTENDED);
1886                 *errors |= UTF8_GOT_OVERFLOW;
1887
1888                 /* But the API says we flag all errors found */
1889                 if (flags & (UTF8_WARN_SUPER|UTF8_DISALLOW_SUPER)) {
1890                     *errors |= UTF8_GOT_SUPER;
1891                 }
1892                 if (flags
1893                         & (UTF8_WARN_PERL_EXTENDED|UTF8_DISALLOW_PERL_EXTENDED))
1894                 {
1895                     *errors |= UTF8_GOT_PERL_EXTENDED;
1896                 }
1897
1898                 /* Disallow if any of the three categories say to */
1899                 if ( ! (flags &   UTF8_ALLOW_OVERFLOW)
1900                     || (flags & ( UTF8_DISALLOW_SUPER
1901                                  |UTF8_DISALLOW_PERL_EXTENDED)))
1902                 {
1903                     disallowed = TRUE;
1904                 }
1905
1906                 /* Likewise, warn if any say to */
1907                 if (  ! (flags & UTF8_ALLOW_OVERFLOW)
1908                     ||  (flags & (UTF8_WARN_SUPER|UTF8_WARN_PERL_EXTENDED)))
1909                 {
1910
1911                     /* The warnings code explicitly says it doesn't handle the
1912                      * case of packWARN2 and two categories which have
1913                      * parent-child relationship.  Even if it works now to
1914                      * raise the warning if either is enabled, it wouldn't
1915                      * necessarily do so in the future.  We output (only) the
1916                      * most dire warning */
1917                     if (! (flags & UTF8_CHECK_ONLY)) {
1918                         if (msgs || ckWARN_d(WARN_UTF8)) {
1919                             pack_warn = packWARN(WARN_UTF8);
1920                         }
1921                         else if (msgs || ckWARN_d(WARN_NON_UNICODE)) {
1922                             pack_warn = packWARN(WARN_NON_UNICODE);
1923                         }
1924                         if (pack_warn) {
1925                             message = Perl_form(aTHX_ "%s: %s (overflows)",
1926                                             malformed_text,
1927                                             _byte_dump_string(s0, curlen, 0));
1928                             this_flag_bit = UTF8_GOT_OVERFLOW;
1929                         }
1930                     }
1931                 }
1932             }
1933             else if (possible_problems & UTF8_GOT_EMPTY) {
1934                 possible_problems &= ~UTF8_GOT_EMPTY;
1935                 *errors |= UTF8_GOT_EMPTY;
1936
1937                 if (! (flags & UTF8_ALLOW_EMPTY)) {
1938
1939                     /* This so-called malformation is now treated as a bug in
1940                      * the caller.  If you have nothing to decode, skip calling
1941                      * this function */
1942                     assert(0);
1943
1944                     disallowed = TRUE;
1945                     if (  (msgs
1946                         || ckWARN_d(WARN_UTF8)) && ! (flags & UTF8_CHECK_ONLY))
1947                     {
1948                         pack_warn = packWARN(WARN_UTF8);
1949                         message = Perl_form(aTHX_ "%s (empty string)",
1950                                                    malformed_text);
1951                         this_flag_bit = UTF8_GOT_EMPTY;
1952                     }
1953                 }
1954             }
1955             else if (possible_problems & UTF8_GOT_CONTINUATION) {
1956                 possible_problems &= ~UTF8_GOT_CONTINUATION;
1957                 *errors |= UTF8_GOT_CONTINUATION;
1958
1959                 if (! (flags & UTF8_ALLOW_CONTINUATION)) {
1960                     disallowed = TRUE;
1961                     if ((   msgs
1962                          || ckWARN_d(WARN_UTF8)) && ! (flags & UTF8_CHECK_ONLY))
1963                     {
1964                         pack_warn = packWARN(WARN_UTF8);
1965                         message = Perl_form(aTHX_
1966                                 "%s: %s (unexpected continuation byte 0x%02x,"
1967                                 " with no preceding start byte)",
1968                                 malformed_text,
1969                                 _byte_dump_string(s0, 1, 0), *s0);
1970                         this_flag_bit = UTF8_GOT_CONTINUATION;
1971                     }
1972                 }
1973             }
1974             else if (possible_problems & UTF8_GOT_SHORT) {
1975                 possible_problems &= ~UTF8_GOT_SHORT;
1976                 *errors |= UTF8_GOT_SHORT;
1977
1978                 if (! (flags & UTF8_ALLOW_SHORT)) {
1979                     disallowed = TRUE;
1980                     if ((   msgs
1981                          || ckWARN_d(WARN_UTF8)) && ! (flags & UTF8_CHECK_ONLY))
1982                     {
1983                         pack_warn = packWARN(WARN_UTF8);
1984                         message = Perl_form(aTHX_
1985                              "%s: %s (too short; %d byte%s available, need %d)",
1986                              malformed_text,
1987                              _byte_dump_string(s0, send - s0, 0),
1988                              (int)avail_len,
1989                              avail_len == 1 ? "" : "s",
1990                              (int)expectlen);
1991                         this_flag_bit = UTF8_GOT_SHORT;
1992                     }
1993                 }
1994
1995             }
1996             else if (possible_problems & UTF8_GOT_NON_CONTINUATION) {
1997                 possible_problems &= ~UTF8_GOT_NON_CONTINUATION;
1998                 *errors |= UTF8_GOT_NON_CONTINUATION;
1999
2000                 if (! (flags & UTF8_ALLOW_NON_CONTINUATION)) {
2001                     disallowed = TRUE;
2002                     if ((   msgs
2003                          || ckWARN_d(WARN_UTF8)) && ! (flags & UTF8_CHECK_ONLY))
2004                     {
2005
2006                         /* If we don't know for sure that the input length is
2007                          * valid, avoid as much as possible reading past the
2008                          * end of the buffer */
2009                         int printlen = (flags & _UTF8_NO_CONFIDENCE_IN_CURLEN)
2010                                        ? (int) (s - s0)
2011                                        : (int) (send - s0);
2012                         pack_warn = packWARN(WARN_UTF8);
2013                         message = Perl_form(aTHX_ "%s",
2014                             unexpected_non_continuation_text(s0,
2015                                                             printlen,
2016                                                             s - s0,
2017                                                             (int) expectlen));
2018                         this_flag_bit = UTF8_GOT_NON_CONTINUATION;
2019                     }
2020                 }
2021             }
2022             else if (possible_problems & UTF8_GOT_SURROGATE) {
2023                 possible_problems &= ~UTF8_GOT_SURROGATE;
2024
2025                 if (flags & UTF8_WARN_SURROGATE) {
2026                     *errors |= UTF8_GOT_SURROGATE;
2027
2028                     if (   ! (flags & UTF8_CHECK_ONLY)
2029                         && (msgs || ckWARN_d(WARN_SURROGATE)))
2030                     {
2031                         pack_warn = packWARN(WARN_SURROGATE);
2032
2033                         /* These are the only errors that can occur with a
2034                         * surrogate when the 'uv' isn't valid */
2035                         if (orig_problems & UTF8_GOT_TOO_SHORT) {
2036                             message = Perl_form(aTHX_
2037                                     "UTF-16 surrogate (any UTF-8 sequence that"
2038                                     " starts with \"%s\" is for a surrogate)",
2039                                     _byte_dump_string(s0, curlen, 0));
2040                         }
2041                         else {
2042                             message = Perl_form(aTHX_ surrogate_cp_format, uv);
2043                         }
2044                         this_flag_bit = UTF8_GOT_SURROGATE;
2045                     }
2046                 }
2047
2048                 if (flags & UTF8_DISALLOW_SURROGATE) {
2049                     disallowed = TRUE;
2050                     *errors |= UTF8_GOT_SURROGATE;
2051                 }
2052             }
2053             else if (possible_problems & UTF8_GOT_SUPER) {
2054                 possible_problems &= ~UTF8_GOT_SUPER;
2055
2056                 if (flags & UTF8_WARN_SUPER) {
2057                     *errors |= UTF8_GOT_SUPER;
2058
2059                     if (   ! (flags & UTF8_CHECK_ONLY)
2060                         && (msgs || ckWARN_d(WARN_NON_UNICODE)))
2061                     {
2062                         pack_warn = packWARN(WARN_NON_UNICODE);
2063
2064                         if (orig_problems & UTF8_GOT_TOO_SHORT) {
2065                             message = Perl_form(aTHX_
2066                                     "Any UTF-8 sequence that starts with"
2067                                     " \"%s\" is for a non-Unicode code point,"
2068                                     " may not be portable",
2069                                     _byte_dump_string(s0, curlen, 0));
2070                         }
2071                         else {
2072                             message = Perl_form(aTHX_ super_cp_format, uv);
2073                         }
2074                         this_flag_bit = UTF8_GOT_SUPER;
2075                     }
2076                 }
2077
2078                 /* Test for Perl's extended UTF-8 after the regular SUPER ones,
2079                  * and before possibly bailing out, so that the more dire
2080                  * warning will override the regular one. */
2081                 if (UNLIKELY(isUTF8_PERL_EXTENDED(s0))) {
2082                     if (  ! (flags & UTF8_CHECK_ONLY)
2083                         &&  (flags & (UTF8_WARN_PERL_EXTENDED|UTF8_WARN_SUPER))
2084                         &&  (msgs || (   ckWARN_d(WARN_NON_UNICODE)
2085                                       || ckWARN(WARN_PORTABLE))))
2086                     {
2087                         pack_warn = packWARN2(WARN_NON_UNICODE, WARN_PORTABLE);
2088
2089                         /* If it is an overlong that evaluates to a code point
2090                          * that doesn't have to use the Perl extended UTF-8, it
2091                          * still used it, and so we output a message that
2092                          * doesn't refer to the code point.  The same is true
2093                          * if there was a SHORT malformation where the code
2094                          * point is not valid.  In that case, 'uv' will have
2095                          * been set to the REPLACEMENT CHAR, and the message
2096                          * below without the code point in it will be selected
2097                          * */
2098                         if (UNICODE_IS_PERL_EXTENDED(uv)) {
2099                             message = Perl_form(aTHX_
2100                                             PL_extended_cp_format, uv);
2101                         }
2102                         else {
2103                             message = Perl_form(aTHX_
2104                                         "Any UTF-8 sequence that starts with"
2105                                         " \"%s\" is a Perl extension, and"
2106                                         " so is not portable",
2107                                         _byte_dump_string(s0, curlen, 0));
2108                         }
2109                         this_flag_bit = UTF8_GOT_PERL_EXTENDED;
2110                     }
2111
2112                     if (flags & ( UTF8_WARN_PERL_EXTENDED
2113                                  |UTF8_DISALLOW_PERL_EXTENDED))
2114                     {
2115                         *errors |= UTF8_GOT_PERL_EXTENDED;
2116
2117                         if (flags & UTF8_DISALLOW_PERL_EXTENDED) {
2118                             disallowed = TRUE;
2119                         }
2120                     }
2121                 }
2122
2123                 if (flags & UTF8_DISALLOW_SUPER) {
2124                     *errors |= UTF8_GOT_SUPER;
2125                     disallowed = TRUE;
2126                 }
2127             }
2128             else if (possible_problems & UTF8_GOT_NONCHAR) {
2129                 possible_problems &= ~UTF8_GOT_NONCHAR;
2130
2131                 if (flags & UTF8_WARN_NONCHAR) {
2132                     *errors |= UTF8_GOT_NONCHAR;
2133
2134                     if (  ! (flags & UTF8_CHECK_ONLY)
2135                         && (msgs || ckWARN_d(WARN_NONCHAR)))
2136                     {
2137                         /* The code above should have guaranteed that we don't
2138                          * get here with errors other than overlong */
2139                         assert (! (orig_problems
2140                                         & ~(UTF8_GOT_LONG|UTF8_GOT_NONCHAR)));
2141
2142                         pack_warn = packWARN(WARN_NONCHAR);
2143                         message = Perl_form(aTHX_ nonchar_cp_format, uv);
2144                         this_flag_bit = UTF8_GOT_NONCHAR;
2145                     }
2146                 }
2147
2148                 if (flags & UTF8_DISALLOW_NONCHAR) {
2149                     disallowed = TRUE;
2150                     *errors |= UTF8_GOT_NONCHAR;
2151                 }
2152             }
2153             else if (possible_problems & UTF8_GOT_LONG) {
2154                 possible_problems &= ~UTF8_GOT_LONG;
2155                 *errors |= UTF8_GOT_LONG;
2156
2157                 if (flags & UTF8_ALLOW_LONG) {
2158
2159                     /* We don't allow the actual overlong value, unless the
2160                      * special extra bit is also set */
2161                     if (! (flags & (   UTF8_ALLOW_LONG_AND_ITS_VALUE
2162                                     & ~UTF8_ALLOW_LONG)))
2163                     {
2164                         uv = UNICODE_REPLACEMENT;
2165                     }
2166                 }
2167                 else {
2168                     disallowed = TRUE;
2169
2170                     if ((   msgs
2171                          || ckWARN_d(WARN_UTF8)) && ! (flags & UTF8_CHECK_ONLY))
2172                     {
2173                         pack_warn = packWARN(WARN_UTF8);
2174
2175                         /* These error types cause 'uv' to be something that
2176                          * isn't what was intended, so can't use it in the
2177                          * message.  The other error types either can't
2178                          * generate an overlong, or else the 'uv' is valid */
2179                         if (orig_problems &
2180                                         (UTF8_GOT_TOO_SHORT|UTF8_GOT_OVERFLOW))
2181                         {
2182                             message = Perl_form(aTHX_
2183                                     "%s: %s (any UTF-8 sequence that starts"
2184                                     " with \"%s\" is overlong which can and"
2185                                     " should be represented with a"
2186                                     " different, shorter sequence)",
2187                                     malformed_text,
2188                                     _byte_dump_string(s0, send - s0, 0),
2189                                     _byte_dump_string(s0, curlen, 0));
2190                         }
2191                         else {
2192                             U8 tmpbuf[UTF8_MAXBYTES+1];
2193                             const U8 * const e = uvoffuni_to_utf8_flags(tmpbuf,
2194                                                                         uv, 0);
2195                             /* Don't use U+ for non-Unicode code points, which
2196                              * includes those in the Latin1 range */
2197                             const char * preface = (    uv > PERL_UNICODE_MAX
2198 #ifdef EBCDIC
2199                                                      || uv <= 0xFF
2200 #endif
2201                                                     )
2202                                                    ? "0x"
2203                                                    : "U+";
2204                             message = Perl_form(aTHX_
2205                                 "%s: %s (overlong; instead use %s to represent"
2206                                 " %s%0*" UVXf ")",
2207                                 malformed_text,
2208                                 _byte_dump_string(s0, send - s0, 0),
2209                                 _byte_dump_string(tmpbuf, e - tmpbuf, 0),
2210                                 preface,
2211                                 ((uv < 256) ? 2 : 4), /* Field width of 2 for
2212                                                          small code points */
2213                                 UNI_TO_NATIVE(uv));
2214                         }
2215                         this_flag_bit = UTF8_GOT_LONG;
2216                     }
2217                 }
2218             } /* End of looking through the possible flags */
2219
2220             /* Display the message (if any) for the problem being handled in
2221              * this iteration of the loop */
2222             if (message) {
2223                 if (msgs) {
2224                     assert(this_flag_bit);
2225
2226                     if (*msgs == NULL) {
2227                         *msgs = newAV();
2228                     }
2229
2230                     av_push(*msgs, newRV_noinc((SV*) new_msg_hv(message,
2231                                                                 pack_warn,
2232                                                                 this_flag_bit)));
2233                 }
2234                 else if (PL_op)
2235                     Perl_warner(aTHX_ pack_warn, "%s in %s", message,
2236                                                  OP_DESC(PL_op));
2237                 else
2238                     Perl_warner(aTHX_ pack_warn, "%s", message);
2239             }
2240         }   /* End of 'while (possible_problems)' */
2241
2242         /* Since there was a possible problem, the returned length may need to
2243          * be changed from the one stored at the beginning of this function.
2244          * Instead of trying to figure out if that's needed, just do it. */
2245         if (retlen) {
2246             *retlen = curlen;
2247         }
2248
2249         if (disallowed) {
2250             if (flags & UTF8_CHECK_ONLY && retlen) {
2251                 *retlen = ((STRLEN) -1);
2252             }
2253             return 0;
2254         }
2255     }
2256
2257     return UNI_TO_NATIVE(uv);
2258 }
2259
2260 /*
2261 =for apidoc utf8_to_uvchr_buf
2262
2263 Returns the native code point of the first character in the string C<s> which
2264 is assumed to be in UTF-8 encoding; C<send> points to 1 beyond the end of C<s>.
2265 C<*retlen> will be set to the length, in bytes, of that character.
2266
2267 If C<s> does not point to a well-formed UTF-8 character and UTF8 warnings are
2268 enabled, zero is returned and C<*retlen> is set (if C<retlen> isn't
2269 C<NULL>) to -1.  If those warnings are off, the computed value, if well-defined
2270 (or the Unicode REPLACEMENT CHARACTER if not), is silently returned, and
2271 C<*retlen> is set (if C<retlen> isn't C<NULL>) so that (S<C<s> + C<*retlen>>) is
2272 the next possible position in C<s> that could begin a non-malformed character.
2273 See L</utf8n_to_uvchr> for details on when the REPLACEMENT CHARACTER is
2274 returned.
2275
2276 =cut
2277
2278 Also implemented as a macro in utf8.h
2279
2280 */
2281
2282
2283 UV
2284 Perl_utf8_to_uvchr_buf(pTHX_ const U8 *s, const U8 *send, STRLEN *retlen)
2285 {
2286     PERL_ARGS_ASSERT_UTF8_TO_UVCHR_BUF;
2287
2288     return utf8_to_uvchr_buf_helper(s, send, retlen);
2289 }
2290
2291 /* This is marked as deprecated
2292  *
2293 =for apidoc utf8_to_uvuni_buf
2294
2295 Only in very rare circumstances should code need to be dealing in Unicode
2296 (as opposed to native) code points.  In those few cases, use
2297 C<L<NATIVE_TO_UNI(utf8_to_uvchr_buf(...))|perlapi/utf8_to_uvchr_buf>> instead.
2298 If you are not absolutely sure this is one of those cases, then assume it isn't
2299 and use plain C<utf8_to_uvchr_buf> instead.
2300
2301 Returns the Unicode (not-native) code point of the first character in the
2302 string C<s> which
2303 is assumed to be in UTF-8 encoding; C<send> points to 1 beyond the end of C<s>.
2304 C<retlen> will be set to the length, in bytes, of that character.
2305
2306 If C<s> does not point to a well-formed UTF-8 character and UTF8 warnings are
2307 enabled, zero is returned and C<*retlen> is set (if C<retlen> isn't
2308 NULL) to -1.  If those warnings are off, the computed value if well-defined (or
2309 the Unicode REPLACEMENT CHARACTER, if not) is silently returned, and C<*retlen>
2310 is set (if C<retlen> isn't NULL) so that (S<C<s> + C<*retlen>>) is the
2311 next possible position in C<s> that could begin a non-malformed character.
2312 See L<perlapi/utf8n_to_uvchr> for details on when the REPLACEMENT CHARACTER is
2313 returned.
2314
2315 =cut
2316 */
2317
2318 UV
2319 Perl_utf8_to_uvuni_buf(pTHX_ const U8 *s, const U8 *send, STRLEN *retlen)
2320 {
2321     PERL_ARGS_ASSERT_UTF8_TO_UVUNI_BUF;
2322
2323     assert(send > s);
2324
2325     return NATIVE_TO_UNI(utf8_to_uvchr_buf(s, send, retlen));
2326 }
2327
2328 /*
2329 =for apidoc utf8_length
2330
2331 Returns the number of characters in the sequence of UTF-8-encoded bytes starting
2332 at C<s> and ending at the byte just before C<e>.  If <s> and <e> point to the
2333 same place, it returns 0 with no warning raised.
2334
2335 If C<e E<lt> s> or if the scan would end up past C<e>, it raises a UTF8 warning
2336 and returns the number of valid characters.
2337
2338 =cut
2339 */
2340
2341 STRLEN
2342 Perl_utf8_length(pTHX_ const U8 *s, const U8 *e)
2343 {
2344     STRLEN len = 0;
2345
2346     PERL_ARGS_ASSERT_UTF8_LENGTH;
2347
2348     /* Note: cannot use UTF8_IS_...() too eagerly here since e.g.
2349      * the bitops (especially ~) can create illegal UTF-8.
2350      * In other words: in Perl UTF-8 is not just for Unicode. */
2351
2352     if (UNLIKELY(e < s))
2353         goto warn_and_return;
2354     while (s < e) {
2355         s += UTF8SKIP(s);
2356         len++;
2357     }
2358
2359     if (UNLIKELY(e != s)) {
2360         len--;
2361         warn_and_return:
2362         if (PL_op)
2363             Perl_ck_warner_d(aTHX_ packWARN(WARN_UTF8),
2364                              "%s in %s", unees, OP_DESC(PL_op));
2365         else
2366             Perl_ck_warner_d(aTHX_ packWARN(WARN_UTF8), "%s", unees);
2367     }
2368
2369     return len;
2370 }
2371
2372 /*
2373 =for apidoc bytes_cmp_utf8
2374
2375 Compares the sequence of characters (stored as octets) in C<b>, C<blen> with the
2376 sequence of characters (stored as UTF-8)
2377 in C<u>, C<ulen>.  Returns 0 if they are
2378 equal, -1 or -2 if the first string is less than the second string, +1 or +2
2379 if the first string is greater than the second string.
2380
2381 -1 or +1 is returned if the shorter string was identical to the start of the
2382 longer string.  -2 or +2 is returned if
2383 there was a difference between characters
2384 within the strings.
2385
2386 =cut
2387 */
2388
2389 int
2390 Perl_bytes_cmp_utf8(pTHX_ const U8 *b, STRLEN blen, const U8 *u, STRLEN ulen)
2391 {
2392     const U8 *const bend = b + blen;
2393     const U8 *const uend = u + ulen;
2394
2395     PERL_ARGS_ASSERT_BYTES_CMP_UTF8;
2396
2397     while (b < bend && u < uend) {
2398         U8 c = *u++;
2399         if (!UTF8_IS_INVARIANT(c)) {
2400             if (UTF8_IS_DOWNGRADEABLE_START(c)) {
2401                 if (u < uend) {
2402                     U8 c1 = *u++;
2403                     if (UTF8_IS_CONTINUATION(c1)) {
2404                         c = EIGHT_BIT_UTF8_TO_NATIVE(c, c1);
2405                     } else {
2406                         /* diag_listed_as: Malformed UTF-8 character%s */
2407                         Perl_ck_warner_d(aTHX_ packWARN(WARN_UTF8),
2408                               "%s %s%s",
2409                               unexpected_non_continuation_text(u - 2, 2, 1, 2),
2410                               PL_op ? " in " : "",
2411                               PL_op ? OP_DESC(PL_op) : "");
2412                         return -2;
2413                     }
2414                 } else {
2415                     if (PL_op)
2416                         Perl_ck_warner_d(aTHX_ packWARN(WARN_UTF8),
2417                                          "%s in %s", unees, OP_DESC(PL_op));
2418                     else
2419                         Perl_ck_warner_d(aTHX_ packWARN(WARN_UTF8), "%s", unees);
2420                     return -2; /* Really want to return undef :-)  */
2421                 }
2422             } else {
2423                 return -2;
2424             }
2425         }
2426         if (*b != c) {
2427             return *b < c ? -2 : +2;
2428         }
2429         ++b;
2430     }
2431
2432     if (b == bend && u == uend)
2433         return 0;
2434
2435     return b < bend ? +1 : -1;
2436 }
2437
2438 /*
2439 =for apidoc utf8_to_bytes
2440
2441 Converts a string C<"s"> of length C<*lenp> from UTF-8 into native byte encoding.
2442 Unlike L</bytes_to_utf8>, this over-writes the original string, and
2443 updates C<*lenp> to contain the new length.
2444 Returns zero on failure (leaving C<"s"> unchanged) setting C<*lenp> to -1.
2445
2446 Upon successful return, the number of variants in the string can be computed by
2447 having saved the value of C<*lenp> before the call, and subtracting the
2448 after-call value of C<*lenp> from it.
2449
2450 If you need a copy of the string, see L</bytes_from_utf8>.
2451
2452 =cut
2453 */
2454
2455 U8 *
2456 Perl_utf8_to_bytes(pTHX_ U8 *s, STRLEN *lenp)
2457 {
2458     U8 * first_variant;
2459
2460     PERL_ARGS_ASSERT_UTF8_TO_BYTES;
2461     PERL_UNUSED_CONTEXT;
2462
2463     /* This is a no-op if no variants at all in the input */
2464     if (is_utf8_invariant_string_loc(s, *lenp, (const U8 **) &first_variant)) {
2465         return s;
2466     }
2467
2468     {
2469         U8 * const save = s;
2470         U8 * const send = s + *lenp;
2471         U8 * d;
2472
2473         /* Nothing before the first variant needs to be changed, so start the real
2474          * work there */
2475         s = first_variant;
2476         while (s < send) {
2477             if (! UTF8_IS_INVARIANT(*s)) {
2478                 if (! UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(s, send)) {
2479                     *lenp = ((STRLEN) -1);
2480                     return 0;
2481                 }
2482                 s++;
2483             }
2484             s++;
2485         }
2486
2487         /* Is downgradable, so do it */
2488         d = s = first_variant;
2489         while (s < send) {
2490             U8 c = *s++;
2491             if (! UVCHR_IS_INVARIANT(c)) {
2492                 /* Then it is two-byte encoded */
2493                 c = EIGHT_BIT_UTF8_TO_NATIVE(c, *s);
2494                 s++;
2495             }
2496             *d++ = c;
2497         }
2498         *d = '\0';
2499         *lenp = d - save;
2500
2501         return save;
2502     }
2503 }
2504
2505 /*
2506 =for apidoc bytes_from_utf8
2507
2508 Converts a potentially UTF-8 encoded string C<s> of length C<*lenp> into native
2509 byte encoding.  On input, the boolean C<*is_utf8p> gives whether or not C<s> is
2510 actually encoded in UTF-8.
2511
2512 Unlike L</utf8_to_bytes> but like L</bytes_to_utf8>, this is non-destructive of
2513 the input string.
2514
2515 Do nothing if C<*is_utf8p> is 0, or if there are code points in the string
2516 not expressible in native byte encoding.  In these cases, C<*is_utf8p> and
2517 C<*lenp> are unchanged, and the return value is the original C<s>.
2518
2519 Otherwise, C<*is_utf8p> is set to 0, and the return value is a pointer to a
2520 newly created string containing a downgraded copy of C<s>, and whose length is
2521 returned in C<*lenp>, updated.  The new string is C<NUL>-terminated.  The
2522 caller is responsible for arranging for the memory used by this string to get
2523 freed.
2524
2525 Upon successful return, the number of variants in the string can be computed by
2526 having saved the value of C<*lenp> before the call, and subtracting the
2527 after-call value of C<*lenp> from it.
2528
2529 =cut
2530
2531 There is a macro that avoids this function call, but this is retained for
2532 anyone who calls it with the Perl_ prefix */
2533
2534 U8 *
2535 Perl_bytes_from_utf8(pTHX_ const U8 *s, STRLEN *lenp, bool *is_utf8p)
2536 {
2537     PERL_ARGS_ASSERT_BYTES_FROM_UTF8;
2538     PERL_UNUSED_CONTEXT;
2539
2540     return bytes_from_utf8_loc(s, lenp, is_utf8p, NULL);
2541 }
2542
2543 /*
2544 =for apidoc bytes_from_utf8_loc
2545
2546 Like C<L<perlapi/bytes_from_utf8>()>, but takes an extra parameter, a pointer
2547 to where to store the location of the first character in C<"s"> that cannot be
2548 converted to non-UTF8.
2549
2550 If that parameter is C<NULL>, this function behaves identically to
2551 C<bytes_from_utf8>.
2552
2553 Otherwise if C<*is_utf8p> is 0 on input, the function behaves identically to
2554 C<bytes_from_utf8>, except it also sets C<*first_non_downgradable> to C<NULL>.
2555
2556 Otherwise, the function returns a newly created C<NUL>-terminated string
2557 containing the non-UTF8 equivalent of the convertible first portion of
2558 C<"s">.  C<*lenp> is set to its length, not including the terminating C<NUL>.
2559 If the entire input string was converted, C<*is_utf8p> is set to a FALSE value,
2560 and C<*first_non_downgradable> is set to C<NULL>.
2561
2562 Otherwise, C<*first_non_downgradable> is set to point to the first byte of the
2563 first character in the original string that wasn't converted.  C<*is_utf8p> is
2564 unchanged.  Note that the new string may have length 0.
2565
2566 Another way to look at it is, if C<*first_non_downgradable> is non-C<NULL> and
2567 C<*is_utf8p> is TRUE, this function starts at the beginning of C<"s"> and
2568 converts as many characters in it as possible stopping at the first one it
2569 finds that can't be converted to non-UTF-8.  C<*first_non_downgradable> is
2570 set to point to that.  The function returns the portion that could be converted
2571 in a newly created C<NUL>-terminated string, and C<*lenp> is set to its length,
2572 not including the terminating C<NUL>.  If the very first character in the
2573 original could not be converted, C<*lenp> will be 0, and the new string will
2574 contain just a single C<NUL>.  If the entire input string was converted,
2575 C<*is_utf8p> is set to FALSE and C<*first_non_downgradable> is set to C<NULL>.
2576
2577 Upon successful return, the number of variants in the converted portion of the
2578 string can be computed by having saved the value of C<*lenp> before the call,
2579 and subtracting the after-call value of C<*lenp> from it.
2580
2581 =cut
2582
2583
2584 */
2585
2586 U8 *
2587 Perl_bytes_from_utf8_loc(const U8 *s, STRLEN *lenp, bool *is_utf8p, const U8** first_unconverted)
2588 {
2589     U8 *d;
2590     const U8 *original = s;
2591     U8 *converted_start;
2592     const U8 *send = s + *lenp;
2593
2594     PERL_ARGS_ASSERT_BYTES_FROM_UTF8_LOC;
2595
2596     if (! *is_utf8p) {
2597         if (first_unconverted) {
2598             *first_unconverted = NULL;
2599         }
2600
2601         return (U8 *) original;
2602     }
2603
2604     Newx(d, (*lenp) + 1, U8);
2605
2606     converted_start = d;
2607     while (s < send) {
2608         U8 c = *s++;
2609         if (! UTF8_IS_INVARIANT(c)) {
2610
2611             /* Then it is multi-byte encoded.  If the code point is above 0xFF,
2612              * have to stop now */
2613             if (UNLIKELY (! UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(s - 1, send))) {
2614                 if (first_unconverted) {
2615                     *first_unconverted = s - 1;
2616                     goto finish_and_return;
2617                 }
2618                 else {
2619                     Safefree(converted_start);
2620                     return (U8 *) original;
2621                 }
2622             }
2623
2624             c = EIGHT_BIT_UTF8_TO_NATIVE(c, *s);
2625             s++;
2626         }
2627         *d++ = c;
2628     }
2629
2630     /* Here, converted the whole of the input */
2631     *is_utf8p = FALSE;
2632     if (first_unconverted) {
2633         *first_unconverted = NULL;
2634     }
2635
2636   finish_and_return:
2637     *d = '\0';
2638     *lenp = d - converted_start;
2639
2640     /* Trim unused space */
2641     Renew(converted_start, *lenp + 1, U8);
2642
2643     return converted_start;
2644 }
2645
2646 /*
2647 =for apidoc bytes_to_utf8
2648
2649 Converts a string C<s> of length C<*lenp> bytes from the native encoding into
2650 UTF-8.
2651 Returns a pointer to the newly-created string, and sets C<*lenp> to
2652 reflect the new length in bytes.  The caller is responsible for arranging for
2653 the memory used by this string to get freed.
2654
2655 Upon successful return, the number of variants in the string can be computed by
2656 having saved the value of C<*lenp> before the call, and subtracting it from the
2657 after-call value of C<*lenp>.
2658
2659 A C<NUL> character will be written after the end of the string.
2660
2661 If you want to convert to UTF-8 from encodings other than
2662 the native (Latin1 or EBCDIC),
2663 see L</sv_recode_to_utf8>().
2664
2665 =cut
2666 */
2667
2668 U8*
2669 Perl_bytes_to_utf8(pTHX_ const U8 *s, STRLEN *lenp)
2670 {
2671     const U8 * const send = s + (*lenp);
2672     U8 *d;
2673     U8 *dst;
2674
2675     PERL_ARGS_ASSERT_BYTES_TO_UTF8;
2676     PERL_UNUSED_CONTEXT;
2677
2678     /* 1 for each byte + 1 for each byte that expands to two, + trailing NUL */
2679     Newx(d, (*lenp) + variant_under_utf8_count(s, send) + 1, U8);
2680     dst = d;
2681
2682     while (s < send) {
2683         append_utf8_from_native_byte(*s, &d);
2684         s++;
2685     }
2686
2687     *d = '\0';
2688     *lenp = d-dst;
2689
2690     return dst;
2691 }
2692
2693 /*
2694  * Convert native (big-endian) UTF-16 to UTF-8.  For reversed (little-endian),
2695  * use utf16_to_utf8_reversed().
2696  *
2697  * UTF-16 requires 2 bytes for every code point below 0x10000; otherwise 4 bytes.
2698  * UTF-8 requires 1-3 bytes for every code point below 0x1000; otherwise 4 bytes.
2699  * UTF-EBCDIC requires 1-4 bytes for every code point below 0x1000; otherwise 4-5 bytes.
2700  *
2701  * These functions don't check for overflow.  The worst case is every code
2702  * point in the input is 2 bytes, and requires 4 bytes on output.  (If the code
2703  * is never going to run in EBCDIC, it is 2 bytes requiring 3 on output.)  Therefore the
2704  * destination must be pre-extended to 2 times the source length.
2705  *
2706  * Do not use in-place.  We optimize for native, for obvious reasons. */
2707
2708 U8*
2709 Perl_utf16_to_utf8(pTHX_ U8* p, U8* d, Size_t bytelen, Size_t *newlen)
2710 {
2711     U8* pend;
2712     U8* dstart = d;
2713
2714     PERL_ARGS_ASSERT_UTF16_TO_UTF8;
2715
2716     if (bytelen & 1)
2717         Perl_croak(aTHX_ "panic: utf16_to_utf8: odd bytelen %" UVuf,
2718                                                                (UV)bytelen);
2719
2720     pend = p + bytelen;
2721
2722     while (p < pend) {
2723         UV uv = (p[0] << 8) + p[1]; /* UTF-16BE */
2724         p += 2;
2725         if (OFFUNI_IS_INVARIANT(uv)) {
2726             *d++ = LATIN1_TO_NATIVE((U8) uv);
2727             continue;
2728         }
2729         if (uv <= MAX_UTF8_TWO_BYTE) {
2730             *d++ = UTF8_TWO_BYTE_HI(UNI_TO_NATIVE(uv));
2731             *d++ = UTF8_TWO_BYTE_LO(UNI_TO_NATIVE(uv));
2732             continue;
2733         }
2734
2735 #define FIRST_HIGH_SURROGATE UNICODE_SURROGATE_FIRST
2736 #define LAST_HIGH_SURROGATE  0xDBFF
2737 #define FIRST_LOW_SURROGATE  0xDC00
2738 #define LAST_LOW_SURROGATE   UNICODE_SURROGATE_LAST
2739 #define FIRST_IN_PLANE1      0x10000
2740
2741         /* This assumes that most uses will be in the first Unicode plane, not
2742          * needing surrogates */
2743         if (UNLIKELY(inRANGE(uv, UNICODE_SURROGATE_FIRST,
2744                                  UNICODE_SURROGATE_LAST)))
2745         {
2746             if (UNLIKELY(p >= pend) || UNLIKELY(uv > LAST_HIGH_SURROGATE)) {
2747                 Perl_croak(aTHX_ "Malformed UTF-16 surrogate");
2748             }
2749             else {
2750                 UV low = (p[0] << 8) + p[1];
2751                 if (UNLIKELY(! inRANGE(low, FIRST_LOW_SURROGATE,
2752                                             LAST_LOW_SURROGATE)))
2753                 {
2754                     Perl_croak(aTHX_ "Malformed UTF-16 surrogate");
2755                 }
2756                 p += 2;
2757                 uv = ((uv - FIRST_HIGH_SURROGATE) << 10)
2758                                 + (low - FIRST_LOW_SURROGATE) + FIRST_IN_PLANE1;
2759             }
2760         }
2761 #ifdef EBCDIC
2762         d = uvoffuni_to_utf8_flags(d, uv, 0);
2763 #else
2764         if (uv < FIRST_IN_PLANE1) {
2765             *d++ = (U8)(( uv >> 12)         | 0xe0);
2766             *d++ = (U8)(((uv >>  6) & 0x3f) | 0x80);
2767             *d++ = (U8)(( uv        & 0x3f) | 0x80);
2768             continue;
2769         }
2770         else {
2771             *d++ = (U8)(( uv >> 18)         | 0xf0);
2772             *d++ = (U8)(((uv >> 12) & 0x3f) | 0x80);
2773             *d++ = (U8)(((uv >>  6) & 0x3f) | 0x80);
2774             *d++ = (U8)(( uv        & 0x3f) | 0x80);
2775             continue;
2776         }
2777 #endif
2778     }
2779     *newlen = d - dstart;
2780     return d;
2781 }
2782
2783 /* Note: this one is slightly destructive of the source. */
2784
2785 U8*
2786 Perl_utf16_to_utf8_reversed(pTHX_ U8* p, U8* d, Size_t bytelen, Size_t *newlen)
2787 {
2788     U8* s = (U8*)p;
2789     U8* const send = s + bytelen;
2790
2791     PERL_ARGS_ASSERT_UTF16_TO_UTF8_REVERSED;
2792
2793     if (bytelen & 1)
2794         Perl_croak(aTHX_ "panic: utf16_to_utf8_reversed: odd bytelen %" UVuf,
2795                    (UV)bytelen);
2796
2797     while (s < send) {
2798         const U8 tmp = s[0];
2799         s[0] = s[1];
2800         s[1] = tmp;
2801         s += 2;
2802     }
2803     return utf16_to_utf8(p, d, bytelen, newlen);
2804 }
2805
2806 bool
2807 Perl__is_uni_FOO(pTHX_ const U8 classnum, const UV c)
2808 {
2809     return _invlist_contains_cp(PL_XPosix_ptrs[classnum], c);
2810 }
2811
2812 bool
2813 Perl__is_uni_perl_idcont(pTHX_ UV c)
2814 {
2815     return _invlist_contains_cp(PL_utf8_perl_idcont, c);
2816 }
2817
2818 bool
2819 Perl__is_uni_perl_idstart(pTHX_ UV c)
2820 {
2821     return _invlist_contains_cp(PL_utf8_perl_idstart, c);
2822 }
2823
2824 UV
2825 Perl__to_upper_title_latin1(pTHX_ const U8 c, U8* p, STRLEN *lenp,
2826                                   const char S_or_s)
2827 {
2828     /* We have the latin1-range values compiled into the core, so just use
2829      * those, converting the result to UTF-8.  The only difference between upper
2830      * and title case in this range is that LATIN_SMALL_LETTER_SHARP_S is
2831      * either "SS" or "Ss".  Which one to use is passed into the routine in
2832      * 'S_or_s' to avoid a test */
2833
2834     UV converted = toUPPER_LATIN1_MOD(c);
2835
2836     PERL_ARGS_ASSERT__TO_UPPER_TITLE_LATIN1;
2837
2838     assert(S_or_s == 'S' || S_or_s == 's');
2839
2840     if (UVCHR_IS_INVARIANT(converted)) { /* No difference between the two for
2841                                              characters in this range */
2842         *p = (U8) converted;
2843         *lenp = 1;
2844         return converted;
2845     }
2846
2847     /* toUPPER_LATIN1_MOD gives the correct results except for three outliers,
2848      * which it maps to one of them, so as to only have to have one check for
2849      * it in the main case */
2850     if (UNLIKELY(converted == LATIN_SMALL_LETTER_Y_WITH_DIAERESIS)) {
2851         switch (c) {
2852             case LATIN_SMALL_LETTER_Y_WITH_DIAERESIS:
2853                 converted = LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS;
2854                 break;
2855             case MICRO_SIGN:
2856                 converted = GREEK_CAPITAL_LETTER_MU;
2857                 break;
2858 #if    UNICODE_MAJOR_VERSION > 2                                        \
2859    || (UNICODE_MAJOR_VERSION == 2 && UNICODE_DOT_VERSION >= 1           \
2860                                   && UNICODE_DOT_DOT_VERSION >= 8)
2861             case LATIN_SMALL_LETTER_SHARP_S:
2862                 *(p)++ = 'S';
2863                 *p = S_or_s;
2864                 *lenp = 2;
2865                 return 'S';
2866 #endif
2867             default:
2868                 Perl_croak(aTHX_ "panic: to_upper_title_latin1 did not expect"
2869                                  " '%c' to map to '%c'",
2870                                  c, LATIN_SMALL_LETTER_Y_WITH_DIAERESIS);
2871                 NOT_REACHED; /* NOTREACHED */
2872         }
2873     }
2874
2875     *(p)++ = UTF8_TWO_BYTE_HI(converted);
2876     *p = UTF8_TWO_BYTE_LO(converted);
2877     *lenp = 2;
2878
2879     return converted;
2880 }
2881
2882 /* If compiled on an early Unicode version, there may not be auxiliary tables
2883  * */
2884 #ifndef HAS_UC_AUX_TABLES
2885 #  define UC_AUX_TABLE_ptrs     NULL
2886 #  define UC_AUX_TABLE_lengths  NULL
2887 #endif
2888 #ifndef HAS_TC_AUX_TABLES
2889 #  define TC_AUX_TABLE_ptrs     NULL
2890 #  define TC_AUX_TABLE_lengths  NULL
2891 #endif
2892 #ifndef HAS_LC_AUX_TABLES
2893 #  define LC_AUX_TABLE_ptrs     NULL
2894 #  define LC_AUX_TABLE_lengths  NULL
2895 #endif
2896 #ifndef HAS_CF_AUX_TABLES
2897 #  define CF_AUX_TABLE_ptrs     NULL
2898 #  define CF_AUX_TABLE_lengths  NULL
2899 #endif
2900 #ifndef HAS_UC_AUX_TABLES
2901 #  define UC_AUX_TABLE_ptrs     NULL
2902 #  define UC_AUX_TABLE_lengths  NULL
2903 #endif
2904
2905 /* Call the function to convert a UTF-8 encoded character to the specified case.
2906  * Note that there may be more than one character in the result.
2907  * 's' is a pointer to the first byte of the input character
2908  * 'd' will be set to the first byte of the string of changed characters.  It
2909  *      needs to have space for UTF8_MAXBYTES_CASE+1 bytes
2910  * 'lenp' will be set to the length in bytes of the string of changed characters
2911  *
2912  * The functions return the ordinal of the first character in the string of
2913  * 'd' */
2914 #define CALL_UPPER_CASE(uv, s, d, lenp)                                     \
2915                 _to_utf8_case(uv, s, d, lenp, PL_utf8_toupper,              \
2916                                               Uppercase_Mapping_invmap,     \
2917                                               UC_AUX_TABLE_ptrs,            \
2918                                               UC_AUX_TABLE_lengths,         \
2919                                               "uppercase")
2920 #define CALL_TITLE_CASE(uv, s, d, lenp)                                     \
2921                 _to_utf8_case(uv, s, d, lenp, PL_utf8_totitle,              \
2922                                               Titlecase_Mapping_invmap,     \
2923                                               TC_AUX_TABLE_ptrs,            \
2924                                               TC_AUX_TABLE_lengths,         \
2925                                               "titlecase")
2926 #define CALL_LOWER_CASE(uv, s, d, lenp)                                     \
2927                 _to_utf8_case(uv, s, d, lenp, PL_utf8_tolower,              \
2928                                               Lowercase_Mapping_invmap,     \
2929                                               LC_AUX_TABLE_ptrs,            \
2930                                               LC_AUX_TABLE_lengths,         \
2931                                               "lowercase")
2932
2933
2934 /* This additionally has the input parameter 'specials', which if non-zero will
2935  * cause this to use the specials hash for folding (meaning get full case
2936  * folding); otherwise, when zero, this implies a simple case fold */
2937 #define CALL_FOLD_CASE(uv, s, d, lenp, specials)                            \
2938         (specials)                                                          \
2939         ?  _to_utf8_case(uv, s, d, lenp, PL_utf8_tofold,                    \
2940                                           Case_Folding_invmap,              \
2941                                           CF_AUX_TABLE_ptrs,                \
2942                                           CF_AUX_TABLE_lengths,             \
2943                                           "foldcase")                       \
2944         : _to_utf8_case(uv, s, d, lenp, PL_utf8_tosimplefold,               \
2945                                          Simple_Case_Folding_invmap,        \
2946                                          NULL, NULL,                        \
2947                                          "foldcase")
2948
2949 UV
2950 Perl_to_uni_upper(pTHX_ UV c, U8* p, STRLEN *lenp)
2951 {
2952     /* Convert the Unicode character whose ordinal is <c> to its uppercase
2953      * version and store that in UTF-8 in <p> and its length in bytes in <lenp>.
2954      * Note that the <p> needs to be at least UTF8_MAXBYTES_CASE+1 bytes since
2955      * the changed version may be longer than the original character.
2956      *
2957      * The ordinal of the first character of the changed version is returned
2958      * (but note, as explained above, that there may be more.) */
2959
2960     PERL_ARGS_ASSERT_TO_UNI_UPPER;
2961
2962     if (c < 256) {
2963         return _to_upper_title_latin1((U8) c, p, lenp, 'S');
2964     }
2965
2966     return CALL_UPPER_CASE(c, NULL, p, lenp);
2967 }
2968
2969 UV
2970 Perl_to_uni_title(pTHX_ UV c, U8* p, STRLEN *lenp)
2971 {
2972     PERL_ARGS_ASSERT_TO_UNI_TITLE;
2973
2974     if (c < 256) {
2975         return _to_upper_title_latin1((U8) c, p, lenp, 's');
2976     }
2977
2978     return CALL_TITLE_CASE(c, NULL, p, lenp);
2979 }
2980
2981 STATIC U8
2982 S_to_lower_latin1(const U8 c, U8* p, STRLEN *lenp, const char dummy)
2983 {
2984     /* We have the latin1-range values compiled into the core, so just use
2985      * those, converting the result to UTF-8.  Since the result is always just
2986      * one character, we allow <p> to be NULL */
2987
2988     U8 converted = toLOWER_LATIN1(c);
2989
2990     PERL_UNUSED_ARG(dummy);
2991
2992     if (p != NULL) {
2993         if (NATIVE_BYTE_IS_INVARIANT(converted)) {
2994             *p = converted;
2995             *lenp = 1;
2996         }
2997         else {
2998             /* Result is known to always be < 256, so can use the EIGHT_BIT
2999              * macros */
3000             *p = UTF8_EIGHT_BIT_HI(converted);
3001             *(p+1) = UTF8_EIGHT_BIT_LO(converted);
3002             *lenp = 2;
3003         }
3004     }
3005     return converted;
3006 }
3007
3008 UV
3009 Perl_to_uni_lower(pTHX_ UV c, U8* p, STRLEN *lenp)
3010 {
3011     PERL_ARGS_ASSERT_TO_UNI_LOWER;
3012
3013     if (c < 256) {
3014         return to_lower_latin1((U8) c, p, lenp, 0 /* 0 is a dummy arg */ );
3015     }
3016
3017     return CALL_LOWER_CASE(c, NULL, p, lenp);
3018 }
3019
3020 UV
3021 Perl__to_fold_latin1(const U8 c, U8* p, STRLEN *lenp, const unsigned int flags)
3022 {
3023     /* Corresponds to to_lower_latin1(); <flags> bits meanings:
3024      *      FOLD_FLAGS_NOMIX_ASCII iff non-ASCII to ASCII folds are prohibited
3025      *      FOLD_FLAGS_FULL  iff full folding is to be used;
3026      *
3027      *  Not to be used for locale folds
3028      */
3029
3030     UV converted;
3031
3032     PERL_ARGS_ASSERT__TO_FOLD_LATIN1;
3033
3034     assert (! (flags & FOLD_FLAGS_LOCALE));
3035
3036     if (UNLIKELY(c == MICRO_SIGN)) {
3037         converted = GREEK_SMALL_LETTER_MU;
3038     }
3039 #if    UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */   \
3040    || (UNICODE_MAJOR_VERSION == 3 && (   UNICODE_DOT_VERSION > 0)       \
3041                                       || UNICODE_DOT_DOT_VERSION > 0)
3042     else if (   (flags & FOLD_FLAGS_FULL)
3043              && UNLIKELY(c == LATIN_SMALL_LETTER_SHARP_S))
3044     {
3045         /* If can't cross 127/128 boundary, can't return "ss"; instead return
3046          * two U+017F characters, as fc("\df") should eq fc("\x{17f}\x{17f}")
3047          * under those circumstances. */
3048         if (flags & FOLD_FLAGS_NOMIX_ASCII) {
3049             *lenp = 2 * sizeof(LATIN_SMALL_LETTER_LONG_S_UTF8) - 2;
3050             Copy(LATIN_SMALL_LETTER_LONG_S_UTF8 LATIN_SMALL_LETTER_LONG_S_UTF8,
3051                  p, *lenp, U8);
3052             return LATIN_SMALL_LETTER_LONG_S;
3053         }
3054         else {
3055             *(p)++ = 's';
3056             *p = 's';
3057             *lenp = 2;
3058             return 's';
3059         }
3060     }
3061 #endif
3062     else { /* In this range the fold of all other characters is their lower
3063               case */
3064         converted = toLOWER_LATIN1(c);
3065     }
3066
3067     if (UVCHR_IS_INVARIANT(converted)) {
3068         *p = (U8) converted;
3069         *lenp = 1;
3070     }
3071     else {
3072         *(p)++ = UTF8_TWO_BYTE_HI(converted);
3073         *p = UTF8_TWO_BYTE_LO(converted);
3074         *lenp = 2;
3075     }
3076
3077     return converted;
3078 }
3079
3080 UV
3081 Perl__to_uni_fold_flags(pTHX_ UV c, U8* p, STRLEN *lenp, U8 flags)
3082 {
3083
3084     /* Not currently externally documented, and subject to change
3085      *  <flags> bits meanings:
3086      *      FOLD_FLAGS_FULL  iff full folding is to be used;
3087      *      FOLD_FLAGS_LOCALE is set iff the rules from the current underlying
3088      *                        locale are to be used.
3089      *      FOLD_FLAGS_NOMIX_ASCII iff non-ASCII to ASCII folds are prohibited
3090      */
3091
3092     PERL_ARGS_ASSERT__TO_UNI_FOLD_FLAGS;
3093
3094     if (flags & FOLD_FLAGS_LOCALE) {
3095         /* Treat a non-Turkic UTF-8 locale as not being in locale at all,
3096          * except for potentially warning */
3097         _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
3098         if (IN_UTF8_CTYPE_LOCALE && ! PL_in_utf8_turkic_locale) {
3099             flags &= ~FOLD_FLAGS_LOCALE;
3100         }
3101         else {
3102             goto needs_full_generality;
3103         }
3104     }
3105
3106     if (c < 256) {
3107         return _to_fold_latin1((U8) c, p, lenp,
3108                             flags & (FOLD_FLAGS_FULL | FOLD_FLAGS_NOMIX_ASCII));
3109     }
3110
3111     /* Here, above 255.  If no special needs, just use the macro */
3112     if ( ! (flags & (FOLD_FLAGS_LOCALE|FOLD_FLAGS_NOMIX_ASCII))) {
3113         return CALL_FOLD_CASE(c, NULL, p, lenp, flags & FOLD_FLAGS_FULL);
3114     }
3115     else {  /* Otherwise, _toFOLD_utf8_flags has the intelligence to deal with
3116                the special flags. */
3117         U8 utf8_c[UTF8_MAXBYTES + 1];
3118
3119       needs_full_generality:
3120         uvchr_to_utf8(utf8_c, c);
3121         return _toFOLD_utf8_flags(utf8_c, utf8_c + sizeof(utf8_c),
3122                                   p, lenp, flags);
3123     }
3124 }
3125
3126 PERL_STATIC_INLINE bool
3127 S_is_utf8_common(pTHX_ const U8 *const p, const U8 * const e,
3128                        SV* const invlist)
3129 {
3130     /* returns a boolean giving whether or not the UTF8-encoded character that
3131      * starts at <p>, and extending no further than <e - 1> is in the inversion
3132      * list <invlist>. */
3133
3134     UV cp = utf8n_to_uvchr(p, e - p, NULL, 0);
3135
3136     PERL_ARGS_ASSERT_IS_UTF8_COMMON;
3137
3138     if (cp == 0 && (p >= e || *p != '\0')) {
3139         _force_out_malformed_utf8_message(p, e, 0, 1);
3140         NOT_REACHED; /* NOTREACHED */
3141     }
3142
3143     assert(invlist);
3144     return _invlist_contains_cp(invlist, cp);
3145 }
3146
3147 #if 0   /* Not currently used, but may be needed in the future */
3148 PERLVAR(I, seen_deprecated_macro, HV *)
3149
3150 STATIC void
3151 S_warn_on_first_deprecated_use(pTHX_ const char * const name,
3152                                      const char * const alternative,
3153                                      const bool use_locale,
3154                                      const char * const file,
3155                                      const unsigned line)
3156 {
3157     const char * key;
3158
3159     PERL_ARGS_ASSERT_WARN_ON_FIRST_DEPRECATED_USE;
3160
3161     if (ckWARN_d(WARN_DEPRECATED)) {
3162
3163         key = Perl_form(aTHX_ "%s;%d;%s;%d", name, use_locale, file, line);
3164         if (! hv_fetch(PL_seen_deprecated_macro, key, strlen(key), 0)) {
3165             if (! PL_seen_deprecated_macro) {
3166                 PL_seen_deprecated_macro = newHV();
3167             }
3168             if (! hv_store(PL_seen_deprecated_macro, key,
3169                            strlen(key), &PL_sv_undef, 0))
3170             {
3171                 Perl_croak(aTHX_ "panic: hv_store() unexpectedly failed");
3172             }
3173
3174             if (instr(file, "mathoms.c")) {
3175                 Perl_warner(aTHX_ WARN_DEPRECATED,
3176                             "In %s, line %d, starting in Perl v5.32, %s()"
3177                             " will be removed.  Avoid this message by"
3178                             " converting to use %s().\n",
3179                             file, line, name, alternative);
3180             }
3181             else {
3182                 Perl_warner(aTHX_ WARN_DEPRECATED,
3183                             "In %s, line %d, starting in Perl v5.32, %s() will"
3184                             " require an additional parameter.  Avoid this"
3185                             " message by converting to use %s().\n",
3186                             file, line, name, alternative);
3187             }
3188         }
3189     }
3190 }
3191 #endif
3192
3193 bool
3194 Perl__is_utf8_FOO(pTHX_ const U8 classnum, const U8 *p, const U8 * const e)
3195 {
3196     PERL_ARGS_ASSERT__IS_UTF8_FOO;
3197
3198     return is_utf8_common(p, e, PL_XPosix_ptrs[classnum]);
3199 }
3200
3201 bool
3202 Perl__is_utf8_perl_idstart(pTHX_ const U8 *p, const U8 * const e)
3203 {
3204     PERL_ARGS_ASSERT__IS_UTF8_PERL_IDSTART;
3205
3206     return is_utf8_common(p, e, PL_utf8_perl_idstart);
3207 }
3208
3209 bool
3210 Perl__is_utf8_perl_idcont(pTHX_ const U8 *p, const U8 * const e)
3211 {
3212     PERL_ARGS_ASSERT__IS_UTF8_PERL_IDCONT;
3213
3214     return is_utf8_common(p, e, PL_utf8_perl_idcont);
3215 }
3216
3217 STATIC UV
3218 S__to_utf8_case(pTHX_ const UV uv1, const U8 *p,
3219                       U8* ustrp, STRLEN *lenp,
3220                       SV *invlist, const I32 * const invmap,
3221                       const U32 * const * const aux_tables,
3222                       const U8 * const aux_table_lengths,
3223                       const char * const normal)
3224 {
3225     STRLEN len = 0;
3226
3227     /* Change the case of code point 'uv1' whose UTF-8 representation (assumed
3228      * by this routine to be valid) begins at 'p'.  'normal' is a string to use
3229      * to name the new case in any generated messages, as a fallback if the
3230      * operation being used is not available.  The new case is given by the
3231      * data structures in the remaining arguments.
3232      *
3233      * On return 'ustrp' points to '*lenp' UTF-8 encoded bytes representing the
3234      * entire changed case string, and the return value is the first code point
3235      * in that string */
3236
3237     PERL_ARGS_ASSERT__TO_UTF8_CASE;
3238
3239     /* For code points that don't change case, we already know that the output
3240      * of this function is the unchanged input, so we can skip doing look-ups
3241      * for them.  Unfortunately the case-changing code points are scattered
3242      * around.  But there are some long consecutive ranges where there are no
3243      * case changing code points.  By adding tests, we can eliminate the lookup
3244      * for all the ones in such ranges.  This is currently done here only for
3245      * just a few cases where the scripts are in common use in modern commerce
3246      * (and scripts adjacent to those which can be included without additional
3247      * tests). */
3248
3249     if (uv1 >= 0x0590) {
3250         /* This keeps from needing further processing the code points most
3251          * likely to be used in the following non-cased scripts: Hebrew,
3252          * Arabic, Syriac, Thaana, NKo, Samaritan, Mandaic, Devanagari,
3253          * Bengali, Gurmukhi, Gujarati, Oriya, Tamil, Telugu, Kannada,
3254          * Malayalam, Sinhala, Thai, Lao, Tibetan, Myanmar */
3255         if (uv1 < 0x10A0) {
3256             goto cases_to_self;
3257         }
3258
3259         /* The following largish code point ranges also don't have case
3260          * changes, but khw didn't think they warranted extra tests to speed
3261          * them up (which would slightly slow down everything else above them):
3262          * 1100..139F   Hangul Jamo, Ethiopic
3263          * 1400..1CFF   Unified Canadian Aboriginal Syllabics, Ogham, Runic,
3264          *              Tagalog, Hanunoo, Buhid, Tagbanwa, Khmer, Mongolian,
3265          *              Limbu, Tai Le, New Tai Lue, Buginese, Tai Tham,
3266          *              Combining Diacritical Marks Extended, Balinese,
3267          *              Sundanese, Batak, Lepcha, Ol Chiki
3268          * 2000..206F   General Punctuation
3269          */
3270
3271         if (uv1 >= 0x2D30) {
3272
3273             /* This keeps the from needing further processing the code points
3274              * most likely to be used in the following non-cased major scripts:
3275              * CJK, Katakana, Hiragana, plus some less-likely scripts.
3276              *
3277              * (0x2D30 above might have to be changed to 2F00 in the unlikely
3278              * event that Unicode eventually allocates the unused block as of
3279              * v8.0 2FE0..2FEF to code points that are cased.  khw has verified
3280              * that the test suite will start having failures to alert you
3281              * should that happen) */
3282             if (uv1 < 0xA640) {
3283                 goto cases_to_self;
3284             }
3285
3286             if (uv1 >= 0xAC00) {
3287                 if (UNLIKELY(UNICODE_IS_SURROGATE(uv1))) {
3288                     if (ckWARN_d(WARN_SURROGATE)) {
3289                         const char* desc = (PL_op) ? OP_DESC(PL_op) : normal;
3290                         Perl_warner(aTHX_ packWARN(WARN_SURROGATE),
3291                             "Operation \"%s\" returns its argument for"
3292                             " UTF-16 surrogate U+%04" UVXf, desc, uv1);
3293                     }
3294                     goto cases_to_self;
3295                 }
3296
3297                 /* AC00..FAFF Catches Hangul syllables and private use, plus
3298                  * some others */
3299                 if (uv1 < 0xFB00) {
3300                     goto cases_to_self;
3301                 }
3302
3303                 if (UNLIKELY(UNICODE_IS_SUPER(uv1))) {
3304                     if (UNLIKELY(uv1 > MAX_LEGAL_CP)) {
3305                         Perl_croak(aTHX_ "%s", form_cp_too_large_msg(16, NULL, 0, uv1));
3306                     }
3307                     if (ckWARN_d(WARN_NON_UNICODE)) {
3308                         const char* desc = (PL_op) ? OP_DESC(PL_op) : normal;
3309                         Perl_warner(aTHX_ packWARN(WARN_NON_UNICODE),
3310                             "Operation \"%s\" returns its argument for"
3311                             " non-Unicode code point 0x%04" UVXf, desc, uv1);
3312                     }
3313                     goto cases_to_self;
3314                 }
3315 #ifdef HIGHEST_CASE_CHANGING_CP_FOR_USE_ONLY_BY_UTF8_DOT_C
3316                 if (UNLIKELY(uv1
3317                     > HIGHEST_CASE_CHANGING_CP_FOR_USE_ONLY_BY_UTF8_DOT_C))
3318                 {
3319
3320                     goto cases_to_self;
3321                 }
3322 #endif
3323             }
3324         }
3325
3326         /* Note that non-characters are perfectly legal, so no warning should
3327          * be given. */
3328     }
3329
3330     {
3331         unsigned int i;
3332         const U32 * cp_list;
3333         U8 * d;
3334
3335         /* 'index' is guaranteed to be non-negative, as this is an inversion
3336          * map that covers all possible inputs.  See [perl #133365] */
3337         SSize_t index = _invlist_search(invlist, uv1);
3338         I32 base = invmap[index];
3339
3340         /* The data structures are set up so that if 'base' is non-negative,
3341          * the case change is 1-to-1; and if 0, the change is to itself */
3342         if (base >= 0) {
3343             IV lc;
3344
3345             if (base == 0) {
3346                 goto cases_to_self;
3347             }
3348
3349             /* This computes, e.g. lc(H) as 'H - A + a', using the lc table */
3350             lc = base + uv1 - invlist_array(invlist)[index];
3351             *lenp = uvchr_to_utf8(ustrp, lc) - ustrp;
3352             return lc;
3353         }
3354
3355         /* Here 'base' is negative.  That means the mapping is 1-to-many, and
3356          * requires an auxiliary table look up.  abs(base) gives the index into
3357          * a list of such tables which points to the proper aux table.  And a
3358          * parallel list gives the length of each corresponding aux table. */
3359         cp_list = aux_tables[-base];
3360
3361         /* Create the string of UTF-8 from the mapped-to code points */
3362         d = ustrp;
3363         for (i = 0; i < aux_table_lengths[-base]; i++) {
3364             d = uvchr_to_utf8(d, cp_list[i]);
3365         }
3366         *d = '\0';
3367         *lenp = d - ustrp;
3368
3369         return cp_list[0];
3370     }
3371
3372     /* Here, there was no mapping defined, which means that the code point maps
3373      * to itself.  Return the inputs */
3374   cases_to_self:
3375     if (p) {
3376         len = UTF8SKIP(p);
3377         if (p != ustrp) {   /* Don't copy onto itself */
3378             Copy(p, ustrp, len, U8);
3379         }
3380         *lenp = len;
3381     }
3382     else {
3383         *lenp = uvchr_to_utf8(ustrp, uv1) - ustrp;
3384     }
3385
3386     return uv1;
3387
3388 }
3389
3390 Size_t
3391 Perl__inverse_folds(pTHX_ const UV cp, U32 * first_folds_to,
3392                           const U32 ** remaining_folds_to)
3393 {
3394     /* Returns the count of the number of code points that fold to the input
3395      * 'cp' (besides itself).
3396      *
3397      * If the return is 0, there is nothing else that folds to it, and
3398      * '*first_folds_to' is set to 0, and '*remaining_folds_to' is set to NULL.
3399      *
3400      * If the return is 1, '*first_folds_to' is set to the single code point,
3401      * and '*remaining_folds_to' is set to NULL.
3402      *
3403      * Otherwise, '*first_folds_to' is set to a code point, and
3404      * '*remaining_fold_to' is set to an array that contains the others.  The
3405      * length of this array is the returned count minus 1.
3406      *
3407      * The reason for this convolution is to avoid having to deal with
3408      * allocating and freeing memory.  The lists are already constructed, so
3409      * the return can point to them, but single code points aren't, so would
3410      * need to be constructed if we didn't employ something like this API
3411      *
3412      * The code points returned by this function are all legal Unicode, which
3413      * occupy at most 21 bits, and so a U32 is sufficient, and the lists are
3414      * constructed with this size (to save space and memory), and we return
3415      * pointers, so they must be this size */
3416
3417     /* 'index' is guaranteed to be non-negative, as this is an inversion map
3418      * that covers all possible inputs.  See [perl #133365] */
3419     SSize_t index = _invlist_search(PL_utf8_foldclosures, cp);
3420     I32 base = _Perl_IVCF_invmap[index];
3421
3422     PERL_ARGS_ASSERT__INVERSE_FOLDS;
3423
3424     if (base == 0) {            /* No fold */
3425         *first_folds_to = 0;
3426         *remaining_folds_to = NULL;
3427         return 0;
3428     }
3429
3430 #ifndef HAS_IVCF_AUX_TABLES     /* This Unicode version only has 1-1 folds */
3431
3432     assert(base > 0);
3433
3434 #else
3435
3436     if (UNLIKELY(base < 0)) {   /* Folds to more than one character */
3437
3438         /* The data structure is set up so that the absolute value of 'base' is
3439          * an index into a table of pointers to arrays, with the array
3440          * corresponding to the index being the list of code points that fold
3441          * to 'cp', and the parallel array containing the length of the list
3442          * array */
3443         *first_folds_to = IVCF_AUX_TABLE_ptrs[-base][0];
3444         *remaining_folds_to = IVCF_AUX_TABLE_ptrs[-base] + 1;
3445                                                 /* +1 excludes first_folds_to */
3446         return IVCF_AUX_TABLE_lengths[-base];
3447     }
3448
3449 #endif
3450
3451     /* Only the single code point.  This works like 'fc(G) = G - A + a' */
3452     *first_folds_to = (U32) (base + cp
3453                                   - invlist_array(PL_utf8_foldclosures)[index]);
3454     *remaining_folds_to = NULL;
3455     return 1;
3456 }
3457
3458 STATIC UV
3459 S_check_locale_boundary_crossing(pTHX_ const U8* const p, const UV result,
3460                                        U8* const ustrp, STRLEN *lenp)
3461 {
3462     /* This is called when changing the case of a UTF-8-encoded character above
3463      * the Latin1 range, and the operation is in a non-UTF-8 locale.  If the
3464      * result contains a character that crosses the 255/256 boundary, disallow
3465      * the change, and return the original code point.  See L<perlfunc/lc> for
3466      * why;
3467      *
3468      * p        points to the original string whose case was changed; assumed
3469      *          by this routine to be well-formed
3470      * result   the code point of the first character in the changed-case string
3471      * ustrp    points to the changed-case string (<result> represents its
3472      *          first char)
3473      * lenp     points to the length of <ustrp> */
3474
3475     UV original;    /* To store the first code point of <p> */
3476
3477     PERL_ARGS_ASSERT_CHECK_LOCALE_BOUNDARY_CROSSING;
3478
3479     assert(UTF8_IS_ABOVE_LATIN1(*p));
3480
3481     /* We know immediately if the first character in the string crosses the
3482      * boundary, so can skip testing */
3483     if (result > 255) {
3484
3485         /* Look at every character in the result; if any cross the
3486         * boundary, the whole thing is disallowed */
3487         U8* s = ustrp + UTF8SKIP(ustrp);
3488         U8* e = ustrp + *lenp;
3489         while (s < e) {
3490             if (! UTF8_IS_ABOVE_LATIN1(*s)) {
3491                 goto bad_crossing;
3492             }
3493             s += UTF8SKIP(s);
3494         }
3495
3496         /* Here, no characters crossed, result is ok as-is, but we warn. */
3497         _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(p, p + UTF8SKIP(p));
3498         return result;
3499     }
3500
3501   bad_crossing:
3502
3503     /* Failed, have to return the original */
3504     original = valid_utf8_to_uvchr(p, lenp);
3505
3506     /* diag_listed_as: Can't do %s("%s") on non-UTF-8 locale; resolved to "%s". */
3507     Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
3508                            "Can't do %s(\"\\x{%" UVXf "}\") on non-UTF-8"
3509                            " locale; resolved to \"\\x{%" UVXf "}\".",
3510                            OP_DESC(PL_op),
3511                            original,
3512                            original);
3513     Copy(p, ustrp, *lenp, char);
3514     return original;
3515 }
3516
3517 STATIC UV
3518 S_turkic_fc(pTHX_ const U8 * const p, const U8 * const e,
3519                         U8 * ustrp, STRLEN *lenp)
3520 {
3521     /* Returns 0 if the foldcase of the input UTF-8 encoded sequence from
3522      * p0..e-1 according to Turkic rules is the same as for non-Turkic.
3523      * Otherwise, it returns the first code point of the Turkic foldcased
3524      * sequence, and the entire sequence will be stored in *ustrp.  ustrp will
3525      * contain *lenp bytes
3526      *
3527      * Turkic differs only from non-Turkic in that 'i' and LATIN CAPITAL LETTER
3528      * I WITH DOT ABOVE form a case pair, as do 'I' and LATIN SMALL LETTER
3529      * DOTLESS I */
3530
3531     PERL_ARGS_ASSERT_TURKIC_FC;
3532     assert(e > p);
3533
3534     if (UNLIKELY(*p == 'I')) {
3535         *lenp = 2;
3536         ustrp[0] = UTF8_TWO_BYTE_HI(LATIN_SMALL_LETTER_DOTLESS_I);
3537         ustrp[1] = UTF8_TWO_BYTE_LO(LATIN_SMALL_LETTER_DOTLESS_I);
3538         return LATIN_SMALL_LETTER_DOTLESS_I;
3539     }
3540
3541     if (UNLIKELY(memBEGINs(p, e - p,
3542                            LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE_UTF8)))
3543     {
3544         *lenp = 1;
3545         *ustrp = 'i';
3546         return 'i';
3547     }
3548
3549     return 0;
3550 }
3551
3552 STATIC UV
3553 S_turkic_lc(pTHX_ const U8 * const p0, const U8 * const e,
3554                         U8 * ustrp, STRLEN *lenp)
3555 {
3556     /* Returns 0 if the lowercase of the input UTF-8 encoded sequence from
3557      * p0..e-1 according to Turkic rules is the same as for non-Turkic.
3558      * Otherwise, it returns the first code point of the Turkic lowercased
3559      * sequence, and the entire sequence will be stored in *ustrp.  ustrp will
3560      * contain *lenp bytes */
3561
3562     PERL_ARGS_ASSERT_TURKIC_LC;
3563     assert(e > p0);
3564
3565     /* A 'I' requires context as to what to do */
3566     if (UNLIKELY(*p0 == 'I')) {
3567         const U8 * p = p0 + 1;
3568
3569         /* According to the Unicode SpecialCasing.txt file, a capital 'I'
3570          * modified by a dot above lowercases to 'i' even in turkic locales. */
3571         while (p < e) {
3572             UV cp;
3573
3574             if (memBEGINs(p, e - p, COMBINING_DOT_ABOVE_UTF8)) {
3575                 ustrp[0] = 'i';
3576                 *lenp = 1;
3577                 return 'i';
3578             }
3579
3580             /* For the dot above to modify the 'I', it must be part of a
3581              * combining sequence immediately following the 'I', and no other
3582              * modifier with a ccc of 230 may intervene */
3583             cp = utf8_to_uvchr_buf(p, e, NULL);
3584             if (! _invlist_contains_cp(PL_CCC_non0_non230, cp)) {
3585                 break;
3586             }
3587
3588             /* Here the combining sequence continues */
3589             p += UTF8SKIP(p);
3590         }
3591     }
3592
3593     /* In all other cases the lc is the same as the fold */
3594     return turkic_fc(p0, e, ustrp, lenp);
3595 }
3596
3597 STATIC UV
3598 S_turkic_uc(pTHX_ const U8 * const p, const U8 * const e,
3599                         U8 * ustrp, STRLEN *lenp)
3600 {
3601     /* Returns 0 if the upper or title-case of the input UTF-8 encoded sequence
3602      * from p0..e-1 according to Turkic rules is the same as for non-Turkic.
3603      * Otherwise, it returns the first code point of the Turkic upper or
3604      * title-cased sequence, and the entire sequence will be stored in *ustrp.
3605      * ustrp will contain *lenp bytes
3606      *
3607      * Turkic differs only from non-Turkic in that 'i' and LATIN CAPITAL LETTER
3608      * I WITH DOT ABOVE form a case pair, as do 'I' and LATIN SMALL LETTER
3609      * DOTLESS I */
3610
3611     PERL_ARGS_ASSERT_TURKIC_UC;
3612     assert(e > p);
3613
3614     if (*p == 'i') {
3615         *lenp = 2;
3616         ustrp[0] = UTF8_TWO_BYTE_HI(LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE);
3617         ustrp[1] = UTF8_TWO_BYTE_LO(LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE);
3618         return LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE;
3619     }
3620
3621     if (memBEGINs(p, e - p, LATIN_SMALL_LETTER_DOTLESS_I_UTF8)) {
3622         *lenp = 1;
3623         *ustrp = 'I';
3624         return 'I';
3625     }
3626
3627     return 0;
3628 }
3629
3630 /* The process for changing the case is essentially the same for the four case
3631  * change types, except there are complications for folding.  Otherwise the
3632  * difference is only which case to change to.  To make sure that they all do
3633  * the same thing, the bodies of the functions are extracted out into the
3634  * following two macros.  The functions are written with the same variable
3635  * names, and these are known and used inside these macros.  It would be
3636  * better, of course, to have inline functions to do it, but since different
3637  * macros are called, depending on which case is being changed to, this is not
3638  * feasible in C (to khw's knowledge).  Two macros are created so that the fold
3639  * function can start with the common start macro, then finish with its special
3640  * handling; while the other three cases can just use the common end macro.
3641  *
3642  * The algorithm is to use the proper (passed in) macro or function to change
3643  * the case for code points that are below 256.  The macro is used if using
3644  * locale rules for the case change; the function if not.  If the code point is
3645  * above 255, it is computed from the input UTF-8, and another macro is called
3646  * to do the conversion.  If necessary, the output is converted to UTF-8.  If
3647  * using a locale, we have to check that the change did not cross the 255/256
3648  * boundary, see check_locale_boundary_crossing() for further details.
3649  *
3650  * The macros are split with the correct case change for the below-256 case
3651  * stored into 'result', and in the middle of an else clause for the above-255
3652  * case.  At that point in the 'else', 'result' is not the final result, but is
3653  * the input code point calculated from the UTF-8.  The fold code needs to
3654  * realize all this and take it from there.
3655  *
3656  * To deal with Turkic locales, the function specified by the parameter
3657  * 'turkic' is called when appropriate.
3658  *
3659  * If you read the two macros as sequential, it's easier to understand what's
3660  * going on. */
3661 #define CASE_CHANGE_BODY_START(locale_flags, LC_L1_change_macro, L1_func,    \
3662                                L1_func_extra_param, turkic)                  \
3663                                                                              \
3664     if (flags & (locale_flags)) {                                            \
3665         _CHECK_AND_WARN_PROBLEMATIC_LOCALE;                                  \
3666         if (IN_UTF8_CTYPE_LOCALE) {                                          \
3667             if (UNLIKELY(PL_in_utf8_turkic_locale)) {                        \
3668                 UV ret = turkic(p, e, ustrp, lenp);                          \
3669                 if (ret) return ret;                                         \
3670             }                                                                \
3671                                                                              \
3672             /* Otherwise, treat a UTF-8 locale as not being in locale at     \
3673              * all */                                                        \
3674             flags &= ~(locale_flags);                                        \
3675         }                                                                    \
3676     }                                                                        \
3677                                                                              \
3678     if (UTF8_IS_INVARIANT(*p)) {                                             \
3679         if (flags & (locale_flags)) {                                        \
3680             result = LC_L1_change_macro(*p);                                 \
3681         }                                                                    \
3682         else {                                                               \
3683             return L1_func(*p, ustrp, lenp, L1_func_extra_param);            \
3684         }                                                                    \
3685     }                                                                        \
3686     else if UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(p, e) {                          \
3687         U8 c = EIGHT_BIT_UTF8_TO_NATIVE(*p, *(p+1));                         \
3688         if (flags & (locale_flags)) {                                        \
3689             result = LC_L1_change_macro(c);                                  \
3690         }                                                                    \
3691         else {                                                               \
3692             return L1_func(c, ustrp, lenp,  L1_func_extra_param);            \
3693         }                                                                    \
3694     }                                                                        \
3695     else {  /* malformed UTF-8 or ord above 255 */                           \
3696         STRLEN len_result;                                                   \
3697         result = utf8n_to_uvchr(p, e - p, &len_result, UTF8_CHECK_ONLY);     \
3698         if (len_result == (STRLEN) -1) {                                     \
3699             _force_out_malformed_utf8_message(p, e, 0, 1 /* Die */ );        \
3700         }
3701
3702 #define CASE_CHANGE_BODY_END(locale_flags, change_macro)                     \
3703         result = change_macro(result, p, ustrp, lenp);                       \
3704                                                                              \
3705         if (flags & (locale_flags)) {                                        \
3706             result = check_locale_boundary_crossing(p, result, ustrp, lenp); \
3707         }                                                                    \
3708         return result;                                                       \
3709     }                                                                        \
3710                                                                              \
3711     /* Here, used locale rules.  Convert back to UTF-8 */                    \
3712     if (UTF8_IS_INVARIANT(result)) {                                         \
3713         *ustrp = (U8) result;                                                \
3714         *lenp = 1;                                                           \
3715     }                                                                        \
3716     else {                                                                   \
3717         *ustrp = UTF8_EIGHT_BIT_HI((U8) result);                             \
3718         *(ustrp + 1) = UTF8_EIGHT_BIT_LO((U8) result);                       \
3719         *lenp = 2;                                                           \
3720     }                                                                        \
3721                                                                              \
3722     return result;
3723
3724 /* Not currently externally documented, and subject to change:
3725  * <flags> is set iff the rules from the current underlying locale are to
3726  *         be used. */
3727
3728 UV
3729 Perl__to_utf8_upper_flags(pTHX_ const U8 *p,
3730                                 const U8 *e,
3731                                 U8* ustrp,
3732                                 STRLEN *lenp,
3733                                 bool flags)
3734 {
3735     UV result;
3736
3737     PERL_ARGS_ASSERT__TO_UTF8_UPPER_FLAGS;
3738
3739     /* ~0 makes anything non-zero in 'flags' mean we are using locale rules */
3740     /* 2nd char of uc(U+DF) is 'S' */
3741     CASE_CHANGE_BODY_START(~0, toUPPER_LC, _to_upper_title_latin1, 'S',
3742                                                                     turkic_uc);
3743     CASE_CHANGE_BODY_END  (~0, CALL_UPPER_CASE);
3744 }
3745
3746 /* Not currently externally documented, and subject to change:
3747  * <flags> is set iff the rules from the current underlying locale are to be
3748  *         used.  Since titlecase is not defined in POSIX, for other than a
3749  *         UTF-8 locale, uppercase is used instead for code points < 256.
3750  */
3751
3752 UV
3753 Perl__to_utf8_title_flags(pTHX_ const U8 *p,
3754                                 const U8 *e,
3755                                 U8* ustrp,
3756                                 STRLEN *lenp,
3757                                 bool flags)
3758 {
3759     UV result;
3760
3761     PERL_ARGS_ASSERT__TO_UTF8_TITLE_FLAGS;
3762
3763     /* 2nd char of ucfirst(U+DF) is 's' */
3764     CASE_CHANGE_BODY_START(~0, toUPPER_LC, _to_upper_title_latin1, 's',
3765                                                                     turkic_uc);
3766     CASE_CHANGE_BODY_END  (~0, CALL_TITLE_CASE);
3767 }
3768
3769 /* Not currently externally documented, and subject to change:
3770  * <flags> is set iff the rules from the current underlying locale are to
3771  *         be used.
3772  */
3773
3774 UV
3775 Perl__to_utf8_lower_flags(pTHX_ const U8 *p,
3776                                 const U8 *e,
3777                                 U8* ustrp,
3778                                 STRLEN *lenp,
3779                                 bool flags)
3780 {
3781     UV result;
3782
3783     PERL_ARGS_ASSERT__TO_UTF8_LOWER_FLAGS;
3784
3785     CASE_CHANGE_BODY_START(~0, toLOWER_LC, to_lower_latin1, 0 /* 0 is dummy */,
3786                                                                     turkic_lc);
3787     CASE_CHANGE_BODY_END  (~0, CALL_LOWER_CASE)
3788 }
3789
3790 /* Not currently externally documented, and subject to change,
3791  * in <flags>
3792  *      bit FOLD_FLAGS_LOCALE is set iff the rules from the current underlying
3793  *                            locale are to be used.
3794  *      bit FOLD_FLAGS_FULL   is set iff full case folds are to be used;
3795  *                            otherwise simple folds
3796  *      bit FOLD_FLAGS_NOMIX_ASCII is set iff folds of non-ASCII to ASCII are
3797  *                            prohibited
3798  */
3799
3800 UV
3801 Perl__to_utf8_fold_flags(pTHX_ const U8 *p,
3802                                const U8 *e,
3803                                U8* ustrp,
3804                                STRLEN *lenp,
3805                                U8 flags)
3806 {
3807     UV result;
3808
3809     PERL_ARGS_ASSERT__TO_UTF8_FOLD_FLAGS;
3810
3811     /* These are mutually exclusive */
3812     assert (! ((flags & FOLD_FLAGS_LOCALE) && (flags & FOLD_FLAGS_NOMIX_ASCII)));
3813
3814     assert(p != ustrp); /* Otherwise overwrites */
3815
3816     CASE_CHANGE_BODY_START(FOLD_FLAGS_LOCALE, toFOLD_LC, _to_fold_latin1,
3817                  ((flags) & (FOLD_FLAGS_FULL | FOLD_FLAGS_NOMIX_ASCII)),
3818                                                                     turkic_fc);
3819
3820         result = CALL_FOLD_CASE(result, p, ustrp, lenp, flags & FOLD_FLAGS_FULL);
3821
3822         if (flags & FOLD_FLAGS_LOCALE) {
3823
3824 #           define LONG_S_T      LATIN_SMALL_LIGATURE_LONG_S_T_UTF8
3825 #         ifdef LATIN_CAPITAL_LETTER_SHARP_S_UTF8
3826 #           define CAP_SHARP_S   LATIN_CAPITAL_LETTER_SHARP_S_UTF8
3827
3828             /* Special case these two characters, as what normally gets
3829              * returned under locale doesn't work */
3830             if (memBEGINs((char *) p, e - p, CAP_SHARP_S))
3831             {
3832                 /* diag_listed_as: Can't do %s("%s") on non-UTF-8 locale; resolved to "%s". */
3833                 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
3834                               "Can't do fc(\"\\x{1E9E}\") on non-UTF-8 locale; "
3835                               "resolved to \"\\x{17F}\\x{17F}\".");
3836                 goto return_long_s;
3837             }
3838             else
3839 #endif
3840                  if (memBEGINs((char *) p, e - p, LONG_S_T))
3841             {
3842                 /* diag_listed_as: Can't do %s("%s") on non-UTF-8 locale; resolved to "%s". */
3843                 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
3844                               "Can't do fc(\"\\x{FB05}\") on non-UTF-8 locale; "
3845                               "resolved to \"\\x{FB06}\".");
3846                 goto return_ligature_st;
3847             }
3848
3849 #if    UNICODE_MAJOR_VERSION   == 3         \
3850     && UNICODE_DOT_VERSION     == 0         \
3851     && UNICODE_DOT_DOT_VERSION == 1
3852 #           define DOTTED_I   LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE_UTF8
3853
3854             /* And special case this on this Unicode version only, for the same
3855              * reaons the other two are special cased.  They would cross the
3856              * 255/256 boundary which is forbidden under /l, and so the code
3857              * wouldn't catch that they are equivalent (which they are only in
3858              * this release) */
3859             else if (memBEGINs((char *) p, e - p, DOTTED_I)) {
3860                 /* diag_listed_as: Can't do %s("%s") on non-UTF-8 locale; resolved to "%s". */
3861                 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
3862                               "Can't do fc(\"\\x{0130}\") on non-UTF-8 locale; "
3863                               "resolved to \"\\x{0131}\".");
3864                 goto return_dotless_i;
3865             }
3866 #endif
3867
3868             return check_locale_boundary_crossing(p, result, ustrp, lenp);
3869         }
3870         else if (! (flags & FOLD_FLAGS_NOMIX_ASCII)) {
3871             return result;
3872         }
3873         else {
3874             /* This is called when changing the case of a UTF-8-encoded
3875              * character above the ASCII range, and the result should not
3876              * contain an ASCII character. */
3877
3878             UV original;    /* To store the first code point of <p> */
3879
3880             /* Look at every character in the result; if any cross the
3881             * boundary, the whole thing is disallowed */
3882             U8* s = ustrp;
3883             U8* send = ustrp + *lenp;
3884             while (s < send) {
3885                 if (isASCII(*s)) {
3886                     /* Crossed, have to return the original */
3887                     original = valid_utf8_to_uvchr(p, lenp);
3888
3889                     /* But in these instances, there is an alternative we can
3890                      * return that is valid */
3891                     if (original == LATIN_SMALL_LETTER_SHARP_S
3892 #ifdef LATIN_CAPITAL_LETTER_SHARP_S /* not defined in early Unicode releases */
3893                         || original == LATIN_CAPITAL_LETTER_SHARP_S
3894 #endif
3895                     ) {
3896                         goto return_long_s;
3897                     }
3898                     else if (original == LATIN_SMALL_LIGATURE_LONG_S_T) {
3899                         goto return_ligature_st;
3900                     }
3901 #if    UNICODE_MAJOR_VERSION   == 3         \
3902     && UNICODE_DOT_VERSION     == 0         \
3903     && UNICODE_DOT_DOT_VERSION == 1
3904
3905                     else if (original == LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE) {
3906                         goto return_dotless_i;
3907                     }
3908 #endif
3909                     Copy(p, ustrp, *lenp, char);
3910                     return original;
3911                 }
3912                 s += UTF8SKIP(s);
3913             }
3914
3915             /* Here, no characters crossed, result is ok as-is */
3916             return result;
3917         }
3918     }
3919
3920     /* Here, used locale rules.  Convert back to UTF-8 */
3921     if (UTF8_IS_INVARIANT(result)) {
3922         *ustrp = (U8) result;
3923         *lenp = 1;
3924     }
3925     else {
3926         *ustrp = UTF8_EIGHT_BIT_HI((U8) result);
3927         *(ustrp + 1) = UTF8_EIGHT_BIT_LO((U8) result);
3928         *lenp = 2;
3929     }
3930
3931     return result;
3932
3933   return_long_s:
3934     /* Certain folds to 'ss' are prohibited by the options, but they do allow
3935      * folds to a string of two of these characters.  By returning this
3936      * instead, then, e.g.,
3937      *      fc("\x{1E9E}") eq fc("\x{17F}\x{17F}")
3938      * works. */
3939
3940     *lenp = 2 * sizeof(LATIN_SMALL_LETTER_LONG_S_UTF8) - 2;
3941     Copy(LATIN_SMALL_LETTER_LONG_S_UTF8   LATIN_SMALL_LETTER_LONG_S_UTF8,
3942         ustrp, *lenp, U8);
3943     return LATIN_SMALL_LETTER_LONG_S;
3944
3945   return_ligature_st:
3946     /* Two folds to 'st' are prohibited by the options; instead we pick one and
3947      * have the other one fold to it */
3948
3949     *lenp = sizeof(LATIN_SMALL_LIGATURE_ST_UTF8) - 1;
3950     Copy(LATIN_SMALL_LIGATURE_ST_UTF8, ustrp, *lenp, U8);
3951     return LATIN_SMALL_LIGATURE_ST;
3952
3953 #if    UNICODE_MAJOR_VERSION   == 3         \
3954     && UNICODE_DOT_VERSION     == 0         \
3955     && UNICODE_DOT_DOT_VERSION == 1
3956
3957   return_dotless_i:
3958     *lenp = sizeof(LATIN_SMALL_LETTER_DOTLESS_I_UTF8) - 1;
3959     Copy(LATIN_SMALL_LETTER_DOTLESS_I_UTF8, ustrp, *lenp, U8);
3960     return LATIN_SMALL_LETTER_DOTLESS_I;
3961
3962 #endif
3963
3964 }
3965
3966 bool
3967 Perl_check_utf8_print(pTHX_ const U8* s, const STRLEN len)
3968 {
3969     /* May change: warns if surrogates, non-character code points, or
3970      * non-Unicode code points are in 's' which has length 'len' bytes.
3971      * Returns TRUE if none found; FALSE otherwise.  The only other validity
3972      * check is to make sure that this won't exceed the string's length nor
3973      * overflow */
3974
3975     const U8* const e = s + len;
3976     bool ok = TRUE;
3977
3978     PERL_ARGS_ASSERT_CHECK_UTF8_PRINT;
3979
3980     while (s < e) {
3981         if (UTF8SKIP(s) > len) {
3982             Perl_ck_warner_d(aTHX_ packWARN(WARN_UTF8),
3983                            "%s in %s", unees, PL_op ? OP_DESC(PL_op) : "print");
3984             return FALSE;
3985         }
3986         if (UNLIKELY(isUTF8_POSSIBLY_PROBLEMATIC(*s))) {
3987             if (UNLIKELY(UTF8_IS_SUPER(s, e))) {
3988                 if (   ckWARN_d(WARN_NON_UNICODE)
3989                     || UNLIKELY(0 < does_utf8_overflow(s, s + len,
3990                                                0 /* Don't consider overlongs */
3991                                                )))
3992                 {
3993                     /* A side effect of this function will be to warn */
3994                     (void) utf8n_to_uvchr(s, e - s, NULL, UTF8_WARN_SUPER);
3995                     ok = FALSE;
3996                 }
3997             }
3998             else if (UNLIKELY(UTF8_IS_SURROGATE(s, e))) {
3999                 if (ckWARN_d(WARN_SURROGATE)) {
4000                     /* This has a different warning than the one the called
4001                      * function would output, so can't just call it, unlike we
4002                      * do for the non-chars and above-unicodes */
4003                     UV uv = utf8_to_uvchr_buf(s, e, NULL);
4004                     Perl_warner(aTHX_ packWARN(WARN_SURROGATE),
4005                         "Unicode surrogate U+%04" UVXf " is illegal in UTF-8",
4006                                              uv);
4007                     ok = FALSE;
4008                 }
4009             }
4010             else if (   UNLIKELY(UTF8_IS_NONCHAR(s, e))
4011                      && (ckWARN_d(WARN_NONCHAR)))
4012             {
4013                 /* A side effect of this function will be to warn */
4014                 (void) utf8n_to_uvchr(s, e - s, NULL, UTF8_WARN_NONCHAR);
4015                 ok = FALSE;
4016             }
4017         }
4018         s += UTF8SKIP(s);
4019     }
4020
4021     return ok;
4022 }
4023
4024 /*
4025 =for apidoc pv_uni_display
4026
4027 Build to the scalar C<dsv> a displayable version of the UTF-8 encoded string
4028 C<spv>, length C<len>, the displayable version being at most C<pvlim> bytes
4029 long (if longer, the rest is truncated and C<"..."> will be appended).
4030
4031 The C<flags> argument can have C<UNI_DISPLAY_ISPRINT> set to display
4032 C<isPRINT()>able characters as themselves, C<UNI_DISPLAY_BACKSLASH>
4033 to display the C<\\[nrfta\\]> as the backslashed versions (like C<"\n">)
4034 (C<UNI_DISPLAY_BACKSLASH> is preferred over C<UNI_DISPLAY_ISPRINT> for C<"\\">).
4035 C<UNI_DISPLAY_QQ> (and its alias C<UNI_DISPLAY_REGEX>) have both
4036 C<UNI_DISPLAY_BACKSLASH> and C<UNI_DISPLAY_ISPRINT> turned on.
4037
4038 Additionally, there is now C<UNI_DISPLAY_BACKSPACE> which allows C<\b> for a
4039 backspace, but only when C<UNI_DISPLAY_BACKSLASH> also is set.
4040
4041 The pointer to the PV of the C<dsv> is returned.
4042
4043 See also L</sv_uni_display>.
4044
4045 =cut */
4046 char *
4047 Perl_pv_uni_display(pTHX_ SV *dsv, const U8 *spv, STRLEN len, STRLEN pvlim,
4048                           UV flags)
4049 {
4050     int truncated = 0;
4051     const char *s, *e;
4052
4053     PERL_ARGS_ASSERT_PV_UNI_DISPLAY;
4054
4055     SvPVCLEAR(dsv);
4056     SvUTF8_off(dsv);
4057     for (s = (const char *)spv, e = s + len; s < e; s += UTF8SKIP(s)) {
4058          UV u;
4059          bool ok = 0;
4060
4061          if (pvlim && SvCUR(dsv) >= pvlim) {
4062               truncated++;
4063               break;
4064          }
4065          u = utf8_to_uvchr_buf((U8*)s, (U8*)e, 0);
4066          if (u < 256) {
4067              const unsigned char c = (unsigned char)u & 0xFF;
4068              if (flags & UNI_DISPLAY_BACKSLASH) {
4069                  if (    isMNEMONIC_CNTRL(c)
4070                      && (   c != '\b'
4071                          || (flags & UNI_DISPLAY_BACKSPACE)))
4072                  {
4073                     const char * mnemonic = cntrl_to_mnemonic(c);
4074                     sv_catpvn(dsv, mnemonic, strlen(mnemonic));
4075                     ok = 1;
4076                  }
4077                  else if (c == '\\') {
4078                     sv_catpvs(dsv, "\\\\");
4079                     ok = 1;
4080                  }
4081              }
4082              /* isPRINT() is the locale-blind version. */
4083              if (!ok && (flags & UNI_DISPLAY_ISPRINT) && isPRINT(c)) {
4084                  const char string = c;
4085                  sv_catpvn(dsv, &string, 1);
4086                  ok = 1;
4087              }
4088          }
4089          if (!ok)
4090              Perl_sv_catpvf(aTHX_ dsv, "\\x{%" UVxf "}", u);
4091     }
4092     if (truncated)
4093          sv_catpvs(dsv, "...");
4094
4095     return SvPVX(dsv);
4096 }
4097
4098 /*
4099 =for apidoc sv_uni_display
4100
4101 Build to the scalar C<dsv> a displayable version of the scalar C<sv>,
4102 the displayable version being at most C<pvlim> bytes long
4103 (if longer, the rest is truncated and "..." will be appended).
4104
4105 The C<flags> argument is as in L</pv_uni_display>().
4106
4107 The pointer to the PV of the C<dsv> is returned.
4108
4109 =cut
4110 */
4111 char *
4112 Perl_sv_uni_display(pTHX_ SV *dsv, SV *ssv, STRLEN pvlim, UV flags)
4113 {
4114     const char * const ptr =
4115         isREGEXP(ssv) ? RX_WRAPPED((REGEXP*)ssv) : SvPVX_const(ssv);
4116
4117     PERL_ARGS_ASSERT_SV_UNI_DISPLAY;
4118
4119     return Perl_pv_uni_display(aTHX_ dsv, (const U8*)ptr,
4120                                 SvCUR(ssv), pvlim, flags);
4121 }
4122
4123 /*
4124 =for apidoc foldEQ_utf8
4125
4126 Returns true if the leading portions of the strings C<s1> and C<s2> (either or
4127 both of which may be in UTF-8) are the same case-insensitively; false
4128 otherwise.  How far into the strings to compare is determined by other input
4129 parameters.
4130
4131 If C<u1> is true, the string C<s1> is assumed to be in UTF-8-encoded Unicode;
4132 otherwise it is assumed to be in native 8-bit encoding.  Correspondingly for
4133 C<u2> with respect to C<s2>.
4134
4135 If the byte length C<l1> is non-zero, it says how far into C<s1> to check for
4136 fold equality.  In other words, C<s1>+C<l1> will be used as a goal to reach.
4137 The scan will not be considered to be a match unless the goal is reached, and
4138 scanning won't continue past that goal.  Correspondingly for C<l2> with respect
4139 to C<s2>.
4140
4141 If C<pe1> is non-C<NULL> and the pointer it points to is not C<NULL>, that
4142 pointer is considered an end pointer to the position 1 byte past the maximum
4143 point in C<s1> beyond which scanning will not continue under any circumstances.
4144 (This routine assumes that UTF-8 encoded input strings are not malformed;
4145 malformed input can cause it to read past C<pe1>).  This means that if both
4146 C<l1> and C<pe1> are specified, and C<pe1> is less than C<s1>+C<l1>, the match
4147 will never be successful because it can never
4148 get as far as its goal (and in fact is asserted against).  Correspondingly for
4149 C<pe2> with respect to C<s2>.
4150
4151 At least one of C<s1> and C<s2> must have a goal (at least one of C<l1> and
4152 C<l2> must be non-zero), and if both do, both have to be
4153 reached for a successful match.   Also, if the fold of a character is multiple
4154 characters, all of them must be matched (see tr21 reference below for
4155 'folding').
4156
4157 Upon a successful match, if C<pe1> is non-C<NULL>,
4158 it will be set to point to the beginning of the I<next> character of C<s1>
4159 beyond what was matched.  Correspondingly for C<pe2> and C<s2>.
4160
4161 For case-insensitiveness, the "casefolding" of Unicode is used
4162 instead of upper/lowercasing both the characters, see
4163 L<https://www.unicode.org/unicode/reports/tr21/> (Case Mappings).
4164
4165 =cut */
4166
4167 /* A flags parameter has been added which may change, and hence isn't
4168  * externally documented.  Currently it is:
4169  *  0 for as-documented above
4170  *  FOLDEQ_UTF8_NOMIX_ASCII meaning that if a non-ASCII character folds to an
4171                             ASCII one, to not match
4172  *  FOLDEQ_LOCALE           is set iff the rules from the current underlying
4173  *                          locale are to be used.
4174  *  FOLDEQ_S1_ALREADY_FOLDED  s1 has already been folded before calling this
4175  *                          routine.  This allows that step to be skipped.
4176  *                          Currently, this requires s1 to be encoded as UTF-8
4177  *                          (u1 must be true), which is asserted for.
4178  *  FOLDEQ_S1_FOLDS_SANE    With either NOMIX_ASCII or LOCALE, no folds may
4179  *                          cross certain boundaries.  Hence, the caller should
4180  *                          let this function do the folding instead of
4181  *                          pre-folding.  This code contains an assertion to
4182  *                          that effect.  However, if the caller knows what
4183  *                          it's doing, it can pass this flag to indicate that,
4184  *                          and the assertion is skipped.
4185  *  FOLDEQ_S2_ALREADY_FOLDED  Similar to FOLDEQ_S1_ALREADY_FOLDED, but applies
4186  *                          to s2, and s2 doesn't have to be UTF-8 encoded.
4187  *                          This introduces an asymmetry to save a few branches
4188  *                          in a loop.  Currently, this is not a problem, as
4189  *                          never are both inputs pre-folded.  Simply call this
4190  *                          function with the pre-folded one as the second
4191  *                          string.
4192  *  FOLDEQ_S2_FOLDS_SANE
4193  */
4194 I32
4195 Perl_foldEQ_utf8_flags(pTHX_ const char *s1, char **pe1, UV l1, bool u1,
4196                              const char *s2, char **pe2, UV l2, bool u2,
4197                              U32 flags)
4198 {
4199     const U8 *p1  = (const U8*)s1; /* Point to current char */
4200     const U8 *p2  = (const U8*)s2;
4201     const U8 *g1 = NULL;       /* goal for s1 */
4202     const U8 *g2 = NULL;
4203     const U8 *e1 = NULL;       /* Don't scan s1 past this */
4204     U8 *f1 = NULL;             /* Point to current folded */
4205     const U8 *e2 = NULL;
4206     U8 *f2 = NULL;
4207     STRLEN n1 = 0, n2 = 0;              /* Number of bytes in current char */
4208     U8 foldbuf1[UTF8_MAXBYTES_CASE+1];
4209     U8 foldbuf2[UTF8_MAXBYTES_CASE+1];
4210     U8 flags_for_folder = FOLD_FLAGS_FULL;
4211
4212     PERL_ARGS_ASSERT_FOLDEQ_UTF8_FLAGS;
4213
4214     assert( ! (             (flags & (FOLDEQ_UTF8_NOMIX_ASCII | FOLDEQ_LOCALE))
4215                && ((        (flags &  FOLDEQ_S1_ALREADY_FOLDED)
4216                         && !(flags &  FOLDEQ_S1_FOLDS_SANE))
4217                     || (    (flags &  FOLDEQ_S2_ALREADY_FOLDED)
4218                         && !(flags &  FOLDEQ_S2_FOLDS_SANE)))));
4219     /* The algorithm is to trial the folds without regard to the flags on
4220      * the first line of the above assert(), and then see if the result
4221      * violates them.  This means that the inputs can't be pre-folded to a
4222      * violating result, hence the assert.  This could be changed, with the
4223      * addition of extra tests here for the already-folded case, which would
4224      * slow it down.  That cost is more than any possible gain for when these
4225      * flags are specified, as the flags indicate /il or /iaa matching which
4226      * is less common than /iu, and I (khw) also believe that real-world /il
4227      * and /iaa matches are most likely to involve code points 0-255, and this
4228      * function only under rare conditions gets called for 0-255. */
4229
4230     if (flags & FOLDEQ_LOCALE) {
4231         if (IN_UTF8_CTYPE_LOCALE) {
4232             if (UNLIKELY(PL_in_utf8_turkic_locale)) {
4233                 flags_for_folder |= FOLD_FLAGS_LOCALE;
4234             }
4235             else {
4236                 flags &= ~FOLDEQ_LOCALE;
4237             }
4238         }
4239         else {
4240             flags_for_folder |= FOLD_FLAGS_LOCALE;
4241         }
4242     }
4243     if (flags & FOLDEQ_UTF8_NOMIX_ASCII) {
4244         flags_for_folder |= FOLD_FLAGS_NOMIX_ASCII;
4245     }
4246
4247     if (pe1) {
4248         e1 = *(U8**)pe1;
4249     }
4250
4251     if (l1) {
4252         g1 = (const U8*)s1 + l1;
4253     }
4254
4255     if (pe2) {
4256         e2 = *(U8**)pe2;
4257     }
4258
4259     if (l2) {
4260         g2 = (const U8*)s2 + l2;
4261     }
4262
4263     /* Must have at least one goal */
4264     assert(g1 || g2);
4265
4266     if (g1) {
4267
4268         /* Will never match if goal is out-of-bounds */
4269         assert(! e1  || e1 >= g1);
4270
4271         /* Here, there isn't an end pointer, or it is beyond the goal.  We
4272         * only go as far as the goal */
4273         e1 = g1;
4274     }
4275     else {
4276         assert(e1);    /* Must have an end for looking at s1 */
4277     }
4278
4279     /* Same for goal for s2 */
4280     if (g2) {
4281         assert(! e2  || e2 >= g2);
4282         e2 = g2;
4283     }
4284     else {
4285         assert(e2);
4286     }
4287
4288     /* If both operands are already folded, we could just do a memEQ on the
4289      * whole strings at once, but it would be better if the caller realized
4290      * this and didn't even call us */
4291
4292     /* Look through both strings, a character at a time */
4293     while (p1 < e1 && p2 < e2) {
4294
4295         /* If at the beginning of a new character in s1, get its fold to use
4296          * and the length of the fold. */
4297         if (n1 == 0) {
4298             if (flags & FOLDEQ_S1_ALREADY_FOLDED) {
4299                 f1 = (U8 *) p1;
4300                 assert(u1);
4301                 n1 = UTF8SKIP(f1);
4302             }
4303             else {
4304                 if (isASCII(*p1) && ! (flags & FOLDEQ_LOCALE)) {
4305
4306                     /* We have to forbid mixing ASCII with non-ASCII if the
4307                      * flags so indicate.  And, we can short circuit having to
4308                      * call the general functions for this common ASCII case,
4309                      * all of whose non-locale folds are also ASCII, and hence
4310                      * UTF-8 invariants, so the UTF8ness of the strings is not
4311                      * relevant. */
4312                     if ((flags & FOLDEQ_UTF8_NOMIX_ASCII) && ! isASCII(*p2)) {
4313                         return 0;
4314                     }
4315                     n1 = 1;
4316                     *foldbuf1 = toFOLD(*p1);
4317                 }
4318                 else if (u1) {
4319                     _toFOLD_utf8_flags(p1, e1, foldbuf1, &n1, flags_for_folder);
4320                 }
4321                 else {  /* Not UTF-8, get UTF-8 fold */
4322                     _to_uni_fold_flags(*p1, foldbuf1, &n1, flags_for_folder);
4323                 }
4324                 f1 = foldbuf1;
4325             }
4326         }
4327
4328         if (n2 == 0) {    /* Same for s2 */
4329             if (flags & FOLDEQ_S2_ALREADY_FOLDED) {
4330
4331                 /* Point to the already-folded character.  But for non-UTF-8
4332                  * variants, convert to UTF-8 for the algorithm below */
4333                 if (UTF8_IS_INVARIANT(*p2)) {
4334                     f2 = (U8 *) p2;
4335                     n2 = 1;
4336                 }
4337                 else if (u2) {
4338                     f2 = (U8 *) p2;
4339                     n2 = UTF8SKIP(f2);
4340                 }
4341                 else {
4342                     foldbuf2[0] = UTF8_EIGHT_BIT_HI(*p2);
4343                     foldbuf2[1] = UTF8_EIGHT_BIT_LO(*p2);
4344                     f2 = foldbuf2;
4345                     n2 = 2;
4346                 }
4347             }
4348             else {
4349                 if (isASCII(*p2) && ! (flags & FOLDEQ_LOCALE)) {
4350                     if ((flags & FOLDEQ_UTF8_NOMIX_ASCII) && ! isASCII(*p1)) {
4351                         return 0;
4352                     }
4353                     n2 = 1;
4354                     *foldbuf2 = toFOLD(*p2);
4355                 }
4356                 else if (u2) {
4357                     _toFOLD_utf8_flags(p2, e2, foldbuf2, &n2, flags_for_folder);
4358                 }
4359                 else {
4360                     _to_uni_fold_flags(*p2, foldbuf2, &n2, flags_for_folder);
4361                 }
4362                 f2 = foldbuf2;
4363             }
4364         }
4365
4366         /* Here f1 and f2 point to the beginning of the strings to compare.
4367          * These strings are the folds of the next character from each input
4368          * string, stored in UTF-8. */
4369
4370         /* While there is more to look for in both folds, see if they
4371         * continue to match */
4372         while (n1 && n2) {
4373             U8 fold_length = UTF8SKIP(f1);
4374             if (fold_length != UTF8SKIP(f2)
4375                 || (fold_length == 1 && *f1 != *f2) /* Short circuit memNE
4376                                                        function call for single
4377                                                        byte */
4378                 || memNE((char*)f1, (char*)f2, fold_length))
4379             {
4380                 return 0; /* mismatch */
4381             }
4382
4383             /* Here, they matched, advance past them */
4384             n1 -= fold_length;
4385             f1 += fold_length;
4386             n2 -= fold_length;
4387             f2 += fold_length;
4388         }
4389
4390         /* When reach the end of any fold, advance the input past it */
4391         if (n1 == 0) {
4392             p1 += u1 ? UTF8SKIP(p1) : 1;
4393         }
4394         if (n2 == 0) {
4395             p2 += u2 ? UTF8SKIP(p2) : 1;
4396         }
4397     } /* End of loop through both strings */
4398
4399     /* A match is defined by each scan that specified an explicit length
4400     * reaching its final goal, and the other not having matched a partial
4401     * character (which can happen when the fold of a character is more than one
4402     * character). */
4403     if (! ((g1 == 0 || p1 == g1) && (g2 == 0 || p2 == g2)) || n1 || n2) {
4404         return 0;
4405     }
4406
4407     /* Successful match.  Set output pointers */
4408     if (pe1) {
4409         *pe1 = (char*)p1;
4410     }
4411     if (pe2) {
4412         *pe2 = (char*)p2;
4413     }
4414     return 1;
4415 }
4416
4417 /*
4418  * ex: set ts=8 sts=4 sw=4 et:
4419  */