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