This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
a96537d88f0ac6facaf2afcc9e8befad53b0f2b9
[perl5.git] / perl.h
1 /*    perl.h
2  *
3  *    Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001
4  *    2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 by Larry Wall and others
5  *
6  *    You may distribute under the terms of either the GNU General Public
7  *    License or the Artistic License, as specified in the README file.
8  *
9  */
10
11 #ifndef H_PERL
12 #define H_PERL 1
13
14 #if defined(__HP_cc) || defined(__HP_aCC)
15 /* The HPUX compiler for Itanium is very picky and warns about
16  * things that gcc doesn't and that we would prefer it does not.
17  * So on that platform silence certain warnings unlaterally. */
18
19 /* silence "relational operator ">" always evaluates to 'false'"
20  * warnings. We get a LOT of these from the memwrap checks. */
21 #pragma diag_suppress 4276
22
23 /* silence "may cause misaligned access" warnings from our "OO in C"
24  * type logic. we do this a lot and if it was broken we would fail tests
25  * all over the place */
26 #pragma diag_suppress 4232
27
28 #endif /* end HPUX warning disablement */
29
30 #ifdef PERL_FOR_X2P
31 /*
32  * This file is being used for x2p stuff.
33  * Above symbol is defined via -D in 'x2p/Makefile.SH'
34  * Decouple x2p stuff from some of perls more extreme eccentricities.
35  */
36 #undef MULTIPLICITY
37 #undef USE_STDIO
38 #define USE_STDIO
39 #endif /* PERL_FOR_X2P */
40
41 #include "config.h"
42
43 /* This fakes up using Mingw for locale handling.  In order to not define WIN32
44  * in this file (and hence throughout the code that isn't expecting it), this
45  * doesn't define that, but defines the appropriate things that would otherwise
46  * be defined later in the file.  Hence those and here must be kept in sync */
47 #ifdef WIN32_USE_FAKE_OLD_MINGW_LOCALES
48 #  define UINT  unsigned int
49 #  undef USE_THREAD_SAFE_LOCALE
50 #  define NO_POSIX_2008_LOCALE
51 #  undef HAS_NL_LANGINFO
52 #  undef HAS_NL_LANGINFO_L
53 #  undef _UCRT
54 #  ifdef USE_LOCALE
55 #    define TS_W32_BROKEN_LOCALECONV
56 #    ifdef USE_THREADS
57 #      define EMULATE_THREAD_SAFE_LOCALES
58 #    endif
59 #  endif
60 #endif
61
62 /*
63 =for apidoc_section $debugging
64 =for apidoc CmnW ||comma_aDEPTH
65 Some functions when compiled under DEBUGGING take an extra final argument named
66 C<depth>, indicating the C stack depth.  This argument is omitted otherwise.
67 This macro expands to either S<C<, depth>> under DEBUGGING, or to nothing at
68 all when not under DEBUGGING, reducing the number of C<#ifdef>'s in the code.
69
70 The program is responsible for maintaining the correct value for C<depth>.
71
72 =for apidoc CyW ||comma_pDEPTH
73 This is used in the prototype declarations for functions that take a L</C<comma_aDEPTH>>
74 final parameter, much like L<C<pTHX_>|perlguts/Background and MULTIPLICITY>
75 is used in functions that take a thread context initial parameter.
76
77 =for apidoc CmnW ||debug_aDEPTH
78 Same as L</C<comma_aDEPTH>> but with no leading argument. Intended for functions with
79 no normal arguments, and used by L</C<comma_aDEPTH>> itself.
80
81 =for apidoc CmnW ||debug_pDEPTH
82 Same as L</C<comma_pDEPTH>> but with no leading argument. Intended for functions with
83 no normal arguments, and used by L</C<comma_pDEPTH>> itself.
84
85 =cut
86  */
87
88 #ifdef DEBUGGING
89 #  define debug_pDEPTH U32 depth
90 #  define comma_pDEPTH ,debug_pDEPTH
91 #  define debug_aDEPTH depth
92 #  define comma_aDEPTH ,debug_aDEPTH
93 #else
94 #  define debug_aDEPTH
95 #  define comma_aDEPTH
96 #  define debug_pDEPTH
97 #  define comma_pDEPTH
98 #endif
99
100 /* NOTE 1: that with gcc -std=c89 the __STDC_VERSION__ is *not* defined
101  * because the __STDC_VERSION__ became a thing only with C90.  Therefore,
102  * with gcc, HAS_C99 will never become true as long as we use -std=c89.
103
104  * NOTE 2: headers lie.  Do not expect that if HAS_C99 gets to be true,
105  * all the C99 features are there and are correct. */
106 #if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || \
107     defined(_STDC_C99) || defined(__c99)
108 #  define HAS_C99 1
109 #endif
110
111 /* =========================================================================
112  * The defines from here to the following ===== line are unfortunately
113  * duplicated in makedef.pl, and changes here MUST also be made there */
114
115 /* See L<perlguts/"The Perl API"> for detailed notes on
116  * MULTIPLICITY and PERL_IMPLICIT_SYS */
117
118 #ifdef USE_ITHREADS
119 #  if !defined(MULTIPLICITY)
120 #    define MULTIPLICITY
121 #  endif
122 #endif
123
124 /* PERL_IMPLICIT_CONTEXT is a legacy synonym for MULTIPLICITY */
125 #if defined(MULTIPLICITY)               \
126  && ! defined(PERL_CORE)                \
127  && ! defined(PERL_IMPLICIT_CONTEXT)
128 #  define PERL_IMPLICIT_CONTEXT
129 #endif
130 #if defined(PERL_IMPLICIT_CONTEXT) && !defined(MULTIPLICITY)
131 #  define MULTIPLICITY
132 #endif
133 #if defined(PERL_CORE) && defined(PERL_IMPLICIT_CONTEXT)
134 #  pragma message("PERL_IMPLICIT_CONTEXT was removed from core perl. It does not do anything. Undeffing it for compilation")
135 #  undef PERL_IMPLICIT_CONTEXT
136 #endif
137
138 /* undef WIN32 when building on Cygwin (for libwin32) - gph */
139 #ifdef __CYGWIN__
140 #   undef WIN32
141 #   undef _WIN32
142 #endif
143
144 /* Use the reentrant APIs like localtime_r and getpwent_r */
145 /* Win32 has naturally threadsafe libraries, no need to use any _r variants.
146  * XXX KEEP makedef.pl copy of this code in sync */
147 #if defined(USE_ITHREADS) && !defined(USE_REENTRANT_API) && !defined(WIN32)
148 #   define USE_REENTRANT_API
149 #endif
150
151 /* end of makedef.pl logic duplication.  But there are other groups below.
152  * ========================================================================= */
153
154 /*
155 =for apidoc_section $directives
156 =for apidoc AmnUu|void|EXTERN_C
157 When not compiling using C++, expands to nothing.
158 Otherwise is used in a declaration of a function to indicate the function
159 should have external C linkage.  This is required for things to work for just
160 about all functions with external linkage compiled into perl.
161 Often, you can use C<L</START_EXTERN_C>> ... C<L</END_EXTERN_C>> blocks
162 surrounding all your code that you need to have this linkage.
163
164 Example usage:
165
166  EXTERN_C int flock(int fd, int op);
167
168 =for apidoc Amnu||START_EXTERN_C
169 When not compiling using C++, expands to nothing.
170 Otherwise begins a section of code in which every function will effectively
171 have C<L</EXTERN_C>> applied to it, that is to have external C linkage.  The
172 section is ended by a C<L</END_EXTERN_C>>.
173
174 =for apidoc Amnu||END_EXTERN_C
175 When not compiling using C++, expands to nothing.
176 Otherwise ends a section of code already begun by a C<L</START_EXTERN_C>>.
177
178 =cut
179 */
180
181 #undef START_EXTERN_C
182 #undef END_EXTERN_C
183 #undef EXTERN_C
184 #ifdef __cplusplus
185 #  define EXTERN_C extern "C"
186 #  define START_EXTERN_C EXTERN_C {
187 #  define END_EXTERN_C }
188 #else
189 #  define START_EXTERN_C
190 #  define END_EXTERN_C
191 #  define EXTERN_C extern
192 #endif
193
194 /* Fallback definitions in case we don't have definitions from config.h.
195    This should only matter for systems that don't use Configure and
196    haven't been modified to define PERL_STATIC_INLINE yet.
197 */
198 #if !defined(PERL_STATIC_INLINE)
199 #  ifdef HAS_STATIC_INLINE
200 #    define PERL_STATIC_INLINE static inline
201 #  else
202 #    define PERL_STATIC_INLINE static
203 #  endif
204 #endif
205
206 /*
207 =for apidoc_section $concurrency
208 =for apidoc AmU|void|dTHXa|PerlInterpreter * a
209 On threaded perls, set C<pTHX> to C<a>; on unthreaded perls, do nothing
210
211 =for apidoc AmU|void|dTHXoa|PerlInterpreter * a
212 Now a synonym for C<L</dTHXa>>.
213
214 =cut
215 */
216
217 #ifdef MULTIPLICITY
218 #  define tTHX  PerlInterpreter*
219 #  define pTHX  tTHX my_perl PERL_UNUSED_DECL
220 #  define aTHX  my_perl
221 #  define aTHXa(a) aTHX = (tTHX)a
222 #  define dTHXa(a)      pTHX = (tTHX)a
223 #  define dTHX          pTHX = PERL_GET_THX
224 #  define pTHX_         pTHX,
225 #  define aTHX_         aTHX,
226 #  define pTHX_1        2
227 #  define pTHX_2        3
228 #  define pTHX_3        4
229 #  define pTHX_4        5
230 #  define pTHX_5        6
231 #  define pTHX_6        7
232 #  define pTHX_7        8
233 #  define pTHX_8        9
234 #  define pTHX_9        10
235 #  define pTHX_12       13
236 #  if defined(DEBUGGING) && !defined(PERL_TRACK_MEMPOOL)
237 #    define PERL_TRACK_MEMPOOL
238 #  endif
239 #else
240 #  undef PERL_TRACK_MEMPOOL
241 #endif
242
243 #ifdef DEBUGGING
244 #  define dTHX_DEBUGGING dTHX
245 #else
246 #  define dTHX_DEBUGGING dNOOP
247 #endif
248
249 #define STATIC static
250
251 #ifndef PERL_CORE
252 /* Do not use these macros. They were part of PERL_OBJECT, which was an
253  * implementation of multiplicity using C++ objects. They have been left
254  * here solely for the sake of XS code which has incorrectly
255  * cargo-culted them.
256  *
257  * The only one Devel::PPPort handles is this; list it as deprecated
258
259 =for apidoc_section $concurrency
260 =for apidoc AmD|void|CPERLscope|void x
261 Now a no-op.
262
263 =cut
264  */
265 #  define CPERLscope(x) x
266 #  define CPERLarg void
267 #  define CPERLarg_
268 #  define _CPERLarg
269 #  define PERL_OBJECT_THIS
270 #  define _PERL_OBJECT_THIS
271 #  define PERL_OBJECT_THIS_
272 #  define CALL_FPTR(fptr) (*fptr)
273 #  define MEMBER_TO_FPTR(name) name
274 #endif /* !PERL_CORE */
275
276 #define CALLRUNOPS  PL_runops
277
278 #define CALLREGCOMP(sv, flags) Perl_pregcomp(aTHX_ (sv),(flags))
279
280 #define CALLREGCOMP_ENG(prog, sv, flags) (prog)->comp(aTHX_ sv, flags)
281 #define CALLREGEXEC(prog,stringarg,strend,strbeg,minend,sv,data,flags) \
282     RX_ENGINE(prog)->exec(aTHX_ (prog),(stringarg),(strend), \
283         (strbeg),(minend),(sv),(data),(flags))
284 #define CALLREG_INTUIT_START(prog,sv,strbeg,strpos,strend,flags,data) \
285     RX_ENGINE(prog)->intuit(aTHX_ (prog), (sv), (strbeg), (strpos), \
286         (strend),(flags),(data))
287 #define CALLREG_INTUIT_STRING(prog) \
288     RX_ENGINE(prog)->checkstr(aTHX_ (prog))
289
290 #define CALLREGFREE(prog) \
291     Perl_pregfree(aTHX_ (prog))
292
293 #define CALLREGFREE_PVT(prog) \
294     if(prog && RX_ENGINE(prog)) RX_ENGINE(prog)->rxfree(aTHX_ (prog))
295
296 #define CALLREG_NUMBUF_FETCH(rx,paren,usesv)                                \
297     RX_ENGINE(rx)->numbered_buff_FETCH(aTHX_ (rx),(paren),(usesv))
298
299 #define CALLREG_NUMBUF_STORE(rx,paren,value) \
300     RX_ENGINE(rx)->numbered_buff_STORE(aTHX_ (rx),(paren),(value))
301
302 #define CALLREG_NUMBUF_LENGTH(rx,sv,paren)                              \
303     RX_ENGINE(rx)->numbered_buff_LENGTH(aTHX_ (rx),(sv),(paren))
304
305 #define CALLREG_NAMED_BUFF_FETCH(rx, key, flags) \
306     RX_ENGINE(rx)->named_buff(aTHX_ (rx), (key), NULL, ((flags) | RXapif_FETCH))
307
308 #define CALLREG_NAMED_BUFF_STORE(rx, key, value, flags) \
309     RX_ENGINE(rx)->named_buff(aTHX_ (rx), (key), (value), ((flags) | RXapif_STORE))
310
311 #define CALLREG_NAMED_BUFF_DELETE(rx, key, flags) \
312     RX_ENGINE(rx)->named_buff(aTHX_ (rx),(key), NULL, ((flags) | RXapif_DELETE))
313
314 #define CALLREG_NAMED_BUFF_CLEAR(rx, flags) \
315     RX_ENGINE(rx)->named_buff(aTHX_ (rx), NULL, NULL, ((flags) | RXapif_CLEAR))
316
317 #define CALLREG_NAMED_BUFF_EXISTS(rx, key, flags) \
318     RX_ENGINE(rx)->named_buff(aTHX_ (rx), (key), NULL, ((flags) | RXapif_EXISTS))
319
320 #define CALLREG_NAMED_BUFF_FIRSTKEY(rx, flags) \
321     RX_ENGINE(rx)->named_buff_iter(aTHX_ (rx), NULL, ((flags) | RXapif_FIRSTKEY))
322
323 #define CALLREG_NAMED_BUFF_NEXTKEY(rx, lastkey, flags) \
324     RX_ENGINE(rx)->named_buff_iter(aTHX_ (rx), (lastkey), ((flags) | RXapif_NEXTKEY))
325
326 #define CALLREG_NAMED_BUFF_SCALAR(rx, flags) \
327     RX_ENGINE(rx)->named_buff(aTHX_ (rx), NULL, NULL, ((flags) | RXapif_SCALAR))
328
329 #define CALLREG_NAMED_BUFF_COUNT(rx) \
330     RX_ENGINE(rx)->named_buff(aTHX_ (rx), NULL, NULL, RXapif_REGNAMES_COUNT)
331
332 #define CALLREG_NAMED_BUFF_ALL(rx, flags) \
333     RX_ENGINE(rx)->named_buff(aTHX_ (rx), NULL, NULL, flags)
334
335 #define CALLREG_PACKAGE(rx) \
336     RX_ENGINE(rx)->qr_package(aTHX_ (rx))
337
338 #if defined(USE_ITHREADS)
339 #  define CALLREGDUPE(prog,param) \
340     Perl_re_dup(aTHX_ (prog),(param))
341
342 #  define CALLREGDUPE_PVT(prog,param) \
343     (prog ? RX_ENGINE(prog)->dupe(aTHX_ (prog),(param)) \
344           : (REGEXP *)NULL)
345 #endif
346
347 /* some compilers impersonate gcc */
348 #if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER)
349 #  define PERL_IS_GCC 1
350 #endif
351
352 #define PERL_GCC_VERSION_GE(major,minor,patch)                              \
353     (((100000 * __GNUC__) + (1000 * __GNUC_MINOR__) + __GNUC_PATCHLEVEL__)  \
354         >= ((100000 * (major)) + (1000 * (minor)) + (patch)))
355 #define PERL_GCC_VERSION_GT(major,minor,patch)                              \
356     (((100000 * __GNUC__) + (1000 * __GNUC_MINOR__) + __GNUC_PATCHLEVEL__)  \
357         > ((100000 * (major)) + (1000 * (minor)) + (patch)))
358 #define PERL_GCC_VERSION_LE(major,minor,patch)                              \
359     (((100000 * __GNUC__) + (1000 * __GNUC_MINOR__) + __GNUC_PATCHLEVEL__)  \
360         <= ((100000 * (major)) + (1000 * (minor)) + (patch)))
361 #define PERL_GCC_VERSION_LT(major,minor,patch)                              \
362     (((100000 * __GNUC__) + (1000 * __GNUC_MINOR__) + __GNUC_PATCHLEVEL__)  \
363         < ((100000 * (major)) + (1000 * (minor)) + (patch)))
364
365 /* In case Configure was not used (we are using a "canned config"
366  * such as Win32, or a cross-compilation setup, for example) try going
367  * by the gcc major and minor versions.  One useful URL is
368  * http://www.ohse.de/uwe/articles/gcc-attributes.html,
369  * but contrary to this information warn_unused_result seems
370  * not to be in gcc 3.3.5, at least. --jhi
371  * Also, when building extensions with an installed perl, this allows
372  * the user to upgrade gcc and get the right attributes, rather than
373  * relying on the list generated at Configure time.  --AD
374  * Set these up now otherwise we get confused when some of the <*thread.h>
375  * includes below indirectly pull in <perlio.h> (which needs to know if we
376  * have HASATTRIBUTE_FORMAT).
377  */
378
379 #if defined __GNUC__ && !defined(__INTEL_COMPILER)
380 #  if PERL_GCC_VERSION_GE(3,1,0)
381 #    define HASATTRIBUTE_DEPRECATED
382 #  endif
383 #  if PERL_GCC_VERSION_GE(3,0,0)  /* XXX Verify this version */
384 #    define HASATTRIBUTE_FORMAT
385 #    if defined __MINGW32__
386 #      define PRINTF_FORMAT_NULL_OK
387 #    endif
388 #  endif
389 #  if PERL_GCC_VERSION_GE(3,0,0)
390 #    define HASATTRIBUTE_MALLOC
391 #  endif
392 #  if PERL_GCC_VERSION_GE(3,3,0)
393 #    define HASATTRIBUTE_NONNULL
394 #  endif
395 #  if PERL_GCC_VERSION_GE(2,5,0)
396 #    define HASATTRIBUTE_NORETURN
397 #  endif
398 #  if PERL_GCC_VERSION_GE(3,0,0)
399 #    define HASATTRIBUTE_PURE
400 #  endif
401 #  if PERL_GCC_VERSION_GE(3,4,0)
402 #    define HASATTRIBUTE_UNUSED
403 #  endif
404 #  if __GNUC__ == 3 && __GNUC_MINOR__ == 3 && !defined(__cplusplus)
405 #    define HASATTRIBUTE_UNUSED /* gcc-3.3, but not g++-3.3. */
406 #  endif
407 #  if PERL_GCC_VERSION_GE(3,4,0)
408 #    define HASATTRIBUTE_WARN_UNUSED_RESULT
409 #  endif
410    /* always_inline is buggy in gcc <= 4.6 and causes compilation errors */
411 #  if PERL_GCC_VERSION_GE(4,7,0)
412 #    define HASATTRIBUTE_ALWAYS_INLINE
413 #  endif
414 #  if PERL_GCC_VERSION_GE(3,3,0)
415 #    define HASATTRIBUTE_VISIBILITY
416 #  endif
417 #endif
418
419 #ifdef HASATTRIBUTE_DEPRECATED
420 #  define __attribute__deprecated__         __attribute__((deprecated))
421 #endif
422 #ifdef HASATTRIBUTE_FORMAT
423 #  define __attribute__format__(x,y,z)      __attribute__((format(x,y,z)))
424 #endif
425 #ifdef HASATTRIBUTE_MALLOC
426 #  define __attribute__malloc__             __attribute__((__malloc__))
427 #endif
428 #ifdef HASATTRIBUTE_NONNULL
429 #  define __attribute__nonnull__(a)         __attribute__((nonnull(a)))
430 #endif
431 #ifdef HASATTRIBUTE_NORETURN
432 #  define __attribute__noreturn__           __attribute__((noreturn))
433 #endif
434 #ifdef HASATTRIBUTE_PURE
435 #  define __attribute__pure__               __attribute__((pure))
436 #endif
437 #ifdef HASATTRIBUTE_UNUSED
438 #  define __attribute__unused__             __attribute__((unused))
439 #endif
440 #ifdef HASATTRIBUTE_WARN_UNUSED_RESULT
441 #  define __attribute__warn_unused_result__ __attribute__((warn_unused_result))
442 #endif
443 #ifdef HASATTRIBUTE_ALWAYS_INLINE
444 /* always_inline is buggy in gcc <= 4.6 and causes compilation errors */
445 #  if !defined(PERL_IS_GCC) || PERL_GCC_VERSION_GE(4,7,0)
446 #    define __attribute__always_inline__      __attribute__((always_inline))
447 #  endif
448 #endif
449 #if defined(HASATTRIBUTE_VISIBILITY) && !defined(_WIN32) && !defined(__CYGWIN__)
450 /* On Windows instead of this, we use __declspec(dllexport) and a .def file
451  * Cygwin works by exporting every global symbol, see the definition of ldflags
452  * near the end of hints/cygwin.sh and the visibility attribute doesn't appear
453  * to control that.
454  */
455 #  define __attribute__visibility__(x) __attribute__((visibility(x)))
456 #endif
457
458 /* If we haven't defined the attributes yet, define them to blank. */
459 #ifndef __attribute__deprecated__
460 #  define __attribute__deprecated__
461 #endif
462 #ifndef __attribute__format__
463 #  define __attribute__format__(x,y,z)
464 #endif
465 #ifndef __attribute__malloc__
466 #  define __attribute__malloc__
467 #endif
468 #ifndef __attribute__nonnull__
469 #  define __attribute__nonnull__(a)
470 #endif
471 #ifndef __attribute__noreturn__
472 #  define __attribute__noreturn__
473 #endif
474 #ifndef __attribute__pure__
475 #  define __attribute__pure__
476 #endif
477 #ifndef __attribute__unused__
478 #  define __attribute__unused__
479 #endif
480 #ifndef __attribute__warn_unused_result__
481 #  define __attribute__warn_unused_result__
482 #endif
483 #ifndef __attribute__always_inline__
484 #  define __attribute__always_inline__
485 #endif
486 #ifndef __attribute__visibility__
487 #  define __attribute__visibility__(x)
488 #endif
489
490 /* Some OS warn on NULL format to printf */
491 #ifdef PRINTF_FORMAT_NULL_OK
492 #  define __attribute__format__null_ok__(x,y,z)  __attribute__format__(x,y,z)
493 #else
494 #  define __attribute__format__null_ok__(x,y,z)
495 #endif
496
497 /*
498  * Because of backward compatibility reasons the PERL_UNUSED_DECL
499  * cannot be changed from postfix to PERL_UNUSED_DECL(x).  Sigh.
500  *
501  * Note that there are C compilers such as MetroWerks CodeWarrior
502  * which do not have an "inlined" way (like the gcc __attribute__) of
503  * marking unused variables (they need e.g. a #pragma) and therefore
504  * cpp macros like PERL_UNUSED_DECL cannot work for this purpose, even
505  * if it were PERL_UNUSED_DECL(x), which it cannot be (see above).
506 */
507
508 /*
509 =for apidoc_section $directives
510 =for apidoc AmnU||PERL_UNUSED_DECL
511 Tells the compiler that the parameter in the function prototype just before it
512 is not necessarily expected to be used in the function.  Not that many
513 compilers understand this, so this should only be used in cases where
514 C<L</PERL_UNUSED_ARG>> can't conveniently be used.
515
516 Example usage:
517
518 =over
519
520  Signal_t
521  Perl_perly_sighandler(int sig, Siginfo_t *sip PERL_UNUSED_DECL,
522                        void *uap PERL_UNUSED_DECL, bool safe)
523
524 =back
525
526 =cut
527 */
528
529 #ifndef PERL_UNUSED_DECL
530 #  define PERL_UNUSED_DECL __attribute__unused__
531 #endif
532
533 /* gcc -Wall:
534  * for silencing unused variables that are actually used most of the time,
535  * but we cannot quite get rid of, such as "ax" in PPCODE+noargs xsubs,
536  * or variables/arguments that are used only in certain configurations.
537  */
538 /*
539 =for apidoc Am;||PERL_UNUSED_ARG|void x
540 This is used to suppress compiler warnings that a parameter to a function is
541 not used.  This situation can arise, for example, when a parameter is needed
542 under some configuration conditions, but not others, so that C preprocessor
543 conditional compilation causes it be used just sometimes.
544
545 =for apidoc Amn;||PERL_UNUSED_CONTEXT
546 This is used to suppress compiler warnings that the thread context parameter to
547 a function is not used.  This situation can arise, for example, when a
548 C preprocessor conditional compilation causes it be used just some times.
549
550 =for apidoc Am;||PERL_UNUSED_VAR|void x
551 This is used to suppress compiler warnings that the variable I<x> is not used.
552 This situation can arise, for example, when a C preprocessor conditional
553 compilation causes it be used just some times.
554
555 =cut
556 */
557 #ifndef PERL_UNUSED_ARG
558 #  define PERL_UNUSED_ARG(x) ((void)sizeof(x))
559 #endif
560 #ifndef PERL_UNUSED_VAR
561 #  define PERL_UNUSED_VAR(x) ((void)sizeof(x))
562 #endif
563
564 #if defined(USE_ITHREADS)
565 #  define PERL_UNUSED_CONTEXT PERL_UNUSED_ARG(my_perl)
566 #else
567 #  define PERL_UNUSED_CONTEXT
568 #endif
569
570 /* gcc (-ansi) -pedantic doesn't allow gcc statement expressions,
571  * g++ allows them but seems to have problems with them
572  * (insane errors ensue).
573  * g++ does not give insane errors now (RMB 2008-01-30, gcc 4.2.2).
574  */
575 #if defined(PERL_GCC_PEDANTIC) || \
576     (defined(__GNUC__) && defined(__cplusplus) && \
577         (PERL_GCC_VERSION_LT(4,2,0)))
578 #  ifndef PERL_GCC_BRACE_GROUPS_FORBIDDEN
579 #    define PERL_GCC_BRACE_GROUPS_FORBIDDEN
580 #  endif
581 #endif
582
583 /*
584
585 =for apidoc Am||PERL_UNUSED_RESULT|void x
586
587 This macro indicates to discard the return value of the function call inside
588 it, I<e.g.>,
589
590  PERL_UNUSED_RESULT(foo(a, b))
591
592 The main reason for this is that the combination of C<gcc -Wunused-result>
593 (part of C<-Wall>) and the C<__attribute__((warn_unused_result))> cannot
594 be silenced with casting to C<void>.  This causes trouble when the system
595 header files use the attribute.
596
597 Use C<PERL_UNUSED_RESULT> sparingly, though, since usually the warning
598 is there for a good reason: you might lose success/failure information,
599 or leak resources, or changes in resources.
600
601 But sometimes you just want to ignore the return value, I<e.g.>, on
602 codepaths soon ending up in abort, or in "best effort" attempts,
603 or in situations where there is no good way to handle failures.
604
605 Sometimes C<PERL_UNUSED_RESULT> might not be the most natural way:
606 another possibility is that you can capture the return value
607 and use C<L</PERL_UNUSED_VAR>> on that.
608
609 =cut
610
611 The __typeof__() is used instead of typeof() since typeof() is not
612 available under strict ISO C, and because of compilers masquerading
613 as gcc (clang and icc), we want exactly the gcc extension
614 __typeof__ and nothing else.
615
616 */
617 #ifndef PERL_UNUSED_RESULT
618 #  if defined(__GNUC__) && defined(HASATTRIBUTE_WARN_UNUSED_RESULT)
619 #    define PERL_UNUSED_RESULT(v) STMT_START { __typeof__(v) z = (v); (void)sizeof(z); } STMT_END
620 #  else
621 #    define PERL_UNUSED_RESULT(v) ((void)(v))
622 #  endif
623 #endif
624
625 /* on gcc (and clang), specify that a warning should be temporarily
626  * ignored; e.g.
627  *
628  *    GCC_DIAG_IGNORE_DECL(-Wmultichar);
629  *    char b = 'ab';
630  *    GCC_DIAG_RESTORE_DECL;
631  *
632  * based on http://dbp-consulting.com/tutorials/SuppressingGCCWarnings.html
633  *
634  * Note that "pragma GCC diagnostic push/pop" was added in GCC 4.6, Mar 2011;
635  * clang only pretends to be GCC 4.2, but still supports push/pop.
636  *
637  * Note on usage: all macros must be used at a place where a declaration
638  * or statement can occur, i.e., not in the middle of an expression.
639  * *_DIAG_IGNORE() and *_DIAG_RESTORE can be used in any such place, but
640  * must be used without a following semicolon.  *_DIAG_IGNORE_DECL() and
641  * *_DIAG_RESTORE_DECL must be used with a following semicolon, and behave
642  * syntactically as declarations (like dNOOP).  *_DIAG_IGNORE_STMT()
643  * and *_DIAG_RESTORE_STMT must be used with a following semicolon,
644  * and behave syntactically as statements (like NOOP).
645  *
646  */
647
648 #if defined(__clang__) || defined(__clang) || PERL_GCC_VERSION_GE(4,6,0)
649 #  define GCC_DIAG_PRAGMA(x) _Pragma (#x)
650 /* clang has "clang diagnostic" pragmas, but also understands gcc. */
651 #  define GCC_DIAG_IGNORE(x) _Pragma("GCC diagnostic push") \
652                              GCC_DIAG_PRAGMA(GCC diagnostic ignored #x)
653 #  define GCC_DIAG_RESTORE   _Pragma("GCC diagnostic pop")
654 #else
655 #  define GCC_DIAG_IGNORE(w)
656 #  define GCC_DIAG_RESTORE
657 #endif
658 #define GCC_DIAG_IGNORE_DECL(x) GCC_DIAG_IGNORE(x) dNOOP
659 #define GCC_DIAG_RESTORE_DECL GCC_DIAG_RESTORE dNOOP
660 #define GCC_DIAG_IGNORE_STMT(x) GCC_DIAG_IGNORE(x) NOOP
661 #define GCC_DIAG_RESTORE_STMT GCC_DIAG_RESTORE NOOP
662 /* for clang specific pragmas */
663 #if defined(__clang__) || defined(__clang)
664 #  define CLANG_DIAG_PRAGMA(x) _Pragma (#x)
665 #  define CLANG_DIAG_IGNORE(x) _Pragma("clang diagnostic push") \
666                                CLANG_DIAG_PRAGMA(clang diagnostic ignored #x)
667 #  define CLANG_DIAG_RESTORE   _Pragma("clang diagnostic pop")
668 #else
669 #  define CLANG_DIAG_IGNORE(w)
670 #  define CLANG_DIAG_RESTORE
671 #endif
672 #define CLANG_DIAG_IGNORE_DECL(x) CLANG_DIAG_IGNORE(x) dNOOP
673 #define CLANG_DIAG_RESTORE_DECL CLANG_DIAG_RESTORE dNOOP
674 #define CLANG_DIAG_IGNORE_STMT(x) CLANG_DIAG_IGNORE(x) NOOP
675 #define CLANG_DIAG_RESTORE_STMT CLANG_DIAG_RESTORE NOOP
676
677 #if defined(_MSC_VER)
678 #  define MSVC_DIAG_IGNORE(x) __pragma(warning(push)) \
679                               __pragma(warning(disable : x))
680 #  define MSVC_DIAG_RESTORE   __pragma(warning(pop))
681 #else
682 #  define MSVC_DIAG_IGNORE(x)
683 #  define MSVC_DIAG_RESTORE
684 #endif
685 #define MSVC_DIAG_IGNORE_DECL(x) MSVC_DIAG_IGNORE(x) dNOOP
686 #define MSVC_DIAG_RESTORE_DECL MSVC_DIAG_RESTORE dNOOP
687 #define MSVC_DIAG_IGNORE_STMT(x) MSVC_DIAG_IGNORE(x) NOOP
688 #define MSVC_DIAG_RESTORE_STMT MSVC_DIAG_RESTORE NOOP
689
690 /*
691 =for apidoc Amn;||NOOP
692 Do nothing; typically used as a placeholder to replace something that used to
693 do something.
694
695 =for apidoc Amn;||dNOOP
696 Declare nothing; typically used as a placeholder to replace something that used
697 to declare something.  Works on compilers that require declarations before any
698 code.
699
700 =cut
701 */
702 #define NOOP ((void)0)
703 #define dNOOP struct Perl___notused_struct
704
705 #ifndef pTHX
706 /* Don't bother defining tTHX ; using it outside
707  * code guarded by MULTIPLICITY is an error.
708  */
709 #  define pTHX          void
710 #  define pTHX_
711 #  define aTHX
712 #  define aTHX_
713 #  define aTHXa(a)      NOOP
714 #  define dTHXa(a)      dNOOP
715 #  define dTHX          dNOOP
716 #  define pTHX_1        1
717 #  define pTHX_2        2
718 #  define pTHX_3        3
719 #  define pTHX_4        4
720 #  define pTHX_5        5
721 #  define pTHX_6        6
722 #  define pTHX_7        7
723 #  define pTHX_8        8
724 #  define pTHX_9        9
725 #  define pTHX_12       12
726 #endif
727
728 /*
729 =for apidoc_section $concurrency
730 =for apidoc AmnU||dVAR
731 This is now a synonym for dNOOP: declare nothing
732
733 =for apidoc_section $XS
734 =for apidoc Amn;||dMY_CXT_SV
735 Now a placeholder that declares nothing
736
737 =cut
738 */
739
740 #ifndef PERL_CORE
741     /* Backwards compatibility macro for XS code. It used to be part of the
742      * PERL_GLOBAL_STRUCT(_PRIVATE) feature, which no longer exists */
743 #  define dVAR          dNOOP
744
745     /* these are only defined for compatibility; should not be used internally.
746      * */
747 #  define dMY_CXT_SV    dNOOP
748 #  ifndef pTHXo
749 #    define pTHXo               pTHX
750 #    define pTHXo_      pTHX_
751 #    define aTHXo               aTHX
752 #    define aTHXo_      aTHX_
753 #    define dTHXo               dTHX
754 #    define dTHXoa(x)   dTHXa(x)
755 #  endif
756 #endif
757
758 #ifndef pTHXx
759 #  define pTHXx         PerlInterpreter *my_perl
760 #  define pTHXx_        pTHXx,
761 #  define aTHXx         my_perl
762 #  define aTHXx_        aTHXx,
763 #  define dTHXx         dTHX
764 #endif
765
766 /* Under PERL_IMPLICIT_SYS (used in Windows for fork emulation)
767  * PerlIO_foo() expands to PL_StdIO->pFOO(PL_StdIO, ...).
768  * dTHXs is therefore needed for all functions using PerlIO_foo(). */
769 #ifdef PERL_IMPLICIT_SYS
770 #    define dTHXs               dTHX
771 #else
772 #    define dTHXs               dNOOP
773 #endif
774
775 #if defined(__GNUC__) && !defined(PERL_GCC_BRACE_GROUPS_FORBIDDEN) && !defined(__cplusplus)
776 #  ifndef PERL_USE_GCC_BRACE_GROUPS
777 #    define PERL_USE_GCC_BRACE_GROUPS
778 #  endif
779 #endif
780
781 /*
782 =for apidoc_section $directives
783 =for apidoc AmnUu|void|STMT_END
784 =for apidoc_item |    |STMT_START
785
786 These allow a series of statements in a macro to be used as a single statement,
787 as in
788
789  if (x) STMT_START { ... } STMT_END else ...
790
791 Note that you can't return a value out of this construct and cannot use it as
792 an operand to the comma operator.  These limit its utility.
793
794 But, a value could be returned by constructing the API so that a pointer is
795 passed and the macro dereferences this to set the return.  If the value can be
796 any of various types, depending on context, you can handle that situation in
797 some situations by adding the type of the return as an extra accompanying
798 parameter:
799
800  #define foo(param, type)  STMT_START {
801                               type * param; *param = do_calc; ...
802                            } STMT_END
803
804 This could be awkward, so consider instead using a C language C<static inline>
805 function.
806
807 If you do use this construct, it is easy to forget that it is a macro and not a
808 function, and hence fall into traps that might not show up until someone
809 someday writes code which contains names that clash with the ones you chose
810 here, or calls it with a parameter which is an expression with side effects,
811 the consequences of which you didn't think about.  See L<perlhacktips/Writing
812 safer macros> for how to avoid these.
813
814 =for apidoc_section $genconfig
815 =for apidoc Amn#||PERL_USE_GCC_BRACE_GROUPS
816
817 This C pre-processor value, if defined, indicates that it is permissible to use
818 the GCC brace groups extension.  However, use of this extension is DISCOURAGED.
819 Use a C<static inline> function instead.
820
821 The extension, of the form
822
823  ({ statement ... })
824
825 turns the block consisting of I<statement ...> into an expression with a
826 value, unlike plain C language blocks.  This can present optimization
827 possibilities, B<BUT>, unless you know for sure that this will never be
828 compiled without this extension being available and not forbidden, you need to
829 specify an alternative.  Thus two code paths have to be maintained, which can
830 get out-of-sync.  All these issues are solved by using a C<static inline>
831 function instead.
832
833 Perl can be configured to not use this feature by passing the parameter
834 C<-Accflags=-DPERL_GCC_BRACE_GROUPS_FORBIDDEN> to F<Configure>.
835
836 =for apidoc Amnh#||PERL_GCC_BRACE_GROUPS_FORBIDDEN
837
838 Example usage:
839
840 =over
841
842  #ifdef PERL_USE_GCC_BRACE_GROUPS
843    ...
844  #else
845    ...
846  #endif
847
848 =back
849
850 =cut
851
852  Trying to select a version that gives no warnings...
853 */
854 #if !(defined(STMT_START) && defined(STMT_END))
855 #   define STMT_START   do
856 #   define STMT_END     while (0)
857 #endif
858
859 #ifndef BYTEORDER  /* Should never happen -- byteorder is in config.h */
860 #   define BYTEORDER 0x1234
861 #endif
862
863 /*
864 =for apidoc_section $genconfig
865 =for apidoc Amn#||ASCIIish
866
867 A preprocessor symbol that is defined iff the system is an ASCII platform; this
868 symbol would not be defined on C<L</EBCDIC>> platforms.
869
870 =cut
871 */
872 #if 'A' == 65 && 'I' == 73 && 'J' == 74 && 'Z' == 90
873 #  define ASCIIish
874 #else
875 #  undef  ASCIIish
876 #endif
877
878 /*
879  * The following contortions are brought to you on behalf of all the
880  * standards, semi-standards, de facto standards, not-so-de-facto standards
881  * of the world, as well as all the other botches anyone ever thought of.
882  * The basic theory is that if we work hard enough here, the rest of the
883  * code can be a lot prettier.  Well, so much for theory.  Sorry, Henry...
884  */
885
886 /* define this once if either system, instead of cluttering up the src */
887 #if defined(WIN32)
888 #define DOSISH 1
889 #endif
890
891 /* These exist only for back-compat with XS modules. */
892 #ifndef PERL_CORE
893 #define VOL volatile
894 #define CAN_PROTOTYPE
895 #define _(args) args
896 #define I_LIMITS
897 #define I_STDARG
898 #define STANDARD_C
899 #endif
900
901 /* By compiling a perl with -DNO_TAINT_SUPPORT or -DSILENT_NO_TAINT_SUPPORT,
902  * you get a perl without taint support, but doubtlessly with a lesser
903  * degree of support. Do not do so unless you know exactly what it means
904  * technically, have a good reason to do so, and know exactly how the
905  * perl will be used. perls with -DSILENT_NO_TAINT_SUPPORT are considered
906  * a potential security risk due to flat out ignoring the security-relevant
907  * taint flags. This being said, a perl without taint support compiled in
908  * has marginal run-time performance benefits.
909  * SILENT_NO_TAINT_SUPPORT implies NO_TAINT_SUPPORT.
910  * SILENT_NO_TAINT_SUPPORT is the same as NO_TAINT_SUPPORT except it
911  * silently ignores -t/-T instead of throwing an exception.
912  *
913  * DANGER! Using NO_TAINT_SUPPORT or SILENT_NO_TAINT_SUPPORT
914  *         voids your nonexistent warranty!
915  */
916 #if defined(SILENT_NO_TAINT_SUPPORT) && !defined(NO_TAINT_SUPPORT)
917 #  define NO_TAINT_SUPPORT 1
918 #endif
919
920 /* NO_TAINT_SUPPORT can be set to transform virtually all taint-related
921  * operations into no-ops for a very modest speed-up. Enable only if you
922  * know what you're doing: tests and CPAN modules' tests are bound to fail.
923  */
924 #ifdef NO_TAINT_SUPPORT
925 #   define TAINT                NOOP
926 #   define TAINT_NOT            NOOP
927 #   define TAINT_IF(c)          NOOP
928 #   define TAINT_ENV()          NOOP
929 #   define TAINT_PROPER(s)      NOOP
930 #   define TAINT_set(s)         NOOP
931 #   define TAINT_get            0
932 #   define TAINTING_get         0
933 #   define TAINTING_set(s)      NOOP
934 #   define TAINT_WARN_get       0
935 #   define TAINT_WARN_set(s)    NOOP
936 #else
937
938 /*
939 =for apidoc_section $tainting
940 =for apidoc Cm|void|TAINT
941
942 If we aren't in taint checking mode, do nothing;
943 otherwise indicate to L</C<TAINT_set>> and L</C<TAINT_PROPER>> that some
944 unspecified element is tainted.
945
946 =for apidoc Cm|void|TAINT_NOT
947
948 Remove any taintedness previously set by, I<e.g.>, C<TAINT>.
949
950 =for apidoc Cm|void|TAINT_IF|bool c
951
952 If C<c> evaluates to true, call L</C<TAINT>> to indicate that something is
953 tainted; otherwise do nothing.
954
955 =for apidoc Cmn|void|TAINT_ENV
956
957 Looks at several components of L<C<%ENV>|perlvar/%ENV> for taintedness, and
958 calls L</C<taint_proper>> if any are tainted.  The components it searches are
959 things like C<$PATH>.
960
961 =for apidoc Cm|void|TAINT_PROPER|const char * s
962
963 If no element is tainted, do nothing;
964 otherwise output a message (containing C<s>) that indicates there is a
965 tainting violation.  If such violations are fatal, it croaks.
966
967 =for apidoc Cm|void|TAINT_set|bool s
968
969 If C<s> is true, L</C<TAINT_get>> returns true;
970 If C<s> is false, L</C<TAINT_get>> returns false;
971
972 =for apidoc Cm|bool|TAINT_get
973
974 Returns a boolean as to whether some element is tainted or not.
975
976 =for apidoc Cm|bool|TAINTING_get
977
978 Returns a boolean as to whether taint checking is enabled or not.
979
980 =for apidoc Cm|void|TAINTING_set|bool s
981
982 Turn taint checking mode off/on
983
984 =for apidoc Cm|bool|TAINT_WARN_get
985
986 Returns false if tainting violations are fatal;
987 Returns true if they're just warnings
988
989 =for apidoc Cm|void|TAINT_WARN_set|bool s
990
991 C<s> being true indicates L</C<TAINT_WARN_get>> should return that tainting
992 violations are just warnings
993
994 C<s> being false indicates L</C<TAINT_WARN_get>> should return that tainting
995 violations are fatal.
996
997 =cut
998 */
999     /* Set to tainted if we are running under tainting mode */
1000 #   define TAINT                (PL_tainted = PL_tainting)
1001
1002 #   define TAINT_NOT    (PL_tainted = FALSE)        /* Untaint */
1003 #   define TAINT_IF(c)  if (UNLIKELY(c)) { TAINT; } /* Conditionally taint */
1004 #   define TAINT_ENV()  if (UNLIKELY(PL_tainting)) { taint_env(); }
1005                                 /* croak or warn if tainting */
1006 #   define TAINT_PROPER(s)      if (UNLIKELY(PL_tainting)) {                \
1007                                     taint_proper(NULL, s);                  \
1008                                 }
1009 #   define TAINT_set(s)         (PL_tainted = cBOOL(s))
1010 #   define TAINT_get            (cBOOL(UNLIKELY(PL_tainted)))    /* Is something tainted? */
1011 #   define TAINTING_get         (cBOOL(UNLIKELY(PL_tainting)))
1012 #   define TAINTING_set(s)      (PL_tainting = cBOOL(s))
1013 #   define TAINT_WARN_get       (PL_taint_warn)
1014 #   define TAINT_WARN_set(s)    (PL_taint_warn = cBOOL(s))
1015 #endif
1016
1017 /* flags used internally only within pp_subst and pp_substcont */
1018 #ifdef PERL_CORE
1019 #  define SUBST_TAINT_STR      1        /* string tainted */
1020 #  define SUBST_TAINT_PAT      2        /* pattern tainted */
1021 #  define SUBST_TAINT_REPL     4        /* replacement tainted */
1022 #  define SUBST_TAINT_RETAINT  8        /* use re'taint' in scope */
1023 #  define SUBST_TAINT_BOOLRET 16        /* return is boolean (don't taint) */
1024 #endif
1025
1026 /* XXX All process group stuff is handled in pp_sys.c.  Should these
1027    defines move there?  If so, I could simplify this a lot. --AD  9/96.
1028 */
1029 /* Process group stuff changed from traditional BSD to POSIX.
1030    perlfunc.pod documents the traditional BSD-style syntax, so we'll
1031    try to preserve that, if possible.
1032 */
1033 #ifdef HAS_SETPGID
1034 #  define BSD_SETPGRP(pid, pgrp)        setpgid((pid), (pgrp))
1035 #elif defined(HAS_SETPGRP) && defined(USE_BSD_SETPGRP)
1036 #  define BSD_SETPGRP(pid, pgrp)        setpgrp((pid), (pgrp))
1037 #elif defined(HAS_SETPGRP2)
1038 #  define BSD_SETPGRP(pid, pgrp)        setpgrp2((pid), (pgrp))
1039 #endif
1040 #if defined(BSD_SETPGRP) && !defined(HAS_SETPGRP)
1041 #  define HAS_SETPGRP  /* Well, effectively it does . . . */
1042 #endif
1043
1044 #ifdef HAS_GETPGID
1045 #  define BSD_GETPGRP(pid)              getpgid((pid))
1046 #elif defined(HAS_GETPGRP) && defined(USE_BSD_GETPGRP)
1047 #  define BSD_GETPGRP(pid)              getpgrp((pid))
1048 #elif defined(HAS_GETPGRP2)
1049 #  define BSD_GETPGRP(pid)              getpgrp2((pid))
1050 #endif
1051 #if defined(BSD_GETPGRP) && !defined(HAS_GETPGRP)
1052 #  define HAS_GETPGRP  /* Well, effectively it does . . . */
1053 #endif
1054
1055 /* These are not exact synonyms, since setpgrp() and getpgrp() may
1056    have different behaviors, but perl.h used to define USE_BSDPGRP
1057    (prior to 5.003_05) so some extension might depend on it.
1058 */
1059 #if defined(USE_BSD_SETPGRP) || defined(USE_BSD_GETPGRP)
1060 #  ifndef USE_BSDPGRP
1061 #    define USE_BSDPGRP
1062 #  endif
1063 #endif
1064
1065 /* This define exists only for compatibility. It used to mean "my_setenv and
1066  * friends should use setenv/putenv, instead of manipulating environ directly",
1067  * which is now always the case. It's still defined to prevent XS modules from
1068  * using the no longer existing PL_use_safe_putenv variable.
1069  */
1070 #define PERL_USE_SAFE_PUTENV
1071
1072 /* HP-UX 10.X CMA (Common Multithreaded Architecture) insists that
1073    pthread.h must be included before all other header files.
1074 */
1075 #if defined(USE_ITHREADS) && defined(PTHREAD_H_FIRST) && defined(I_PTHREAD)
1076 #  include <pthread.h>
1077 #endif
1078
1079 #include <sys/types.h>
1080
1081 #  ifdef I_WCHAR
1082 #    include <wchar.h>
1083 #  endif
1084
1085 # include <stdarg.h>
1086
1087 #ifdef I_STDINT
1088 # include <stdint.h>
1089 #endif
1090
1091 #include <ctype.h>
1092 #include <float.h>
1093 #include <limits.h>
1094
1095 #ifdef METHOD   /* Defined by OSF/1 v3.0 by ctype.h */
1096 #undef METHOD
1097 #endif
1098
1099 #ifdef I_LOCALE
1100 #   include <locale.h>
1101 #endif
1102
1103 #ifdef NEED_XLOCALE_H
1104 #   include <xlocale.h>
1105 #endif
1106
1107 #include "perl_langinfo.h"    /* Needed for _NL_LOCALE_NAME */
1108
1109 /* =========================================================================
1110  * The defines from here to the following ===== line are unfortunately
1111  * duplicated in makedef.pl, and changes here MUST also be made there */
1112
1113 /* If not forbidden, we enable locale handling if either 1) the POSIX 2008
1114  * functions are available, or 2) just the setlocale() function.  This logic is
1115  * repeated in t/loc_tools.pl and makedef.pl;  The three should be kept in
1116  * sync. */
1117 #if   ! defined(NO_LOCALE)
1118
1119 #  if ! defined(NO_POSIX_2008_LOCALE)           \
1120    &&   defined(HAS_NEWLOCALE)                  \
1121    &&   defined(HAS_USELOCALE)                  \
1122    &&   defined(HAS_DUPLOCALE)                  \
1123    &&   defined(HAS_FREELOCALE)                 \
1124    &&   defined(LC_ALL_MASK)
1125
1126     /* For simplicity, the code is written to assume that any platform advanced
1127      * enough to have the Posix 2008 locale functions has LC_ALL.  The final
1128      * test above makes sure that assumption is valid */
1129
1130 #    define HAS_POSIX_2008_LOCALE
1131 #    define USE_LOCALE
1132 #  elif defined(HAS_SETLOCALE)
1133 #    define USE_LOCALE
1134 #  endif
1135 #endif
1136
1137 /* end of makedef.pl logic duplication.  But there are other groups below.
1138  * ========================================================================= */
1139
1140 #ifdef USE_LOCALE
1141 #   define HAS_SKIP_LOCALE_INIT /* Solely for XS code to test for this
1142                                    #define */
1143 #   if !defined(NO_LOCALE_COLLATE) && defined(LC_COLLATE) \
1144        && defined(HAS_STRXFRM)
1145 #       define USE_LOCALE_COLLATE
1146 #   endif
1147 #   if !defined(NO_LOCALE_CTYPE) && defined(LC_CTYPE)
1148 #       define USE_LOCALE_CTYPE
1149 #   endif
1150 #   if !defined(NO_LOCALE_NUMERIC) && defined(LC_NUMERIC)
1151 #       define USE_LOCALE_NUMERIC
1152 #   endif
1153 #   if !defined(NO_LOCALE_MESSAGES) && defined(LC_MESSAGES)
1154 #       define USE_LOCALE_MESSAGES
1155 #   endif
1156 #   if !defined(NO_LOCALE_MONETARY) && defined(LC_MONETARY)
1157 #       define USE_LOCALE_MONETARY
1158 #   endif
1159 #   if !defined(NO_LOCALE_TIME) && defined(LC_TIME)
1160 #       define USE_LOCALE_TIME
1161 #   endif
1162 #   if !defined(NO_LOCALE_ADDRESS) && defined(LC_ADDRESS)
1163 #       define USE_LOCALE_ADDRESS
1164 #   endif
1165 #   if !defined(NO_LOCALE_IDENTIFICATION) && defined(LC_IDENTIFICATION)
1166 #       define USE_LOCALE_IDENTIFICATION
1167 #   endif
1168 #   if !defined(NO_LOCALE_MEASUREMENT) && defined(LC_MEASUREMENT)
1169 #       define USE_LOCALE_MEASUREMENT
1170 #   endif
1171 #   if !defined(NO_LOCALE_PAPER) && defined(LC_PAPER)
1172 #       define USE_LOCALE_PAPER
1173 #   endif
1174 #   if !defined(NO_LOCALE_TELEPHONE) && defined(LC_TELEPHONE)
1175 #       define USE_LOCALE_TELEPHONE
1176 #   endif
1177 #   if !defined(NO_LOCALE_NAME) && defined(LC_NAME)
1178 #       define USE_LOCALE_NAME
1179 #   endif
1180 #   if !defined(NO_LOCALE_SYNTAX) && defined(LC_SYNTAX)
1181 #       define USE_LOCALE_SYNTAX
1182 #   endif
1183 #   if !defined(NO_LOCALE_TOD) && defined(LC_TOD)
1184 #       define USE_LOCALE_TOD
1185 #   endif
1186 #endif
1187
1188 /* XXX The Configure probe for categories must be updated when adding new
1189  * categories here */
1190
1191 /* Create an enum that allows translation between the arbitrary locale category
1192  * integers that a platform has, and our desired values that range from 0..n
1193  * which makes array indexing feasible.
1194  *
1195  * In locale.c, there are a bunch of parallel arrays corresponding to this
1196  * enum.  The first element of each corresponds with the first enum value here,
1197  * and so on.  That means this enum must be in identical order with those
1198  * arrays.  This is guaranteed by using locale_table.h in all instances.
1199  * (There are also asserts in locale.c that should fail if this gets
1200  * out-of-sync.)  So, if the platform doesn't have LC_CTYPE, but does have
1201  * LC_NUMERIC, the code below will cause LC_NUMERIC_INDEX_ to be defined to be
1202  * 0.  That way the foo_INDEX_ values are contiguous non-negative integers,
1203  * regardless of how the platform defines the actual locale categories.
1204  */
1205 typedef enum {
1206
1207 #ifdef USE_LOCALE
1208
1209 /* Now create LC_foo_INDEX_ values for just those categories used on this
1210  * system */
1211 #    undef PERL_LOCALE_TABLE_ENTRY
1212 #    define PERL_LOCALE_TABLE_ENTRY(name, call_back)  name ## _INDEX_,
1213 #    include "locale_table.h"
1214
1215 #endif  /* USE_LOCALE */
1216
1217     LC_ALL_INDEX_   /* Always defined, even if no LC_ALL on system */
1218
1219 } locale_category_index;
1220
1221 #ifdef USE_LOCALE
1222
1223 /* And a count of all the locale categories, mainly for use in array
1224  * declarations */
1225 #  define LOCALE_CATEGORIES_COUNT_        (LC_ALL_INDEX_ + 1)
1226
1227 /* =========================================================================
1228  * The defines from here to the following ===== line are unfortunately
1229  * duplicated in makedef.pl, and changes here MUST also be made there */
1230
1231 #  if defined(USE_ITHREADS) && ! defined(NO_LOCALE_THREADS)
1232 #    define USE_LOCALE_THREADS
1233 #  endif
1234
1235    /* Use POSIX 2008 locales if available, and no alternative exists
1236     * ('setlocale()' is the alternative); or is threaded and not forbidden to
1237     * use them */
1238 #  if (       defined(HAS_POSIX_2008_LOCALE)                                \
1239        && (    ! defined(HAS_SETLOCALE)                                     \
1240            || (     defined(USE_LOCALE_THREADS)                             \
1241                && ! defined(NO_POSIX_2008_LOCALE)))                         \
1242                && ! defined(NO_THREAD_SAFE_LOCALE))
1243 #    define USE_POSIX_2008_LOCALE
1244 #  endif
1245
1246    /* On threaded builds, use thread-safe locales if they are available and not
1247     * forbidden.  Availability is when we are using POSIX 2008 locales, or
1248     * Windows for any vintage recent enough to have _MSC_VER defined */
1249 #  if defined(USE_LOCALE_THREADS) && ! defined(NO_THREAD_SAFE_LOCALE)
1250 #    if defined(USE_POSIX_2008_LOCALE) || (defined(WIN32) && defined(_MSC_VER))
1251 #      define USE_THREAD_SAFE_LOCALE
1252 #    endif
1253 #  endif
1254
1255 #  include "perl_langinfo.h"    /* Needed for _NL_LOCALE_NAME */
1256
1257 #  ifdef USE_POSIX_2008_LOCALE
1258 #    if  defined(HAS_QUERYLOCALE)                                           \
1259               /* Use querylocale if has it, or has the glibc internal       \
1260                * undocumented equivalent. */                                \
1261      || (     defined(_NL_LOCALE_NAME)                                      \
1262               /* And asked for */                                           \
1263          &&   defined(USE_NL_LOCALE_NAME)                                   \
1264               /* nl_langinfo_l almost certainly will exist on systems that  \
1265                * have _NL_LOCALE_NAME, so there is nothing lost by          \
1266                * requiring it instead of also allowing plain nl_langinfo(). \
1267                * And experience indicates that its glibc implementation is  \
1268                * thread-safe, eliminating code complications */             \
1269          &&   defined(HAS_NL_LANGINFO_L)                                    \
1270                /* On systems that accept any locale name, the real          \
1271                 * underlying locale is often returned by this internal      \
1272                 * item, so we can't use it */                               \
1273          && ! defined(SETLOCALE_ACCEPTS_ANY_LOCALE_NAME))
1274 #      define USE_QUERYLOCALE
1275 #    endif
1276 #  endif
1277
1278    /* POSIX 2008 has no means of finding out the current locale without a
1279     * querylocale; so must keep track of it ourselves */
1280 #  if (defined(USE_POSIX_2008_LOCALE) && ! defined(USE_QUERYLOCALE))
1281 #    define USE_PL_CURLOCALES
1282 #  endif
1283
1284 #  if defined(WIN32)
1285
1286       /* We need to be able to map the current value of what the tTHX context
1287        * thinks LC_ALL is so as to inform the Windows libc when switching
1288        * contexts. */
1289 #    if defined(USE_THREAD_SAFE_LOCALE)
1290 #      define USE_PL_CUR_LC_ALL
1291 #    endif
1292
1293      /* Microsoft documentation reads in the change log for VS 2015: "The
1294       * localeconv function declared in locale.h now works correctly when
1295       * per-thread locale is enabled. In previous versions of the library, this
1296       * function would return the lconv data for the global locale, not the
1297       * thread's locale." */
1298 #      ifndef _MSC_VER
1299 #        define TS_W32_BROKEN_LOCALECONV
1300 #      elif _MSC_VER < 1900
1301 #        define TS_W32_BROKEN_LOCALECONV
1302 #      endif
1303 #  endif
1304
1305    /* POSIX 2008 and Windows with thread-safe locales keep locale information
1306     * in libc data.  Therefore we must inform their libc's when the context
1307     * switches */
1308 #  if defined(MULTIPLICITY) && (   defined(USE_POSIX_2008_LOCALE)           \
1309                                 || (   defined(WIN32)                       \
1310                                     && defined(USE_THREAD_SAFE_LOCALE)))
1311 #    define USE_PERL_SWITCH_LOCALE_CONTEXT
1312 #  endif
1313 #endif  /* End of USE_LOCALE */
1314
1315 /* end of makedef.pl logic duplication
1316  * ========================================================================= */
1317
1318 #ifdef PERL_CORE
1319
1320 /* These typedefs are used in locale.c only (and documented there), but defined
1321  * here so that embed.fnc can generate the proper prototypes. */
1322
1323 typedef enum {  /* Is the locale UTF8? */
1324     LOCALE_NOT_UTF8,
1325     LOCALE_IS_UTF8,
1326     LOCALE_UTF8NESS_UNKNOWN
1327 } locale_utf8ness_t;
1328
1329 typedef struct {
1330     const char *name;
1331     size_t offset;
1332 } lconv_offset_t;
1333
1334
1335 typedef enum {
1336     invalid,
1337     no_array,
1338     full_array
1339 } parse_LC_ALL_string_return;
1340
1341 #endif
1342
1343 #include <setjmp.h>
1344
1345 #ifdef I_SYS_PARAM
1346 #   ifdef PARAM_NEEDS_TYPES
1347 #       include <sys/types.h>
1348 #   endif
1349 #   include <sys/param.h>
1350 #endif
1351
1352 /* On BSD-derived systems, <sys/param.h> defines BSD to a year-month
1353    value something like 199306.  This may be useful if no more-specific
1354    feature test is available.
1355 */
1356 #if defined(BSD)
1357 #   ifndef BSDish
1358 #       define BSDish
1359 #   endif
1360 #endif
1361
1362 /* Use all the "standard" definitions */
1363 #include <stdlib.h>
1364
1365 /* If this causes problems, set i_unistd=undef in the hint file.  */
1366 #ifdef I_UNISTD
1367 #    if defined(__amigaos4__)
1368 #        ifdef I_NETINET_IN
1369 #            include <netinet/in.h>
1370 #        endif
1371 #   endif
1372 #   include <unistd.h>
1373 #   if defined(__amigaos4__)
1374 /* Under AmigaOS 4 newlib.library provides an environ.  However using
1375  * it doesn't give us enough control over inheritance of variables by
1376  * subshells etc. so replace with custom version based on abc-shell
1377  * code. */
1378 extern char **myenviron;
1379 #       undef environ
1380 #       define environ myenviron
1381 #   endif
1382 #endif
1383
1384 /* for WCOREDUMP */
1385 #ifdef I_SYS_WAIT
1386 #   include <sys/wait.h>
1387 #endif
1388
1389 #if defined(HAS_SYSCALL) && !defined(HAS_SYSCALL_PROTO)
1390 EXTERN_C int syscall(int, ...);
1391 #endif
1392
1393 #if defined(HAS_USLEEP) && !defined(HAS_USLEEP_PROTO)
1394 EXTERN_C int usleep(unsigned int);
1395 #endif
1396
1397 /* Macros for correct constant construction.  These are in C99 <stdint.h>
1398  * (so they will not be available in strict C89 mode), but they are nice, so
1399  * let's define them if necessary. */
1400
1401 /*
1402 =for apidoc_section $integer
1403 =for apidoc    Am|I16|INT16_C|number
1404 =for apidoc_item |I32|INT32_C|number
1405 =for apidoc_item |I64|INT64_C|number
1406
1407 Returns a token the C compiler recognizes for the constant C<number> of the
1408 corresponding integer type on the machine.
1409
1410 If the machine does not have a 64-bit type, C<INT64_C> is undefined.
1411 Use C<L</INTMAX_C>> to get the largest type available on the platform.
1412
1413 =for apidoc    Am|U16|UINT16_C|number
1414 =for apidoc_item |U32|UINT32_C|number
1415 =for apidoc_item |U64|UINT64_C|number
1416
1417 Returns a token the C compiler recognizes for the constant C<number> of the
1418 corresponding unsigned integer type on the machine.
1419
1420 If the machine does not have a 64-bit type, C<UINT64_C> is undefined.
1421 Use C<L</UINTMAX_C>> to get the largest type available on the platform.
1422
1423
1424 =cut
1425 */
1426 #ifndef UINT16_C
1427 #  if INTSIZE >= 2
1428 #    define UINT16_C(x) ((U16_TYPE)x##U)
1429 #  else
1430 #    define UINT16_C(x) ((U16_TYPE)x##UL)
1431 #  endif
1432 #endif
1433
1434 #ifndef UINT32_C
1435 #  if INTSIZE >= 4
1436 #    define UINT32_C(x) ((U32_TYPE)x##U)
1437 #  else
1438 #    define UINT32_C(x) ((U32_TYPE)x##UL)
1439 #  endif
1440 #endif
1441
1442 #ifdef I_STDINT
1443     typedef intmax_t  PERL_INTMAX_T;
1444     typedef uintmax_t PERL_UINTMAX_T;
1445 #endif
1446
1447 /* N.B.  We use QUADKIND here instead of HAS_QUAD here, because that doesn't
1448  * actually mean what it has always been documented to mean (see RT #119753)
1449  * and is explicitly turned off outside of core with dire warnings about
1450  * removing the undef. */
1451
1452 #if defined(QUADKIND)
1453 #  undef PeRl_INT64_C
1454 #  undef PeRl_UINT64_C
1455 /* Prefer the native integer types (int and long) over long long
1456  * (which is not C89) and Win32-specific __int64. */
1457 #  if QUADKIND == QUAD_IS_INT && INTSIZE == 8
1458 #    define PeRl_INT64_C(c)     (c)
1459 #    define PeRl_UINT64_C(c)    CAT2(c,U)
1460 #  endif
1461 #  if QUADKIND == QUAD_IS_LONG && LONGSIZE == 8
1462 #    define PeRl_INT64_C(c)     CAT2(c,L)
1463 #    define PeRl_UINT64_C(c)    CAT2(c,UL)
1464 #  endif
1465 #  if QUADKIND == QUAD_IS_LONG_LONG && defined(HAS_LONG_LONG)
1466 #    define PeRl_INT64_C(c)     CAT2(c,LL)
1467 #    define PeRl_UINT64_C(c)    CAT2(c,ULL)
1468 #  endif
1469 #  if QUADKIND == QUAD_IS___INT64
1470 #    define PeRl_INT64_C(c)     CAT2(c,I64)
1471 #    define PeRl_UINT64_C(c)    CAT2(c,UI64)
1472 #  endif
1473 #  ifndef PeRl_INT64_C
1474 #    define PeRl_INT64_C(c)     ((I64)(c)) /* last resort */
1475 #    define PeRl_UINT64_C(c)    ((U64TYPE)(c))
1476 #  endif
1477 /* In OS X the INT64_C/UINT64_C are defined with LL/ULL, which will
1478  * not fly with C89-pedantic gcc, so let's undefine them first so that
1479  * we can redefine them with our native integer preferring versions. */
1480 #  if defined(PERL_DARWIN) && defined(PERL_GCC_PEDANTIC)
1481 #    undef INT64_C
1482 #    undef UINT64_C
1483 #  endif
1484 #  ifndef INT64_C
1485 #    define INT64_C(c) PeRl_INT64_C(c)
1486 #  endif
1487 #  ifndef UINT64_C
1488 #    define UINT64_C(c) PeRl_UINT64_C(c)
1489 #  endif
1490
1491 /*
1492 =for apidoc_section $integer
1493 =for apidoc Am||INTMAX_C|number
1494 Returns a token the C compiler recognizes for the constant C<number> of the
1495 widest integer type on the machine.  For example, if the machine has C<long
1496 long>s, C<INTMAX_C(-1)> would yield
1497
1498  -1LL
1499
1500 See also, for example, C<L</INT32_C>>.
1501
1502 Use L</IV> to declare variables of the maximum usable size on this platform.
1503
1504 =for apidoc Am||UINTMAX_C|number
1505 Returns a token the C compiler recognizes for the constant C<number> of the
1506 widest unsigned integer type on the machine.  For example, if the machine has
1507 C<long>s, C<UINTMAX_C(1)> would yield
1508
1509  1UL
1510
1511 See also, for example, C<L</UINT32_C>>.
1512
1513 Use L</UV> to declare variables of the maximum usable size on this platform.
1514
1515 =cut
1516 */
1517
1518 #  ifndef I_STDINT
1519     typedef I64TYPE PERL_INTMAX_T;
1520     typedef U64TYPE PERL_UINTMAX_T;
1521 #  endif
1522 #  ifndef INTMAX_C
1523 #    define INTMAX_C(c) INT64_C(c)
1524 #  endif
1525 #  ifndef UINTMAX_C
1526 #    define UINTMAX_C(c) UINT64_C(c)
1527 #  endif
1528
1529 #else  /* below QUADKIND is undefined */
1530
1531 /* Perl doesn't work on 16 bit systems, so must be 32 bit */
1532 #  ifndef I_STDINT
1533     typedef I32TYPE PERL_INTMAX_T;
1534     typedef U32TYPE PERL_UINTMAX_T;
1535 #  endif
1536 #  ifndef INTMAX_C
1537 #    define INTMAX_C(c) INT32_C(c)
1538 #  endif
1539 #  ifndef UINTMAX_C
1540 #    define UINTMAX_C(c) UINT32_C(c)
1541 #  endif
1542
1543 #endif  /* no QUADKIND */
1544
1545 #ifdef PERL_CORE
1546
1547 /* byte-swapping functions for big-/little-endian conversion */
1548 # define _swab_16_(x) ((U16)( \
1549          (((U16)(x) & UINT16_C(0x00ff)) << 8) | \
1550          (((U16)(x) & UINT16_C(0xff00)) >> 8) ))
1551
1552 # define _swab_32_(x) ((U32)( \
1553          (((U32)(x) & UINT32_C(0x000000ff)) << 24) | \
1554          (((U32)(x) & UINT32_C(0x0000ff00)) <<  8) | \
1555          (((U32)(x) & UINT32_C(0x00ff0000)) >>  8) | \
1556          (((U32)(x) & UINT32_C(0xff000000)) >> 24) ))
1557
1558 # ifdef HAS_QUAD
1559 #  define _swab_64_(x) ((U64)( \
1560           (((U64)(x) & UINT64_C(0x00000000000000ff)) << 56) | \
1561           (((U64)(x) & UINT64_C(0x000000000000ff00)) << 40) | \
1562           (((U64)(x) & UINT64_C(0x0000000000ff0000)) << 24) | \
1563           (((U64)(x) & UINT64_C(0x00000000ff000000)) <<  8) | \
1564           (((U64)(x) & UINT64_C(0x000000ff00000000)) >>  8) | \
1565           (((U64)(x) & UINT64_C(0x0000ff0000000000)) >> 24) | \
1566           (((U64)(x) & UINT64_C(0x00ff000000000000)) >> 40) | \
1567           (((U64)(x) & UINT64_C(0xff00000000000000)) >> 56) ))
1568 # endif
1569
1570 /* Maximum level of recursion */
1571 #ifndef PERL_SUB_DEPTH_WARN
1572 #define PERL_SUB_DEPTH_WARN 100
1573 #endif
1574
1575 #endif /* PERL_CORE */
1576
1577 /* Maximum number of args that may be passed to an OP_MULTICONCAT op.
1578  * It determines the size of local arrays in S_maybe_multiconcat() and
1579  * pp_multiconcat().
1580  */
1581 #define PERL_MULTICONCAT_MAXARG 64
1582
1583 /* The indexes of fields of a multiconcat aux struct.
1584  * The fixed fields are followed by nargs+1 const segment lengths,
1585  * and if utf8 and non-utf8 differ, a second nargs+1 set for utf8.
1586  */
1587
1588 #define PERL_MULTICONCAT_IX_NARGS     0 /* number of arguments */
1589 #define PERL_MULTICONCAT_IX_PLAIN_PV  1 /* non-utf8 constant string */
1590 #define PERL_MULTICONCAT_IX_PLAIN_LEN 2 /* non-utf8 constant string length */
1591 #define PERL_MULTICONCAT_IX_UTF8_PV   3 /* utf8 constant string */
1592 #define PERL_MULTICONCAT_IX_UTF8_LEN  4 /* utf8 constant string length */
1593 #define PERL_MULTICONCAT_IX_LENGTHS   5 /* first of nargs+1 const segment lens */
1594 #define PERL_MULTICONCAT_HEADER_SIZE 5 /* The number of fields of a
1595                                            multiconcat header */
1596
1597 /* We no longer default to creating a new SV for GvSV.
1598    Do this before embed.  */
1599 #ifndef PERL_CREATE_GVSV
1600 #  ifndef PERL_DONT_CREATE_GVSV
1601 #    define PERL_DONT_CREATE_GVSV
1602 #  endif
1603 #endif
1604
1605 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
1606 #define PERL_USES_PL_PIDSTATUS
1607 #endif
1608
1609 #if !defined(OS2) && !defined(WIN32)
1610 #define PERL_DEFAULT_DO_EXEC3_IMPLEMENTATION
1611 #endif
1612
1613 #define MEM_SIZE Size_t
1614
1615 /* av_extend and analogues enforce a minimum number of array elements.
1616  * This has been 4 elements (so a minimum key size of 3) for a long
1617  * time, but the rationale behind this seems to have been lost to the
1618  * mists of time. */
1619 #ifndef PERL_ARRAY_NEW_MIN_KEY
1620 #define PERL_ARRAY_NEW_MIN_KEY 3
1621 #endif
1622
1623 /* Functions like Perl_sv_grow mandate a minimum string size.
1624  * This was 10 bytes for a long time, the rationale for which seems lost
1625  * to the mists of time. However, this does not correlate to what modern
1626  * malloc implementations will actually return, in particular the fact
1627  * that chunks are almost certainly some multiple of pointer size. The
1628  * default has therefore been revised to a more useful approximation.
1629  * Notes: The following is specifically conservative for 64 bit, since
1630  * most dlmalloc derivatives seem to serve a 3xPTRSIZE minimum chunk,
1631  * so the below perhaps should be:
1632  *     ((PTRSIZE == 4) ? 12 : 24)
1633  * Configure probes for malloc_good_size, malloc_actual_size etc.
1634  * could be revised to record the actual minimum chunk size, to which
1635  * PERL_STRLEN_NEW_MIN could then be set.
1636  */
1637 #ifndef PERL_STRLEN_NEW_MIN
1638 #define PERL_STRLEN_NEW_MIN ((PTRSIZE == 4) ? 12 : 16)
1639 #endif
1640
1641 /* Round all values passed to malloc up, by default to a multiple of
1642    sizeof(size_t)
1643 */
1644 #ifndef PERL_STRLEN_ROUNDUP_QUANTUM
1645 #define PERL_STRLEN_ROUNDUP_QUANTUM Size_t_size
1646 #endif
1647
1648 /* sv_grow() will expand strings by at least a certain percentage of
1649    the previously *used* length to avoid excessive calls to realloc().
1650    The default is 25% of the current length.
1651 */
1652 #ifndef PERL_STRLEN_EXPAND_SHIFT
1653 #  define PERL_STRLEN_EXPAND_SHIFT 2
1654 #endif
1655
1656 /* This use of offsetof() requires /Zc:offsetof- for VS2017 (and presumably
1657  * onwards) when building Socket.xs, but we can just use a different definition
1658  * for STRUCT_OFFSET instead. */
1659 #if defined(WIN32) && defined(_MSC_VER) && _MSC_VER >= 1910
1660 #  define STRUCT_OFFSET(s,m)  (Size_t)(&(((s *)0)->m))
1661 #else
1662 #  include <stddef.h>
1663 #  define STRUCT_OFFSET(s,m)  offsetof(s,m)
1664 #endif
1665
1666 /* ptrdiff_t is C11, so undef it under pedantic builds.  (Actually it is
1667  * in C89, but apparently there are platforms where it doesn't exist.  See
1668  * thread beginning at http://nntp.perl.org/group/perl.perl5.porters/251541.)
1669  * */
1670 #ifdef PERL_GCC_PEDANTIC
1671 #   undef HAS_PTRDIFF_T
1672 #endif
1673
1674 #ifdef HAS_PTRDIFF_T
1675 #  define Ptrdiff_t ptrdiff_t
1676 #else
1677 #  define Ptrdiff_t SSize_t
1678 #endif
1679
1680 #  include <string.h>
1681
1682 /* This comes after <stdlib.h> so we don't try to change the standard
1683  * library prototypes; we'll use our own in proto.h instead. */
1684
1685 #ifdef MYMALLOC
1686 #  ifdef PERL_POLLUTE_MALLOC
1687 #   ifndef PERL_EXTMALLOC_DEF
1688 #    define Perl_malloc         malloc
1689 #    define Perl_calloc         calloc
1690 #    define Perl_realloc        realloc
1691 #    define Perl_mfree          free
1692 #   endif
1693 #  else
1694 #    define EMBEDMYMALLOC       /* for compatibility */
1695 #  endif
1696
1697 #  define safemalloc  Perl_malloc
1698 #  define safecalloc  Perl_calloc
1699 #  define saferealloc Perl_realloc
1700 #  define safefree    Perl_mfree
1701 #  define CHECK_MALLOC_TOO_LATE_FOR_(code)      STMT_START {            \
1702         if (!TAINTING_get && MallocCfg_ptr[MallocCfg_cfg_env_read])     \
1703                 code;                                                   \
1704     } STMT_END
1705 #  define CHECK_MALLOC_TOO_LATE_FOR(ch)                         \
1706         CHECK_MALLOC_TOO_LATE_FOR_(MALLOC_TOO_LATE_FOR(ch))
1707 #  define panic_write2(s)               write(2, s, strlen(s))
1708 #  define CHECK_MALLOC_TAINT(newval)                            \
1709         CHECK_MALLOC_TOO_LATE_FOR_(                             \
1710                 if (newval) {                                   \
1711                   PERL_UNUSED_RESULT(panic_write2("panic: tainting with $ENV{PERL_MALLOC_OPT}\n"));\
1712                   exit(1); })
1713 #  define MALLOC_CHECK_TAINT(argc,argv,env)                     \
1714     STMT_START {                                                \
1715         if (doing_taint(argc,argv,env)) {                       \
1716             MallocCfg_ptr[MallocCfg_skip_cfg_env] = 1;          \
1717         }                                                       \
1718     } STMT_END;
1719 #else  /* MYMALLOC */
1720 #  define safemalloc  safesysmalloc
1721 #  define safecalloc  safesyscalloc
1722 #  define saferealloc safesysrealloc
1723 #  define safefree    safesysfree
1724 #  define CHECK_MALLOC_TOO_LATE_FOR(ch)         ((void)0)
1725 #  define CHECK_MALLOC_TAINT(newval)            ((void)0)
1726 #  define MALLOC_CHECK_TAINT(argc,argv,env)
1727 #endif /* MYMALLOC */
1728
1729 /* diag_listed_as: "-T" is on the #! line, it must also be used on the command line */
1730 #define TOO_LATE_FOR_(ch,what)  Perl_croak(aTHX_ "\"-%c\" is on the #! line, it must also be used on the command line%s", (char)(ch), what)
1731 #define TOO_LATE_FOR(ch)        TOO_LATE_FOR_(ch, "")
1732 #define MALLOC_TOO_LATE_FOR(ch) TOO_LATE_FOR_(ch, " with $ENV{PERL_MALLOC_OPT}")
1733 #define MALLOC_CHECK_TAINT2(argc,argv)  MALLOC_CHECK_TAINT(argc,argv,NULL)
1734
1735 /*
1736 =for apidoc Am|void|memzero|void * d|Size_t l
1737 Set the C<l> bytes starting at C<*d> to all zeroes.
1738
1739 =cut
1740 */
1741 #ifndef memzero
1742 #   define memzero(d,l) memset(d,0,l)
1743 #endif
1744
1745 #ifdef I_NETINET_IN
1746 #   include <netinet/in.h>
1747 #endif
1748
1749 #ifdef I_ARPA_INET
1750 #   include <arpa/inet.h>
1751 #endif
1752
1753 #ifdef I_SYS_STAT
1754 #   include <sys/stat.h>
1755 #endif
1756
1757 /* Microsoft VC's sys/stat.h defines all S_Ixxx macros except S_IFIFO.
1758    This definition should ideally go into win32/win32.h, but S_IFIFO is
1759    used later here in perl.h before win32/win32.h is being included. */
1760 #if !defined(S_IFIFO) && defined(_S_IFIFO)
1761 #   define S_IFIFO _S_IFIFO
1762 #endif
1763
1764 /* The stat macros for Unisoft System V/88 (and derivatives
1765    like UTekV) are broken, sometimes giving false positives.  Undefine
1766    them here and let the code below set them to proper values.
1767
1768    The ghs macro stands for GreenHills Software C-1.8.5 which
1769    is the C compiler for sysV88 and the various derivatives.
1770    This header file bug is corrected in gcc-2.5.8 and later versions.
1771    --Kaveh Ghazi (ghazi@noc.rutgers.edu) 10/3/94.  */
1772
1773 #if defined(m88k) && defined(ghs)
1774 #   undef S_ISDIR
1775 #   undef S_ISCHR
1776 #   undef S_ISBLK
1777 #   undef S_ISREG
1778 #   undef S_ISFIFO
1779 #   undef S_ISLNK
1780 #endif
1781
1782 #include <time.h>
1783
1784 #ifdef I_SYS_TIME
1785 #   ifdef I_SYS_TIME_KERNEL
1786 #       define KERNEL
1787 #   endif
1788 #   include <sys/time.h>
1789 #   ifdef I_SYS_TIME_KERNEL
1790 #       undef KERNEL
1791 #   endif
1792 #endif
1793
1794 #if defined(HAS_TIMES) && defined(I_SYS_TIMES)
1795 #    include <sys/times.h>
1796 #endif
1797
1798 #include <errno.h>
1799
1800 #if defined(WIN32) && defined(PERL_IMPLICIT_SYS)
1801 #  define WIN32SCK_IS_STDSCK            /* don't pull in custom wsock layer */
1802 #endif
1803
1804 #if defined(HAS_SOCKET) && !defined(WIN32) /* WIN32 handles sockets via win32.h */
1805 # include <sys/socket.h>
1806 # if defined(USE_SOCKS) && defined(I_SOCKS)
1807 #   if !defined(INCLUDE_PROTOTYPES)
1808 #       define INCLUDE_PROTOTYPES /* for <socks.h> */
1809 #       define PERL_SOCKS_NEED_PROTOTYPES
1810 #   endif
1811 #   include <socks.h>
1812 #   ifdef PERL_SOCKS_NEED_PROTOTYPES /* keep cpp space clean */
1813 #       undef INCLUDE_PROTOTYPES
1814 #       undef PERL_SOCKS_NEED_PROTOTYPES
1815 #   endif
1816 # endif
1817 # ifdef I_NETDB
1818 #  include <netdb.h>
1819 # endif
1820 # ifndef ENOTSOCK
1821 #  ifdef I_NET_ERRNO
1822 #   include <net/errno.h>
1823 #  endif
1824 # endif
1825 #endif
1826
1827 /* sockatmark() is so new (2001) that many places might have it hidden
1828  * behind some -D_BLAH_BLAH_SOURCE guard.  The __THROW magic is required
1829  * e.g. in Gentoo, see http://bugs.gentoo.org/show_bug.cgi?id=12605 */
1830 #if defined(HAS_SOCKATMARK) && !defined(HAS_SOCKATMARK_PROTO)
1831 # if defined(__THROW) && defined(__GLIBC__)
1832 int sockatmark(int) __THROW;
1833 # else
1834 int sockatmark(int);
1835 # endif
1836 #endif
1837
1838 #if defined(__osf__) && defined(__cplusplus) && !defined(_XOPEN_SOURCE_EXTENDED) /* Tru64 "cxx" (C++), see hints/dec_osf.sh for why the _XOPEN_SOURCE_EXTENDED cannot be defined. */
1839 EXTERN_C int fchdir(int);
1840 EXTERN_C int flock(int, int);
1841 EXTERN_C int fseeko(FILE *, off_t, int);
1842 EXTERN_C off_t ftello(FILE *);
1843 #endif
1844
1845 #if defined(__SUNPRO_CC) /* SUNWspro CC (C++) */
1846 EXTERN_C char *crypt(const char *, const char *);
1847 #endif
1848
1849 #if defined(__cplusplus) && defined(__CYGWIN__)
1850 EXTERN_C char *crypt(const char *, const char *);
1851 #endif
1852
1853 /*
1854 =for apidoc_section $errno
1855
1856 =for apidoc m|void|SETERRNO|int errcode|int vmserrcode
1857
1858 Set C<errno>, and on VMS set C<vaxc$errno>.
1859
1860 =for apidoc mn|void|dSAVEDERRNO
1861
1862 Declare variables needed to save C<errno> and any operating system
1863 specific error number.
1864
1865 =for apidoc mn|void|dSAVE_ERRNO
1866
1867 Declare variables needed to save C<errno> and any operating system
1868 specific error number, and save them for optional later restoration
1869 by C<RESTORE_ERRNO>.
1870
1871 =for apidoc mn|void|SAVE_ERRNO
1872
1873 Save C<errno> and any operating system specific error number for
1874 optional later restoration by C<RESTORE_ERRNO>.  Requires
1875 C<dSAVEDERRNO> or C<dSAVE_ERRNO> in scope.
1876
1877 =for apidoc mn|void|RESTORE_ERRNO
1878
1879 Restore C<errno> and any operating system specific error number that
1880 was saved by C<dSAVE_ERRNO> or C<RESTORE_ERRNO>.
1881
1882 =cut
1883 */
1884
1885 #ifdef SETERRNO
1886 # undef SETERRNO  /* SOCKS might have defined this */
1887 #endif
1888
1889 #ifdef VMS
1890 #   define SETERRNO(errcode,vmserrcode) \
1891         STMT_START {                    \
1892             set_errno(errcode);         \
1893             set_vaxc_errno(vmserrcode); \
1894         } STMT_END
1895 #   define dSAVEDERRNO    int saved_errno; unsigned saved_vms_errno
1896 #   define dSAVE_ERRNO    int saved_errno = errno; unsigned saved_vms_errno = vaxc$errno
1897 #   define SAVE_ERRNO     ( saved_errno = errno, saved_vms_errno = vaxc$errno )
1898 #   define RESTORE_ERRNO  SETERRNO(saved_errno, saved_vms_errno)
1899
1900 #   define LIB_INVARG           LIB$_INVARG
1901 #   define RMS_DIR              RMS$_DIR
1902 #   define RMS_FAC              RMS$_FAC
1903 #   define RMS_FEX              RMS$_FEX
1904 #   define RMS_FNF              RMS$_FNF
1905 #   define RMS_IFI              RMS$_IFI
1906 #   define RMS_ISI              RMS$_ISI
1907 #   define RMS_PRV              RMS$_PRV
1908 #   define SS_ACCVIO            SS$_ACCVIO
1909 #   define SS_DEVOFFLINE        SS$_DEVOFFLINE
1910 #   define SS_IVCHAN            SS$_IVCHAN
1911 #   define SS_NORMAL            SS$_NORMAL
1912 #   define SS_NOPRIV            SS$_NOPRIV
1913 #   define SS_BUFFEROVF         SS$_BUFFEROVF
1914 #else
1915 #   define LIB_INVARG           0
1916 #   define RMS_DIR              0
1917 #   define RMS_FAC              0
1918 #   define RMS_FEX              0
1919 #   define RMS_FNF              0
1920 #   define RMS_IFI              0
1921 #   define RMS_ISI              0
1922 #   define RMS_PRV              0
1923 #   define SS_ACCVIO            0
1924 #   define SS_DEVOFFLINE        0
1925 #   define SS_IVCHAN            0
1926 #   define SS_NORMAL            0
1927 #   define SS_NOPRIV            0
1928 #   define SS_BUFFEROVF         0
1929 #endif
1930
1931 #ifdef WIN32
1932 #   define dSAVEDERRNO  int saved_errno; DWORD saved_win32_errno
1933 #   define dSAVE_ERRNO  int saved_errno = errno; DWORD saved_win32_errno = GetLastError()
1934 #   define SAVE_ERRNO   ( saved_errno = errno, saved_win32_errno = GetLastError() )
1935 #   define RESTORE_ERRNO ( errno = saved_errno, SetLastError(saved_win32_errno) )
1936 #endif
1937
1938 #ifdef OS2
1939 #   define dSAVEDERRNO  int saved_errno; unsigned long saved_os2_errno
1940 #   define dSAVE_ERRNO  int saved_errno = errno; unsigned long saved_os2_errno = Perl_rc
1941 #   define SAVE_ERRNO   ( saved_errno = errno, saved_os2_errno = Perl_rc )
1942 #   define RESTORE_ERRNO ( errno = saved_errno, Perl_rc = saved_os2_errno )
1943 #endif
1944
1945 #ifndef SETERRNO
1946 #   define SETERRNO(errcode,vmserrcode) (errno = (errcode))
1947 #endif
1948
1949 #ifndef dSAVEDERRNO
1950 #   define dSAVEDERRNO    int saved_errno
1951 #   define dSAVE_ERRNO    int saved_errno = errno
1952 #   define SAVE_ERRNO     (saved_errno = errno)
1953 #   define RESTORE_ERRNO  (errno = saved_errno)
1954 #endif
1955
1956 /*
1957 =for apidoc_section $warning
1958
1959 =for apidoc Amn|SV *|ERRSV
1960
1961 Returns the SV for C<$@>, creating it if needed.
1962
1963 =for apidoc Am|void|CLEAR_ERRSV
1964
1965 Clear the contents of C<$@>, setting it to the empty string.
1966
1967 This replaces any read-only SV with a fresh SV and removes any magic.
1968
1969 =for apidoc Am|void|SANE_ERRSV
1970
1971 Clean up ERRSV so we can safely set it.
1972
1973 This replaces any read-only SV with a fresh writable copy and removes
1974 any magic.
1975
1976 =cut
1977 */
1978
1979 #define ERRSV GvSVn(PL_errgv)
1980
1981 /* contains inlined gv_add_by_type */
1982 #define CLEAR_ERRSV() STMT_START {                                      \
1983     SV ** const svp = &GvSV(PL_errgv);                                  \
1984     if (!*svp) {                                                        \
1985         *svp = newSVpvs("");                                            \
1986     } else if (SvREADONLY(*svp)) {                                      \
1987         SvREFCNT_dec_NN(*svp);                                          \
1988         *svp = newSVpvs("");                                            \
1989     } else {                                                            \
1990         SV *const errsv = *svp;                                         \
1991         SvPVCLEAR(errsv);                                               \
1992         SvPOK_only(errsv);                                              \
1993         if (SvMAGICAL(errsv)) {                                         \
1994             mg_free(errsv);                                             \
1995         }                                                               \
1996     }                                                                   \
1997     } STMT_END
1998
1999 /* contains inlined gv_add_by_type */
2000 #define SANE_ERRSV() STMT_START {                                       \
2001     SV ** const svp = &GvSV(PL_errgv);                                  \
2002     if (!*svp) {                                                        \
2003         *svp = newSVpvs("");                                            \
2004     } else if (SvREADONLY(*svp)) {                                      \
2005         SV *dupsv = newSVsv(*svp);                                      \
2006         SvREFCNT_dec_NN(*svp);                                          \
2007         *svp = dupsv;                                                   \
2008     } else {                                                            \
2009         SV *const errsv = *svp;                                         \
2010         if (SvMAGICAL(errsv)) {                                         \
2011             mg_free(errsv);                                             \
2012         }                                                               \
2013     }                                                                   \
2014     } STMT_END
2015
2016
2017 #ifdef PERL_CORE
2018 # define DEFSV (0 + GvSVn(PL_defgv))
2019 # define DEFSV_set(sv) \
2020     (SvREFCNT_dec(GvSV(PL_defgv)), GvSV(PL_defgv) = SvREFCNT_inc(sv))
2021 # define SAVE_DEFSV                \
2022     (                               \
2023         save_gp(PL_defgv, 0),        \
2024         GvINTRO_off(PL_defgv),        \
2025         SAVEGENERICSV(GvSV(PL_defgv)), \
2026         GvSV(PL_defgv) = NULL           \
2027     )
2028 #else
2029 # define DEFSV GvSVn(PL_defgv)
2030 # define DEFSV_set(sv) (GvSV(PL_defgv) = (sv))
2031 # define SAVE_DEFSV SAVESPTR(GvSV(PL_defgv))
2032 #endif
2033
2034 /*
2035 =for apidoc_section $SV
2036 =for apidoc Amn|SV *|DEFSV
2037 Returns the SV associated with C<$_>
2038
2039 =for apidoc Am|void|DEFSV_set|SV * sv
2040 Associate C<sv> with C<$_>
2041
2042 =for apidoc Amn|void|SAVE_DEFSV
2043 Localize C<$_>.  See L<perlguts/Localizing changes>.
2044
2045 =cut
2046 */
2047
2048 #ifndef errno
2049         extern int errno;     /* ANSI allows errno to be an lvalue expr.
2050                                * For example in multithreaded environments
2051                                * something like this might happen:
2052                                * extern int *_errno(void);
2053                                * #define errno (*_errno()) */
2054 #endif
2055
2056 #define UNKNOWN_ERRNO_MSG "(unknown)"
2057
2058 #ifdef VMS
2059 #define Strerror(e) strerror((e), vaxc$errno)
2060 #else
2061 #define Strerror(e) strerror(e)
2062 #endif
2063
2064 #ifdef I_SYS_IOCTL
2065 #   ifndef _IOCTL_
2066 #       include <sys/ioctl.h>
2067 #   endif
2068 #endif
2069
2070 #if defined(mc300) || defined(mc500) || defined(mc700) || defined(mc6000)
2071 #   ifdef HAS_SOCKETPAIR
2072 #       undef HAS_SOCKETPAIR
2073 #   endif
2074 #   ifdef I_NDBM
2075 #       undef I_NDBM
2076 #   endif
2077 #endif
2078
2079 #ifndef HAS_SOCKETPAIR
2080 #   ifdef HAS_SOCKET
2081 #       define socketpair Perl_my_socketpair
2082 #   endif
2083 #endif
2084
2085 #if INTSIZE == 2
2086 #   define htoni htons
2087 #   define ntohi ntohs
2088 #else
2089 #   define htoni htonl
2090 #   define ntohi ntohl
2091 #endif
2092
2093 /* Configure already sets Direntry_t */
2094 #if defined(I_DIRENT)
2095 #  include <dirent.h>
2096 #elif defined(I_SYS_NDIR)
2097 #  include <sys/ndir.h>
2098 #elif defined(I_SYS_DIR)
2099 #  include <sys/dir.h>
2100 #endif
2101
2102 /*
2103  * The following gobbledygook brought to you on behalf of __STDC__.
2104  * (I could just use #ifndef __STDC__, but this is more bulletproof
2105  * in the face of half-implementations.)
2106  */
2107
2108 #if defined(I_SYSMODE)
2109 #include <sys/mode.h>
2110 #endif
2111
2112 #ifndef S_IFMT
2113 #   ifdef _S_IFMT
2114 #       define S_IFMT _S_IFMT
2115 #   else
2116 #       define S_IFMT 0170000
2117 #   endif
2118 #endif
2119
2120 #ifndef S_ISDIR
2121 #   define S_ISDIR(m) ((m & S_IFMT) == S_IFDIR)
2122 #endif
2123
2124 #ifndef S_ISCHR
2125 #   define S_ISCHR(m) ((m & S_IFMT) == S_IFCHR)
2126 #endif
2127
2128 #ifndef S_ISBLK
2129 #   ifdef S_IFBLK
2130 #       define S_ISBLK(m) ((m & S_IFMT) == S_IFBLK)
2131 #   else
2132 #       define S_ISBLK(m) (0)
2133 #   endif
2134 #endif
2135
2136 #ifndef S_ISREG
2137 #   define S_ISREG(m) ((m & S_IFMT) == S_IFREG)
2138 #endif
2139
2140 #ifndef S_ISFIFO
2141 #   ifdef S_IFIFO
2142 #       define S_ISFIFO(m) ((m & S_IFMT) == S_IFIFO)
2143 #   else
2144 #       define S_ISFIFO(m) (0)
2145 #   endif
2146 #endif
2147
2148 #ifndef S_ISLNK
2149 #  ifdef _S_ISLNK
2150 #    define S_ISLNK(m) _S_ISLNK(m)
2151 #  elif defined(_S_IFLNK)
2152 #    define S_ISLNK(m) ((m & S_IFMT) == _S_IFLNK)
2153 #  elif defined(S_IFLNK)
2154 #    define S_ISLNK(m) ((m & S_IFMT) == S_IFLNK)
2155 #  else
2156 #    define S_ISLNK(m) (0)
2157 #  endif
2158 #endif
2159
2160 #ifndef S_ISSOCK
2161 #  ifdef _S_ISSOCK
2162 #    define S_ISSOCK(m) _S_ISSOCK(m)
2163 #  elif defined(_S_IFSOCK)
2164 #    define S_ISSOCK(m) ((m & S_IFMT) == _S_IFSOCK)
2165 #  elif defined(S_IFSOCK)
2166 #    define S_ISSOCK(m) ((m & S_IFMT) == S_IFSOCK)
2167 #  else
2168 #    define S_ISSOCK(m) (0)
2169 #  endif
2170 #endif
2171
2172 #ifndef S_IRUSR
2173 #   ifdef S_IREAD
2174 #       define S_IRUSR S_IREAD
2175 #       define S_IWUSR S_IWRITE
2176 #       define S_IXUSR S_IEXEC
2177 #   else
2178 #       define S_IRUSR 0400
2179 #       define S_IWUSR 0200
2180 #       define S_IXUSR 0100
2181 #   endif
2182 #endif
2183
2184 #ifndef S_IRGRP
2185 #   ifdef S_IRUSR
2186 #       define S_IRGRP (S_IRUSR>>3)
2187 #       define S_IWGRP (S_IWUSR>>3)
2188 #       define S_IXGRP (S_IXUSR>>3)
2189 #   else
2190 #       define S_IRGRP 0040
2191 #       define S_IWGRP 0020
2192 #       define S_IXGRP 0010
2193 #   endif
2194 #endif
2195
2196 #ifndef S_IROTH
2197 #   ifdef S_IRUSR
2198 #       define S_IROTH (S_IRUSR>>6)
2199 #       define S_IWOTH (S_IWUSR>>6)
2200 #       define S_IXOTH (S_IXUSR>>6)
2201 #   else
2202 #       define S_IROTH 0040
2203 #       define S_IWOTH 0020
2204 #       define S_IXOTH 0010
2205 #   endif
2206 #endif
2207
2208 #ifndef S_ISUID
2209 #   define S_ISUID 04000
2210 #endif
2211
2212 #ifndef S_ISGID
2213 #   define S_ISGID 02000
2214 #endif
2215
2216 #ifndef S_IRWXU
2217 #   define S_IRWXU (S_IRUSR|S_IWUSR|S_IXUSR)
2218 #endif
2219
2220 #ifndef S_IRWXG
2221 #   define S_IRWXG (S_IRGRP|S_IWGRP|S_IXGRP)
2222 #endif
2223
2224 #ifndef S_IRWXO
2225 #   define S_IRWXO (S_IROTH|S_IWOTH|S_IXOTH)
2226 #endif
2227
2228 /* Haiku R1 seems to define S_IREAD and S_IWRITE in <posix/fcntl.h>
2229  * which would get included through <sys/file.h >, but that is 3000
2230  * lines in the future.  --jhi */
2231
2232 #if !defined(S_IREAD) && !defined(__HAIKU__)
2233 #   define S_IREAD S_IRUSR
2234 #endif
2235
2236 #if !defined(S_IWRITE) && !defined(__HAIKU__)
2237 #   define S_IWRITE S_IWUSR
2238 #endif
2239
2240 #ifndef S_IEXEC
2241 #   define S_IEXEC S_IXUSR
2242 #endif
2243
2244 #if defined(cray) || defined(gould) || defined(i860) || defined(pyr)
2245 #   define SLOPPYDIVIDE
2246 #endif
2247
2248 #ifdef UV
2249 #undef UV
2250 #endif
2251
2252 /* This used to be conditionally defined based on whether we had a sprintf()
2253  * that correctly returns the string length (as required by C89), but we no
2254  * longer need that. XS modules can (and do) use this name, so it must remain
2255  * a part of the API that's visible to modules.
2256
2257 =for apidoc_section $string
2258 =for apidoc ATmD|int|my_sprintf|NN char *buffer|NN const char *pat|...
2259
2260 Do NOT use this due to the possibility of overflowing C<buffer>.  Instead use
2261 my_snprintf()
2262
2263 =cut
2264 */
2265 #define my_sprintf sprintf
2266
2267 /*
2268  * If we have v?snprintf() and the C99 variadic macros, we can just
2269  * use just the v?snprintf().  It is nice to try to trap the buffer
2270  * overflow, however, so if we are DEBUGGING, and we cannot use the
2271  * gcc statement expressions, then use the function wrappers which try
2272  * to trap the overflow.  If we can use the gcc statement expressions,
2273  * we can try that even with the version that uses the C99 variadic
2274  * macros.
2275  */
2276
2277 /* Note that we do not check against snprintf()/vsnprintf() returning
2278  * negative values because that is non-standard behaviour and we use
2279  * snprintf/vsnprintf only iff HAS_VSNPRINTF has been defined, and
2280  * that should be true only if the snprintf()/vsnprintf() are true
2281  * to the standard. */
2282
2283 #define PERL_SNPRINTF_CHECK(len, max, api) STMT_START { if ((max) > 0 && (Size_t)len > (max)) Perl_croak_nocontext("panic: %s buffer overflow", STRINGIFY(api)); } STMT_END
2284
2285 #if defined(USE_LOCALE_NUMERIC) || defined(USE_QUADMATH)
2286 #  define my_snprintf Perl_my_snprintf
2287 #  define PERL_MY_SNPRINTF_GUARDED
2288 #elif defined(HAS_SNPRINTF) && defined(HAS_C99_VARIADIC_MACROS) && !(defined(DEBUGGING) && !defined(PERL_USE_GCC_BRACE_GROUPS)) && !defined(PERL_GCC_PEDANTIC)
2289 #  ifdef PERL_USE_GCC_BRACE_GROUPS
2290 #      define my_snprintf(buffer, max, ...) ({ int len = snprintf(buffer, max, __VA_ARGS__); PERL_SNPRINTF_CHECK(len, max, snprintf); len; })
2291 #      define PERL_MY_SNPRINTF_GUARDED
2292 #  else
2293 #    define my_snprintf(buffer, max, ...) snprintf(buffer, max, __VA_ARGS__)
2294 #  endif
2295 #else
2296 #  define my_snprintf  Perl_my_snprintf
2297 #  define PERL_MY_SNPRINTF_GUARDED
2298 #endif
2299
2300 /* There is no quadmath_vsnprintf, and therefore my_vsnprintf()
2301  * dies if called under USE_QUADMATH. */
2302 #if !  defined(USE_LOCALE_NUMERIC)                                  \
2303  &&    defined(HAS_VSNPRINTF)                                       \
2304  &&    defined(HAS_C99_VARIADIC_MACROS)                             \
2305  && ! (defined(DEBUGGING) && ! defined(PERL_USE_GCC_BRACE_GROUPS))  \
2306  && !  defined(PERL_GCC_PEDANTIC)
2307 #  ifdef PERL_USE_GCC_BRACE_GROUPS
2308 #      define my_vsnprintf(buffer, max, ...)                        \
2309             ({ int len = vsnprintf(buffer, max, __VA_ARGS__);       \
2310              PERL_SNPRINTF_CHECK(len, max, vsnprintf);              \
2311              len; })
2312 #      define PERL_MY_VSNPRINTF_GUARDED
2313 #  else
2314 #    define my_vsnprintf(buffer, max, ...) vsnprintf(buffer, max, __VA_ARGS__)
2315 #  endif
2316 #else
2317 #  define my_vsnprintf Perl_my_vsnprintf
2318 #  define PERL_MY_VSNPRINTF_GUARDED
2319 #endif
2320
2321 /* You will definitely need to use the PERL_MY_SNPRINTF_POST_GUARD()
2322  * or PERL_MY_VSNPRINTF_POST_GUARD() if you otherwise decide to ignore
2323  * the result of my_snprintf() or my_vsnprintf().  (No, you should not
2324  * completely ignore it: otherwise you cannot know whether your output
2325  * was too long.)
2326  *
2327  * int len = my_sprintf(buf, max, ...);
2328  * PERL_MY_SNPRINTF_POST_GUARD(len, max);
2329  *
2330  * The trick is that in certain platforms [a] the my_sprintf() already
2331  * contains the sanity check, while in certain platforms [b] it needs
2332  * to be done as a separate step.  The POST_GUARD is that step-- in [a]
2333  * platforms the POST_GUARD actually does nothing since the check has
2334  * already been done.  Watch out for the max being the same in both calls.
2335  *
2336  * If you actually use the snprintf/vsnprintf return value already,
2337  * you assumedly are checking its validity somehow.  But you can
2338  * insert the POST_GUARD() also in that case. */
2339
2340 #ifndef PERL_MY_SNPRINTF_GUARDED
2341 #  define PERL_MY_SNPRINTF_POST_GUARD(len, max) PERL_SNPRINTF_CHECK(len, max, snprintf)
2342 #else
2343 #  define PERL_MY_SNPRINTF_POST_GUARD(len, max) PERL_UNUSED_VAR(len)
2344 #endif
2345
2346 #ifndef  PERL_MY_VSNPRINTF_GUARDED
2347 #  define PERL_MY_VSNPRINTF_POST_GUARD(len, max) PERL_SNPRINTF_CHECK(len, max, vsnprintf)
2348 #else
2349 #  define PERL_MY_VSNPRINTF_POST_GUARD(len, max) PERL_UNUSED_VAR(len)
2350 #endif
2351
2352 #ifdef HAS_STRLCAT
2353 #  define my_strlcat    strlcat
2354 #endif
2355
2356 #if defined(PERL_CORE) || defined(PERL_EXT)
2357 #  ifdef HAS_MEMRCHR
2358 #    define my_memrchr  memrchr
2359 #  else
2360 #    define my_memrchr  S_my_memrchr
2361 #  endif
2362 #endif
2363
2364 #ifdef HAS_STRLCPY
2365 #  define my_strlcpy    strlcpy
2366 #endif
2367
2368 #ifdef HAS_STRNLEN
2369 #  define my_strnlen    strnlen
2370 #endif
2371
2372 /*
2373     The IV type is supposed to be long enough to hold any integral
2374     value or a pointer.
2375     --Andy Dougherty    August 1996
2376 */
2377
2378 typedef IVTYPE IV;
2379 typedef UVTYPE UV;
2380
2381 #if defined(USE_64_BIT_INT) && defined(HAS_QUAD)
2382 #  if QUADKIND == QUAD_IS_INT64_T && defined(INT64_MAX)
2383 #    define IV_MAX ((IV)INT64_MAX)
2384 #    define IV_MIN ((IV)INT64_MIN)
2385 #    define UV_MAX ((UV)UINT64_MAX)
2386 #    ifndef UINT64_MIN
2387 #      define UINT64_MIN 0
2388 #    endif
2389 #    define UV_MIN ((UV)UINT64_MIN)
2390 #  else
2391 #    define IV_MAX PERL_QUAD_MAX
2392 #    define IV_MIN PERL_QUAD_MIN
2393 #    define UV_MAX PERL_UQUAD_MAX
2394 #    define UV_MIN PERL_UQUAD_MIN
2395 #  endif
2396 #  define IV_IS_QUAD
2397 #  define UV_IS_QUAD
2398 #else
2399 #  if defined(INT32_MAX) && IVSIZE == 4
2400 #    define IV_MAX ((IV)INT32_MAX)
2401 #    define IV_MIN ((IV)INT32_MIN)
2402 #    ifndef UINT32_MAX_BROKEN /* e.g. HP-UX with gcc messes this up */
2403 #        define UV_MAX ((UV)UINT32_MAX)
2404 #    else
2405 #        define UV_MAX ((UV)4294967295U)
2406 #    endif
2407 #    ifndef UINT32_MIN
2408 #      define UINT32_MIN 0
2409 #    endif
2410 #    define UV_MIN ((UV)UINT32_MIN)
2411 #  else
2412 #    define IV_MAX PERL_LONG_MAX
2413 #    define IV_MIN PERL_LONG_MIN
2414 #    define UV_MAX PERL_ULONG_MAX
2415 #    define UV_MIN PERL_ULONG_MIN
2416 #  endif
2417 #  if IVSIZE == 8
2418 #    define IV_IS_QUAD
2419 #    define UV_IS_QUAD
2420 #    ifndef HAS_QUAD
2421 #      define HAS_QUAD
2422 #    endif
2423 #  else
2424 #    undef IV_IS_QUAD
2425 #    undef UV_IS_QUAD
2426 #if !defined(PERL_CORE)
2427 /* We think that removing this decade-old undef this will cause too much
2428    breakage on CPAN for too little gain. (See RT #119753)
2429    However, we do need HAS_QUAD in the core for use by the drand48 code. */
2430 #    undef HAS_QUAD
2431 #endif
2432 #  endif
2433 #endif
2434
2435 #define Size_t_MAX (~(Size_t)0)
2436 #define SSize_t_MAX (SSize_t)(~(Size_t)0 >> 1)
2437
2438 #define IV_DIG (BIT_DIGITS(IVSIZE * 8))
2439 #define UV_DIG (BIT_DIGITS(UVSIZE * 8))
2440
2441 #ifndef NO_PERL_PRESERVE_IVUV
2442 #define PERL_PRESERVE_IVUV      /* We like our integers to stay integers. */
2443 #endif
2444
2445 /*
2446  *  The macros INT2PTR and NUM2PTR are (despite their names)
2447  *  bi-directional: they will convert int/float to or from pointers.
2448  *  However the conversion to int/float are named explicitly:
2449  *  PTR2IV, PTR2UV, PTR2NV.
2450  *
2451  *  For int conversions we do not need two casts if pointers are
2452  *  the same size as IV and UV.   Otherwise we need an explicit
2453  *  cast (PTRV) to avoid compiler warnings.
2454  *
2455  *  These are mentioned in perlguts
2456  */
2457 #if (IVSIZE == PTRSIZE) && (UVSIZE == PTRSIZE)
2458 #  define PTRV                  UV
2459 #  define INT2PTR(any,d)        (any)(d)
2460 #elif PTRSIZE == LONGSIZE
2461 #  define PTRV                  unsigned long
2462 #  define PTR2ul(p)             (unsigned long)(p)
2463 #else
2464 #  define PTRV                  unsigned
2465 #endif
2466
2467 #ifndef INT2PTR
2468 #  define INT2PTR(any,d)        (any)(PTRV)(d)
2469 #endif
2470
2471 #ifndef PTR2ul
2472 #  define PTR2ul(p)     INT2PTR(unsigned long,p)
2473 #endif
2474
2475 /*
2476 =for apidoc_section $casting
2477 =for apidoc Cyh|type|NUM2PTR|type|int value
2478 You probably want to be using L<C</INT2PTR>> instead.
2479
2480 =cut
2481 */
2482
2483 #define NUM2PTR(any,d)  (any)(PTRV)(d)
2484 #define PTR2IV(p)       INT2PTR(IV,p)
2485 #define PTR2UV(p)       INT2PTR(UV,p)
2486 #define PTR2NV(p)       NUM2PTR(NV,p)
2487 #define PTR2nat(p)      (PTRV)(p)       /* pointer to integer of PTRSIZE */
2488
2489 /* According to strict ANSI C89 one cannot freely cast between
2490  * data pointers and function (code) pointers.  There are at least
2491  * two ways around this.  One (used below) is to do two casts,
2492  * first the other pointer to an (unsigned) integer, and then
2493  * the integer to the other pointer.  The other way would be
2494  * to use unions to "overlay" the pointers.  For an example of
2495  * the latter technique, see union dirpu in struct xpvio in sv.h.
2496  * The only feasible use is probably temporarily storing
2497  * function pointers in a data pointer (such as a void pointer). */
2498
2499 #define DPTR2FPTR(t,p) ((t)PTR2nat(p))  /* data pointer to function pointer */
2500 #define FPTR2DPTR(t,p) ((t)PTR2nat(p))  /* function pointer to data pointer */
2501
2502 #ifdef USE_LONG_DOUBLE
2503 #  if LONG_DOUBLESIZE == DOUBLESIZE
2504 #    define LONG_DOUBLE_EQUALS_DOUBLE
2505 #    undef USE_LONG_DOUBLE /* Ouch! */
2506 #  endif
2507 #endif
2508
2509 /* The following is all to get LDBL_DIG, in order to pick a nice
2510    default value for printing floating point numbers in Gconvert.
2511    (see config.h)
2512 */
2513 #ifndef HAS_LDBL_DIG
2514 #  if LONG_DOUBLESIZE == 10
2515 #    define LDBL_DIG 18 /* assume IEEE */
2516 #  elif LONG_DOUBLESIZE == 12
2517 #    define LDBL_DIG 18 /* gcc? */
2518 #  elif LONG_DOUBLESIZE == 16
2519 #    define LDBL_DIG 33 /* assume IEEE */
2520 #  elif LONG_DOUBLESIZE == DOUBLESIZE
2521 #    define LDBL_DIG DBL_DIG /* bummer */
2522 #  endif
2523 #endif
2524
2525 /* On MS Windows,with 64-bit mingw-w64 compilers, we
2526    need to attend to a __float128 alignment issue if
2527    USE_QUADMATH is defined. Otherwise we simply:
2528    typedef NVTYPE NV
2529    32-bit mingw.org compilers might also require
2530    aligned(32) - at least that's what I found with my
2531    Math::Foat128 module. But this is as yet untested
2532    here, so no allowance is being made for mingw.org
2533    compilers at this stage. -- sisyphus January 2021
2534 */
2535 #if (defined(USE_LONG_DOUBLE) || defined(USE_QUADMATH)) && defined(__MINGW64__)
2536    /* 64-bit build, mingw-w64 compiler only */
2537    typedef NVTYPE NV __attribute__ ((aligned(8)));
2538 #else
2539    typedef NVTYPE NV;
2540 #endif
2541
2542 #ifdef I_IEEEFP
2543 #   include <ieeefp.h>
2544 #endif
2545
2546 #if defined(__DECC) && defined(__osf__)
2547 /* Also Tru64 cc has broken NaN comparisons. */
2548 #  define NAN_COMPARE_BROKEN
2549 #endif
2550 #if defined(__sgi)
2551 #  define NAN_COMPARE_BROKEN
2552 #endif
2553
2554 #ifdef USE_LONG_DOUBLE
2555 #   ifdef I_SUNMATH
2556 #       include <sunmath.h>
2557 #   endif
2558 #   if defined(LDBL_DIG)
2559 #       define NV_DIG LDBL_DIG
2560 #       ifdef LDBL_MANT_DIG
2561 #           define NV_MANT_DIG LDBL_MANT_DIG
2562 #       endif
2563 #       ifdef LDBL_MIN
2564 #           define NV_MIN LDBL_MIN
2565 #       endif
2566 #       ifdef LDBL_MAX
2567 #           define NV_MAX LDBL_MAX
2568 #       endif
2569 #       ifdef LDBL_MIN_EXP
2570 #           define NV_MIN_EXP LDBL_MIN_EXP
2571 #       endif
2572 #       ifdef LDBL_MAX_EXP
2573 #           define NV_MAX_EXP LDBL_MAX_EXP
2574 #       endif
2575 #       ifdef LDBL_MIN_10_EXP
2576 #           define NV_MIN_10_EXP LDBL_MIN_10_EXP
2577 #       endif
2578 #       ifdef LDBL_MAX_10_EXP
2579 #           define NV_MAX_10_EXP LDBL_MAX_10_EXP
2580 #       endif
2581 #       ifdef LDBL_EPSILON
2582 #           define NV_EPSILON LDBL_EPSILON
2583 #       endif
2584 #       ifdef LDBL_MAX
2585 #           define NV_MAX LDBL_MAX
2586 /* Having LDBL_MAX doesn't necessarily mean that we have LDBL_MIN... -Allen */
2587 #       elif defined(HUGE_VALL)
2588 #           define NV_MAX HUGE_VALL
2589 #       endif
2590 #   endif
2591 #   if defined(HAS_SQRTL)
2592 #       define Perl_acos acosl
2593 #       define Perl_asin asinl
2594 #       define Perl_atan atanl
2595 #       define Perl_atan2 atan2l
2596 #       define Perl_ceil ceill
2597 #       define Perl_cos cosl
2598 #       define Perl_cosh coshl
2599 #       define Perl_exp expl
2600 #       define Perl_fabs fabsl
2601 #       define Perl_floor floorl
2602 #       define Perl_fmod fmodl
2603 #       define Perl_log logl
2604 #       define Perl_log10 log10l
2605 #       define Perl_pow powl
2606 #       define Perl_sin sinl
2607 #       define Perl_sinh sinhl
2608 #       define Perl_sqrt sqrtl
2609 #       define Perl_tan tanl
2610 #       define Perl_tanh tanhl
2611 #   endif
2612 /* e.g. libsunmath doesn't have modfl and frexpl as of mid-March 2000 */
2613 #   ifndef Perl_modf
2614 #       ifdef HAS_MODFL
2615 #           define Perl_modf(x,y) modfl(x,y)
2616 /* eg glibc 2.2 series seems to provide modfl on ppc and arm, but has no
2617    prototype in <math.h> */
2618 #           ifndef HAS_MODFL_PROTO
2619 EXTERN_C long double modfl(long double, long double *);
2620 #           endif
2621 #       elif (defined(HAS_TRUNCL) || defined(HAS_AINTL)) && defined(HAS_COPYSIGNL)
2622         extern long double Perl_my_modfl(long double x, long double *ip);
2623 #           define Perl_modf(x,y) Perl_my_modfl(x,y)
2624 #       endif
2625 #   endif
2626 #   ifndef Perl_frexp
2627 #       ifdef HAS_FREXPL
2628 #           define Perl_frexp(x,y) frexpl(x,y)
2629 #       elif defined(HAS_ILOGBL) && defined(HAS_SCALBNL)
2630 extern long double Perl_my_frexpl(long double x, int *e);
2631 #           define Perl_frexp(x,y) Perl_my_frexpl(x,y)
2632 #       endif
2633 #   endif
2634 #   ifndef Perl_ldexp
2635 #       ifdef HAS_LDEXPL
2636 #           define Perl_ldexp(x, y) ldexpl(x,y)
2637 #       elif defined(HAS_SCALBNL) && FLT_RADIX == 2
2638 #           define Perl_ldexp(x,y) scalbnl(x,y)
2639 #       endif
2640 #   endif
2641 #   ifndef Perl_isnan
2642 #       if defined(HAS_ISNANL) && !(defined(isnan) && defined(HAS_C99))
2643 #           define Perl_isnan(x) isnanl(x)
2644 #       elif defined(__sgi) && defined(__c99)  /* XXX Configure test needed */
2645 #           define Perl_isnan(x) isnan(x)
2646 #       endif
2647 #   endif
2648 #   ifndef Perl_isinf
2649 #       if defined(HAS_ISINFL) && !(defined(isinf) && defined(HAS_C99))
2650 #           define Perl_isinf(x) isinfl(x)
2651 #       elif defined(__sgi) && defined(__c99)  /* XXX Configure test needed */
2652 #           define Perl_isinf(x) isinf(x)
2653 #       elif defined(LDBL_MAX) && !defined(NAN_COMPARE_BROKEN)
2654 #           define Perl_isinf(x) ((x) > LDBL_MAX || (x) < -LDBL_MAX)
2655 #       endif
2656 #   endif
2657 #   ifndef Perl_isfinite
2658 #       define Perl_isfinite(x) Perl_isfinitel(x)
2659 #   endif
2660 #elif defined(USE_QUADMATH) && defined(I_QUADMATH)
2661 #   include <quadmath.h>
2662 #   define NV_DIG FLT128_DIG
2663 #   define NV_MANT_DIG FLT128_MANT_DIG
2664 #   define NV_MIN FLT128_MIN
2665 #   define NV_MAX FLT128_MAX
2666 #   define NV_MIN_EXP FLT128_MIN_EXP
2667 #   define NV_MAX_EXP FLT128_MAX_EXP
2668 #   define NV_EPSILON FLT128_EPSILON
2669 #   define NV_MIN_10_EXP FLT128_MIN_10_EXP
2670 #   define NV_MAX_10_EXP FLT128_MAX_10_EXP
2671 #   define Perl_acos acosq
2672 #   define Perl_asin asinq
2673 #   define Perl_atan atanq
2674 #   define Perl_atan2 atan2q
2675 #   define Perl_ceil ceilq
2676 #   define Perl_cos cosq
2677 #   define Perl_cosh coshq
2678 #   define Perl_exp expq
2679 #   define Perl_fabs fabsq
2680 #   define Perl_floor floorq
2681 #   define Perl_fmod fmodq
2682 #   define Perl_log logq
2683 #   define Perl_log10 log10q
2684 #   define Perl_signbit signbitq
2685 #   define Perl_pow powq
2686 #   define Perl_sin sinq
2687 #   define Perl_sinh sinhq
2688 #   define Perl_sqrt sqrtq
2689 #   define Perl_tan tanq
2690 #   define Perl_tanh tanhq
2691 #   define Perl_modf(x,y) modfq(x,y)
2692 #   define Perl_frexp(x,y) frexpq(x,y)
2693 #   define Perl_ldexp(x, y) ldexpq(x,y)
2694 #   define Perl_isinf(x) isinfq(x)
2695 #   define Perl_isnan(x) isnanq(x)
2696 #   define Perl_isfinite(x) (!(isnanq(x) || isinfq(x)))
2697 #   define Perl_fp_class(x) ((x) == 0.0Q ? 0 : isinfq(x) ? 3 : isnanq(x) ? 4 : PERL_ABS(x) < FLT128_MIN ? 2 : 1)
2698 #   define Perl_fp_class_inf(x)    (Perl_fp_class(x) == 3)
2699 #   define Perl_fp_class_nan(x)    (Perl_fp_class(x) == 4)
2700 #   define Perl_fp_class_norm(x)   (Perl_fp_class(x) == 1)
2701 #   define Perl_fp_class_denorm(x) (Perl_fp_class(x) == 2)
2702 #   define Perl_fp_class_zero(x)   (Perl_fp_class(x) == 0)
2703 #else
2704 #   define NV_DIG DBL_DIG
2705 #   define NV_MANT_DIG DBL_MANT_DIG
2706 #   define NV_MIN DBL_MIN
2707 #   define NV_MAX DBL_MAX
2708 #   define NV_MIN_EXP DBL_MIN_EXP
2709 #   define NV_MAX_EXP DBL_MAX_EXP
2710 #   define NV_MIN_10_EXP DBL_MIN_10_EXP
2711 #   define NV_MAX_10_EXP DBL_MAX_10_EXP
2712 #   define NV_EPSILON DBL_EPSILON
2713 #   define NV_MAX DBL_MAX
2714 #   define NV_MIN DBL_MIN
2715
2716 /* These math interfaces are C89. */
2717 #   define Perl_acos acos
2718 #   define Perl_asin asin
2719 #   define Perl_atan atan
2720 #   define Perl_atan2 atan2
2721 #   define Perl_ceil ceil
2722 #   define Perl_cos cos
2723 #   define Perl_cosh cosh
2724 #   define Perl_exp exp
2725 #   define Perl_fabs fabs
2726 #   define Perl_floor floor
2727 #   define Perl_fmod fmod
2728 #   define Perl_log log
2729 #   define Perl_log10 log10
2730 #   define Perl_pow pow
2731 #   define Perl_sin sin
2732 #   define Perl_sinh sinh
2733 #   define Perl_sqrt sqrt
2734 #   define Perl_tan tan
2735 #   define Perl_tanh tanh
2736
2737 #   define Perl_modf(x,y) modf(x,y)
2738 #   define Perl_frexp(x,y) frexp(x,y)
2739 #   define Perl_ldexp(x,y) ldexp(x,y)
2740
2741 #   ifndef Perl_isnan
2742 #       ifdef HAS_ISNAN
2743 #           define Perl_isnan(x) isnan(x)
2744 #       endif
2745 #   endif
2746 #   ifndef Perl_isinf
2747 #       if defined(HAS_ISINF)
2748 #           define Perl_isinf(x) isinf(x)
2749 #       elif defined(DBL_MAX) && !defined(NAN_COMPARE_BROKEN)
2750 #           define Perl_isinf(x) ((x) > DBL_MAX || (x) < -DBL_MAX)
2751 #       endif
2752 #   endif
2753 #   ifndef Perl_isfinite
2754 #     ifdef HAS_ISFINITE
2755 #       define Perl_isfinite(x) isfinite(x)
2756 #     elif defined(HAS_FINITE)
2757 #       define Perl_isfinite(x) finite(x)
2758 #     endif
2759 #   endif
2760 #endif
2761
2762 /* fpclassify(): C99.  It is supposed to be a macro that switches on
2763 * the sizeof() of its argument, so there's no need for e.g. fpclassifyl().*/
2764 #if !defined(Perl_fp_class) && defined(HAS_FPCLASSIFY)
2765 #    include <math.h>
2766 #    if defined(FP_INFINITE) && defined(FP_NAN)
2767 #        define Perl_fp_class(x)        fpclassify(x)
2768 #        define Perl_fp_class_inf(x)    (Perl_fp_class(x)==FP_INFINITE)
2769 #        define Perl_fp_class_nan(x)    (Perl_fp_class(x)==FP_NAN)
2770 #        define Perl_fp_class_norm(x)   (Perl_fp_class(x)==FP_NORMAL)
2771 #        define Perl_fp_class_denorm(x) (Perl_fp_class(x)==FP_SUBNORMAL)
2772 #        define Perl_fp_class_zero(x)   (Perl_fp_class(x)==FP_ZERO)
2773 #    elif defined(FP_PLUS_INF) && defined(FP_QNAN)
2774 /* Some versions of HP-UX (10.20) have (only) fpclassify() but which is
2775  * actually not the C99 fpclassify, with its own set of return defines. */
2776 #        define Perl_fp_class(x)        fpclassify(x)
2777 #        define Perl_fp_class_pinf(x)   (Perl_fp_class(x)==FP_PLUS_INF)
2778 #        define Perl_fp_class_ninf(x)   (Perl_fp_class(x)==FP_MINUS_INF)
2779 #        define Perl_fp_class_snan(x)   (Perl_fp_class(x)==FP_SNAN)
2780 #        define Perl_fp_class_qnan(x)   (Perl_fp_class(x)==FP_QNAN)
2781 #        define Perl_fp_class_pnorm(x)  (Perl_fp_class(x)==FP_PLUS_NORM)
2782 #        define Perl_fp_class_nnorm(x)  (Perl_fp_class(x)==FP_MINUS_NORM)
2783 #        define Perl_fp_class_pdenorm(x)        (Perl_fp_class(x)==FP_PLUS_DENORM)
2784 #        define Perl_fp_class_ndenorm(x)        (Perl_fp_class(x)==FP_MINUS_DENORM)
2785 #        define Perl_fp_class_pzero(x)  (Perl_fp_class(x)==FP_PLUS_ZERO)
2786 #        define Perl_fp_class_nzero(x)  (Perl_fp_class(x)==FP_MINUS_ZERO)
2787 #    else
2788 #        undef Perl_fp_class /* Unknown set of defines */
2789 #    endif
2790 #endif
2791
2792 /* fp_classify(): Legacy: VMS, maybe Unicos? The values, however,
2793  * are identical to the C99 fpclassify(). */
2794 #if !defined(Perl_fp_class) && defined(HAS_FP_CLASSIFY)
2795 #    include <math.h>
2796 #    ifdef __VMS
2797      /* FP_INFINITE and others are here rather than in math.h as C99 stipulates */
2798 #        include <fp.h>
2799      /* oh, and the isnormal macro has a typo in it! */
2800 #    undef isnormal
2801 #    define isnormal(x) Perl_fp_class_norm(x)
2802 #    endif
2803 #    if defined(FP_INFINITE) && defined(FP_NAN)
2804 #        define Perl_fp_class(x)        fp_classify(x)
2805 #        define Perl_fp_class_inf(x)    (Perl_fp_class(x)==FP_INFINITE)
2806 #        define Perl_fp_class_nan(x)    (Perl_fp_class(x)==FP_NAN)
2807 #        define Perl_fp_class_norm(x)   (Perl_fp_class(x)==FP_NORMAL)
2808 #        define Perl_fp_class_denorm(x) (Perl_fp_class(x)==FP_SUBNORMAL)
2809 #        define Perl_fp_class_zero(x)   (Perl_fp_class(x)==FP_ZERO)
2810 #    else
2811 #        undef Perl_fp_class /* Unknown set of defines */
2812 #    endif
2813 #endif
2814
2815 /* Feel free to check with me for the SGI manpages, SGI testing,
2816  * etcetera, if you want to try getting this to work with IRIX.
2817  *
2818  * - Allen <allens@cpan.org> */
2819
2820 /* fpclass(): SysV, at least Solaris and some versions of IRIX. */
2821 #if !defined(Perl_fp_class) && (defined(HAS_FPCLASS)||defined(HAS_FPCLASSL))
2822 /* Solaris and IRIX have fpclass/fpclassl, but they are using
2823  * an enum typedef, not cpp symbols, and Configure doesn't detect that.
2824  * Define some symbols also as cpp symbols so we can detect them. */
2825 #    if defined(__sun) || defined(__sgi) /* XXX Configure test instead */
2826 #     define FP_PINF FP_PINF
2827 #     define FP_QNAN FP_QNAN
2828 #    endif
2829 #    include <math.h>
2830 #    ifdef I_IEEEFP
2831 #        include <ieeefp.h>
2832 #    endif
2833 #    ifdef I_FP
2834 #        include <fp.h>
2835 #    endif
2836 #    if defined(USE_LONG_DOUBLE) && defined(HAS_FPCLASSL)
2837 #        define Perl_fp_class(x)        fpclassl(x)
2838 #    else
2839 #        define Perl_fp_class(x)        fpclass(x)
2840 #    endif
2841 #    if defined(FP_CLASS_PINF) && defined(FP_CLASS_SNAN)
2842 #        define Perl_fp_class_snan(x)   (Perl_fp_class(x)==FP_CLASS_SNAN)
2843 #        define Perl_fp_class_qnan(x)   (Perl_fp_class(x)==FP_CLASS_QNAN)
2844 #        define Perl_fp_class_ninf(x)   (Perl_fp_class(x)==FP_CLASS_NINF)
2845 #        define Perl_fp_class_pinf(x)   (Perl_fp_class(x)==FP_CLASS_PINF)
2846 #        define Perl_fp_class_nnorm(x)  (Perl_fp_class(x)==FP_CLASS_NNORM)
2847 #        define Perl_fp_class_pnorm(x)  (Perl_fp_class(x)==FP_CLASS_PNORM)
2848 #        define Perl_fp_class_ndenorm(x)        (Perl_fp_class(x)==FP_CLASS_NDENORM)
2849 #        define Perl_fp_class_pdenorm(x)        (Perl_fp_class(x)==FP_CLASS_PDENORM)
2850 #        define Perl_fp_class_nzero(x)  (Perl_fp_class(x)==FP_CLASS_NZERO)
2851 #        define Perl_fp_class_pzero(x)  (Perl_fp_class(x)==FP_CLASS_PZERO)
2852 #    elif defined(FP_PINF) && defined(FP_QNAN)
2853 #        define Perl_fp_class_snan(x)   (Perl_fp_class(x)==FP_SNAN)
2854 #        define Perl_fp_class_qnan(x)   (Perl_fp_class(x)==FP_QNAN)
2855 #        define Perl_fp_class_ninf(x)   (Perl_fp_class(x)==FP_NINF)
2856 #        define Perl_fp_class_pinf(x)   (Perl_fp_class(x)==FP_PINF)
2857 #        define Perl_fp_class_nnorm(x)  (Perl_fp_class(x)==FP_NNORM)
2858 #        define Perl_fp_class_pnorm(x)  (Perl_fp_class(x)==FP_PNORM)
2859 #        define Perl_fp_class_ndenorm(x)        (Perl_fp_class(x)==FP_NDENORM)
2860 #        define Perl_fp_class_pdenorm(x)        (Perl_fp_class(x)==FP_PDENORM)
2861 #        define Perl_fp_class_nzero(x)  (Perl_fp_class(x)==FP_NZERO)
2862 #        define Perl_fp_class_pzero(x)  (Perl_fp_class(x)==FP_PZERO)
2863 #    else
2864 #        undef Perl_fp_class /* Unknown set of defines */
2865 #    endif
2866 #endif
2867
2868 /* fp_class(): Legacy: at least Tru64, some versions of IRIX. */
2869 #if !defined(Perl_fp_class) && (defined(HAS_FP_CLASS)||defined(HAS_FP_CLASSL))
2870 #    include <math.h>
2871 #    if !defined(FP_SNAN) && defined(I_FP_CLASS)
2872 #        include <fp_class.h>
2873 #    endif
2874 #    if defined(FP_POS_INF) && defined(FP_QNAN)
2875 #        ifdef __sgi /* XXX Configure test instead */
2876 #            ifdef USE_LONG_DOUBLE
2877 #                define Perl_fp_class(x)        fp_class_l(x)
2878 #            else
2879 #                define Perl_fp_class(x)        fp_class_d(x)
2880 #            endif
2881 #        else
2882 #            if defined(USE_LONG_DOUBLE) && defined(HAS_FP_CLASSL)
2883 #                define Perl_fp_class(x)        fp_classl(x)
2884 #            else
2885 #                define Perl_fp_class(x)        fp_class(x)
2886 #            endif
2887 #        endif
2888 #        if defined(FP_POS_INF) && defined(FP_QNAN)
2889 #            define Perl_fp_class_snan(x)       (Perl_fp_class(x)==FP_SNAN)
2890 #            define Perl_fp_class_qnan(x)       (Perl_fp_class(x)==FP_QNAN)
2891 #            define Perl_fp_class_ninf(x)       (Perl_fp_class(x)==FP_NEG_INF)
2892 #            define Perl_fp_class_pinf(x)       (Perl_fp_class(x)==FP_POS_INF)
2893 #            define Perl_fp_class_nnorm(x)      (Perl_fp_class(x)==FP_NEG_NORM)
2894 #            define Perl_fp_class_pnorm(x)      (Perl_fp_class(x)==FP_POS_NORM)
2895 #            define Perl_fp_class_ndenorm(x)    (Perl_fp_class(x)==FP_NEG_DENORM)
2896 #            define Perl_fp_class_pdenorm(x)    (Perl_fp_class(x)==FP_POS_DENORM)
2897 #            define Perl_fp_class_nzero(x)      (Perl_fp_class(x)==FP_NEG_ZERO)
2898 #            define Perl_fp_class_pzero(x)      (Perl_fp_class(x)==FP_POS_ZERO)
2899 #        else
2900 #            undef Perl_fp_class /* Unknown set of defines */
2901 #        endif
2902 #    endif
2903 #endif
2904
2905 /* class(), _class(): Legacy: AIX. */
2906 #if !defined(Perl_fp_class) && defined(HAS_CLASS)
2907 #    include <math.h>
2908 #    if defined(FP_PLUS_NORM) && defined(FP_PLUS_INF)
2909 #        ifndef _cplusplus
2910 #            define Perl_fp_class(x)    class(x)
2911 #        else
2912 #            define Perl_fp_class(x)    _class(x)
2913 #        endif
2914 #        if defined(FP_PLUS_INF) && defined(FP_NANQ)
2915 #            define Perl_fp_class_snan(x)       (Perl_fp_class(x)==FP_NANS)
2916 #            define Perl_fp_class_qnan(x)       (Perl_fp_class(x)==FP_NANQ)
2917 #            define Perl_fp_class_ninf(x)       (Perl_fp_class(x)==FP_MINUS_INF)
2918 #            define Perl_fp_class_pinf(x)       (Perl_fp_class(x)==FP_PLUS_INF)
2919 #            define Perl_fp_class_nnorm(x)      (Perl_fp_class(x)==FP_MINUS_NORM)
2920 #            define Perl_fp_class_pnorm(x)      (Perl_fp_class(x)==FP_PLUS_NORM)
2921 #            define Perl_fp_class_ndenorm(x)    (Perl_fp_class(x)==FP_MINUS_DENORM)
2922 #            define Perl_fp_class_pdenorm(x)    (Perl_fp_class(x)==FP_PLUS_DENORM)
2923 #            define Perl_fp_class_nzero(x)      (Perl_fp_class(x)==FP_MINUS_ZERO)
2924 #            define Perl_fp_class_pzero(x)      (Perl_fp_class(x)==FP_PLUS_ZERO)
2925 #        else
2926 #            undef Perl_fp_class /* Unknown set of defines */
2927 #        endif
2928 #    endif
2929 #endif
2930
2931 /* Win32: _fpclass(), _isnan(), _finite(). */
2932 #ifdef _MSC_VER
2933 #  ifndef Perl_isnan
2934 #    define Perl_isnan(x) _isnan(x)
2935 #  endif
2936 #  ifndef Perl_isfinite
2937 #    define Perl_isfinite(x) _finite(x)
2938 #  endif
2939 #  ifndef Perl_fp_class_snan
2940 /* No simple way to #define Perl_fp_class because _fpclass()
2941  * returns a set of bits. */
2942 #    define Perl_fp_class_snan(x) (_fpclass(x) & _FPCLASS_SNAN)
2943 #    define Perl_fp_class_qnan(x) (_fpclass(x) & _FPCLASS_QNAN)
2944 #    define Perl_fp_class_nan(x) (_fpclass(x) & (_FPCLASS_SNAN|_FPCLASS_QNAN))
2945 #    define Perl_fp_class_ninf(x) (_fpclass(x) & _FPCLASS_NINF)
2946 #    define Perl_fp_class_pinf(x) (_fpclass(x) & _FPCLASS_PINF)
2947 #    define Perl_fp_class_inf(x) (_fpclass(x) & (_FPCLASS_NINF|_FPCLASS_PINF))
2948 #    define Perl_fp_class_nnorm(x) (_fpclass(x) & _FPCLASS_NN)
2949 #    define Perl_fp_class_pnorm(x) (_fpclass(x) & _FPCLASS_PN)
2950 #    define Perl_fp_class_norm(x) (_fpclass(x) & (_FPCLASS_NN|_FPCLASS_PN))
2951 #    define Perl_fp_class_ndenorm(x) (_fpclass(x) & _FPCLASS_ND)
2952 #    define Perl_fp_class_pdenorm(x) (_fpclass(x) & _FPCLASS_PD)
2953 #    define Perl_fp_class_denorm(x) (_fpclass(x) & (_FPCLASS_ND|_FPCLASS_PD))
2954 #    define Perl_fp_class_nzero(x) (_fpclass(x) & _FPCLASS_NZ)
2955 #    define Perl_fp_class_pzero(x) (_fpclass(x) & _FPCLASS_PZ)
2956 #    define Perl_fp_class_zero(x) (_fpclass(x) & (_FPCLASS_NZ|_FPCLASS_PZ))
2957 #  endif
2958 #endif
2959
2960 #if !defined(Perl_fp_class_inf) && \
2961   defined(Perl_fp_class_pinf) && defined(Perl_fp_class_ninf)
2962 #  define Perl_fp_class_inf(x) \
2963     (Perl_fp_class_pinf(x) || Perl_fp_class_ninf(x))
2964 #endif
2965
2966 #if !defined(Perl_fp_class_nan) && \
2967   defined(Perl_fp_class_snan) && defined(Perl_fp_class_qnan)
2968 #  define Perl_fp_class_nan(x) \
2969     (Perl_fp_class_snan(x) || Perl_fp_class_qnan(x))
2970 #endif
2971
2972 #if !defined(Perl_fp_class_zero) && \
2973   defined(Perl_fp_class_pzero) && defined(Perl_fp_class_nzero)
2974 #  define Perl_fp_class_zero(x) \
2975     (Perl_fp_class_pzero(x) || Perl_fp_class_nzero(x))
2976 #endif
2977
2978 #if !defined(Perl_fp_class_norm) && \
2979   defined(Perl_fp_class_pnorm) && defined(Perl_fp_class_nnorm)
2980 #  define Perl_fp_class_norm(x) \
2981     (Perl_fp_class_pnorm(x) || Perl_fp_class_nnorm(x))
2982 #endif
2983
2984 #if !defined(Perl_fp_class_denorm) && \
2985   defined(Perl_fp_class_pdenorm) && defined(Perl_fp_class_ndenorm)
2986 #  define Perl_fp_class_denorm(x) \
2987     (Perl_fp_class_pdenorm(x) || Perl_fp_class_ndenorm(x))
2988 #endif
2989
2990 #ifndef Perl_isnan
2991 #   ifdef Perl_fp_class_nan
2992 #       define Perl_isnan(x) Perl_fp_class_nan(x)
2993 #   elif defined(HAS_UNORDERED)
2994 #       define Perl_isnan(x) unordered((x), 0.0)
2995 #   else
2996 #       define Perl_isnan(x) ((x)!=(x))
2997 #   endif
2998 #endif
2999
3000 #ifndef Perl_isinf
3001 #   ifdef Perl_fp_class_inf
3002 #       define Perl_isinf(x) Perl_fp_class_inf(x)
3003 #   endif
3004 #endif
3005
3006 #ifndef Perl_isfinite
3007 #   if defined(HAS_ISFINITE) && !defined(isfinite)
3008 #     define Perl_isfinite(x) isfinite((double)(x))
3009 #   elif defined(HAS_FINITE)
3010 #       define Perl_isfinite(x) finite((double)(x))
3011 #   elif defined(Perl_fp_class_finite)
3012 #     define Perl_isfinite(x) Perl_fp_class_finite(x)
3013 #   else
3014 /* For the infinities the multiplication returns nan,
3015  * for the nan the multiplication also returns nan,
3016  * for everything else (that is, finite) zero should be returned. */
3017 #     define Perl_isfinite(x) (((x) * 0) == 0)
3018 #   endif
3019 #endif
3020
3021 #ifndef Perl_isinf
3022 #   if defined(Perl_isfinite) && defined(Perl_isnan)
3023 #       define Perl_isinf(x) (!(Perl_isfinite(x)||Perl_isnan(x)))
3024 #   endif
3025 #endif
3026
3027 /* We need Perl_isfinitel (ends with ell) (if available) even when
3028  * not USE_LONG_DOUBLE because the printf code (sv_catpvfn_flags)
3029  * needs that. */
3030 #if defined(HAS_LONG_DOUBLE) && !defined(Perl_isfinitel)
3031 /* If isfinite() is a macro and looks like we have C99,
3032  * we assume it's the type-aware C99 isfinite(). */
3033 #    if defined(HAS_ISFINITE) && defined(isfinite) && defined(HAS_C99)
3034 #        define Perl_isfinitel(x) isfinite(x)
3035 #    elif defined(HAS_ISFINITEL)
3036 #        define Perl_isfinitel(x) isfinitel(x)
3037 #    elif defined(HAS_FINITEL)
3038 #        define Perl_isfinitel(x) finitel(x)
3039 #    elif defined(HAS_ISINFL) && defined(HAS_ISNANL)
3040 #        define Perl_isfinitel(x) (!(isinfl(x)||isnanl(x)))
3041 #    else
3042 #        define Perl_isfinitel(x) ((x) * 0 == 0)  /* See Perl_isfinite. */
3043 #    endif
3044 #endif
3045
3046 /* The default is to use Perl's own atof() implementation (in numeric.c).
3047  * This knows about if 'use locale' is in effect or not, and handles the radix
3048  * character accordingly.  On some platforms (e.g. UNICOS) it is however best
3049  * to use the native implementation of atof, as long as you accept that the
3050  * current underlying locale will affect the radix character.  Perl's version
3051  * uses a dot for a radix, execpt within the lexical scope of a Perl C<use
3052  * locale> statement.
3053  *
3054  * You can experiment with using your native one by -DUSE_PERL_ATOF=0.
3055  * Some good tests to try out with either setting are t/base/num.t,
3056  * t/op/numconvert.t, and t/op/pack.t. Note that if using long doubles
3057  * you may need to be using a different function than atof! */
3058
3059 #ifndef USE_PERL_ATOF
3060 #   ifndef _UNICOS
3061 #       define USE_PERL_ATOF
3062 #   endif
3063 #else
3064 #   if USE_PERL_ATOF == 0
3065 #       undef USE_PERL_ATOF
3066 #   endif
3067 #endif
3068
3069 #ifdef USE_PERL_ATOF
3070 #   define Perl_atof(s) Perl_my_atof(aTHX_ s)
3071 #   define Perl_atof2(s, n) Perl_my_atof3(aTHX_ (s), &(n), 0)
3072 #else
3073 #   define Perl_atof(s) (NV)atof(s)
3074 #   define Perl_atof2(s, n) ((n) = atof(s))
3075 #endif
3076 #define my_atof2(a,b) my_atof3(a,b,0)
3077
3078 /*
3079 =for apidoc AmTR|NV|Atof|NN const char * const s
3080
3081 This is a synonym for L</C<my_atof>>.
3082
3083 =cut
3084
3085 */
3086
3087 #define Atof                            my_atof
3088
3089 /*
3090 =for apidoc_section $numeric
3091 =for apidoc   AmT|NV|Perl_acos|NV x
3092 =for apidoc_item |NV|Perl_asin|NV x
3093 =for apidoc_item |NV|Perl_atan|NV x
3094 =for apidoc_item |NV|Perl_atan2|NV x|NV y
3095 =for apidoc_item |NV|Perl_ceil|NV x
3096 =for apidoc_item |NV|Perl_cos|NV x
3097 =for apidoc_item |NV|Perl_cosh|NV x
3098 =for apidoc_item |NV|Perl_exp|NV x
3099 =for apidoc_item |NV|Perl_floor|NV x
3100 =for apidoc_item |NV|Perl_fmod|NV x|NV y
3101 =for apidoc_item |NV|Perl_frexp|NV x|int *exp
3102 =for apidoc_item |IV|Perl_isfinite|NV x
3103 =for apidoc_item |IV|Perl_isinf|NV x
3104 =for apidoc_item |IV|Perl_isnan|NV x
3105 =for apidoc_item |NV|Perl_ldexp|NV x|int exp
3106 =for apidoc_item |NV|Perl_log|NV x
3107 =for apidoc_item |NV|Perl_log10|NV x
3108 =for apidoc_item |NV|Perl_modf|NV x|NV *iptr
3109 =for apidoc_item |NV|Perl_pow|NV x|NV y
3110 =for apidoc_item |NV|Perl_sin|NV x
3111 =for apidoc_item |NV|Perl_sinh|NV x
3112 =for apidoc_item |NV|Perl_sqrt|NV x
3113 =for apidoc_item |NV|Perl_tan|NV x
3114 =for apidoc_item |NV|Perl_tanh|NV x
3115
3116 These perform the corresponding mathematical operation on the operand(s), using
3117 the libc function designed for the task that has just enough precision for an
3118 NV on this platform.  If no such function with sufficient precision exists,
3119 the highest precision one available is used.
3120
3121 =cut
3122
3123 */
3124
3125 /*
3126  * CHAR_MIN and CHAR_MAX are not included here, as the (char) type may be
3127  * ambiguous. It may be equivalent to (signed char) or (unsigned char)
3128  * depending on local options. Until Configure detects this (or at least
3129  * detects whether the "signed" keyword is available) the CHAR ranges
3130  * will not be included. UCHAR functions normally.
3131  *                                                           - kja
3132  */
3133
3134 #define PERL_UCHAR_MIN ((unsigned char)0)
3135 #define PERL_UCHAR_MAX ((unsigned char)UCHAR_MAX)
3136
3137 #define PERL_USHORT_MIN ((unsigned short)0)
3138 #define PERL_USHORT_MAX ((unsigned short)USHRT_MAX)
3139
3140 #define PERL_SHORT_MAX ((short)SHRT_MAX)
3141 #define PERL_SHORT_MIN ((short)SHRT_MIN)
3142
3143 #define PERL_UINT_MAX ((unsigned int)UINT_MAX)
3144 #define PERL_UINT_MIN ((unsigned int)0)
3145
3146 #define PERL_INT_MAX ((int)INT_MAX)
3147 #define PERL_INT_MIN ((int)INT_MIN)
3148
3149 #define PERL_ULONG_MAX ((unsigned long)ULONG_MAX)
3150 #define PERL_ULONG_MIN ((unsigned long)0L)
3151
3152 #define PERL_LONG_MAX ((long)LONG_MAX)
3153 #define PERL_LONG_MIN ((long)LONG_MIN)
3154
3155 #ifdef UV_IS_QUAD
3156 #    define PERL_UQUAD_MAX      (~(UV)0)
3157 #    define PERL_UQUAD_MIN      ((UV)0)
3158 #    define PERL_QUAD_MAX       ((IV) (PERL_UQUAD_MAX >> 1))
3159 #    define PERL_QUAD_MIN       (-PERL_QUAD_MAX - ((3 & -1) == 3))
3160 #endif
3161
3162 /*
3163 =for apidoc_section $integer
3164
3165 =for apidoc Amn |int|PERL_INT_MAX
3166 =for apidoc_item |int|PERL_INT_MIN
3167 =for apidoc_item |long|PERL_LONG_MAX
3168 =for apidoc_item |long|PERL_LONG_MIN
3169 =for apidoc_item |IV|PERL_QUAD_MAX
3170 =for apidoc_item |IV|PERL_QUAD_MIN
3171 =for apidoc_item |short|PERL_SHORT_MAX
3172 =for apidoc_item |short|PERL_SHORT_MIN
3173 =for apidoc_item |U8|PERL_UCHAR_MAX
3174 =for apidoc_item |U8|PERL_UCHAR_MIN
3175 =for apidoc_item |unsigned int|PERL_UINT_MAX
3176 =for apidoc_item |unsigned int|PERL_UINT_MIN
3177 =for apidoc_item |unsigned long|PERL_ULONG_MAX
3178 =for apidoc_item |unsigned long|PERL_ULONG_MIN
3179 =for apidoc_item |UV|PERL_UQUAD_MAX
3180 =for apidoc_item |UV|PERL_UQUAD_MIN
3181 =for apidoc_item |unsigned short|PERL_USHORT_MAX
3182 =for apidoc_item |unsigned short|PERL_USHORT_MIN
3183
3184 These give the largest and smallest number representable in the current
3185 platform in variables of the corresponding types.
3186
3187 For signed types, the smallest representable number is the most negative
3188 number, the one furthest away from zero.
3189
3190 For C99 and later compilers, these correspond to things like C<INT_MAX>, which
3191 are available to the C code.  But these constants, furnished by Perl,
3192 allow code compiled on earlier compilers to portably have access to the same
3193 constants.
3194
3195 =cut
3196
3197 */
3198
3199 typedef MEM_SIZE STRLEN;
3200
3201 typedef struct op OP;
3202 typedef struct cop COP;
3203 typedef struct unop UNOP;
3204 typedef struct unop_aux UNOP_AUX;
3205 typedef struct binop BINOP;
3206 typedef struct listop LISTOP;
3207 typedef struct logop LOGOP;
3208 typedef struct pmop PMOP;
3209 typedef struct svop SVOP;
3210 typedef struct padop PADOP;
3211 typedef struct pvop PVOP;
3212 typedef struct loop LOOP;
3213 typedef struct methop METHOP;
3214
3215 #ifdef PERL_CORE
3216 typedef struct opslab OPSLAB;
3217 typedef struct opslot OPSLOT;
3218 #endif
3219
3220 typedef struct block_hooks BHK;
3221 typedef struct custom_op XOP;
3222
3223 typedef struct interpreter PerlInterpreter;
3224
3225 /* SGI's <sys/sema.h> has struct sv */
3226 #if defined(__sgi)
3227 #   define STRUCT_SV perl_sv
3228 #else
3229 #   define STRUCT_SV sv
3230 #endif
3231 typedef struct STRUCT_SV SV;
3232 typedef struct av AV;
3233 typedef struct hv HV;
3234 typedef struct cv CV;
3235 typedef struct p5rx REGEXP;
3236 typedef struct gp GP;
3237 typedef struct gv GV;
3238 typedef struct io IO;
3239 typedef struct context PERL_CONTEXT;
3240 typedef struct block BLOCK;
3241 typedef struct invlist INVLIST;
3242
3243 typedef struct magic MAGIC;
3244 typedef struct xpv XPV;
3245 typedef struct xpviv XPVIV;
3246 typedef struct xpvuv XPVUV;
3247 typedef struct xpvnv XPVNV;
3248 typedef struct xpvmg XPVMG;
3249 typedef struct xpvlv XPVLV;
3250 typedef struct xpvinvlist XINVLIST;
3251 typedef struct xpvav XPVAV;
3252 typedef struct xpvhv XPVHV;
3253 typedef struct xpvgv XPVGV;
3254 typedef struct xpvcv XPVCV;
3255 typedef struct xpvbm XPVBM;
3256 typedef struct xpvfm XPVFM;
3257 typedef struct xpvio XPVIO;
3258 typedef struct xobject XPVOBJ;
3259 typedef struct mgvtbl MGVTBL;
3260 typedef union any ANY;
3261 typedef struct ptr_tbl_ent PTR_TBL_ENT_t;
3262 typedef struct ptr_tbl PTR_TBL_t;
3263 typedef struct clone_params CLONE_PARAMS;
3264
3265 /* a pad is currently just an AV; but that might change,
3266  * so hide the type.  */
3267 typedef struct padlist PADLIST;
3268 typedef AV PAD;
3269 typedef struct padnamelist PADNAMELIST;
3270 typedef struct padname PADNAME;
3271
3272 /* always enable PERL_OP_PARENT  */
3273 #if !defined(PERL_OP_PARENT)
3274 #  define PERL_OP_PARENT
3275 #endif
3276
3277 /* enable PERL_COPY_ON_WRITE by default */
3278 #if !defined(PERL_COPY_ON_WRITE) && !defined(PERL_NO_COW)
3279 #  define PERL_COPY_ON_WRITE
3280 #endif
3281
3282 #ifdef PERL_COPY_ON_WRITE
3283 #  define PERL_ANY_COW
3284 #else
3285 # define PERL_SAWAMPERSAND
3286 #endif
3287
3288 #if defined(PERL_DEBUG_READONLY_OPS) && !defined(USE_ITHREADS)
3289 # error PERL_DEBUG_READONLY_OPS only works with ithreads
3290 #endif
3291
3292 #include "handy.h"
3293 #include "charclass_invlists.h"
3294
3295 #if defined(USE_LARGE_FILES) && !defined(NO_64_BIT_RAWIO)
3296 #   if LSEEKSIZE == 8 && !defined(USE_64_BIT_RAWIO)
3297 #       define USE_64_BIT_RAWIO /* implicit */
3298 #   endif
3299 #endif
3300
3301 /* Notice the use of HAS_FSEEKO: now we are obligated to always use
3302  * fseeko/ftello if possible.  Don't go #defining ftell to ftello yourself,
3303  * however, because operating systems like to do that themself. */
3304 #ifndef FSEEKSIZE
3305 #   ifdef HAS_FSEEKO
3306 #       define FSEEKSIZE LSEEKSIZE
3307 #   else
3308 #       define FSEEKSIZE LONGSIZE
3309 #   endif
3310 #endif
3311
3312 #if defined(USE_LARGE_FILES) && !defined(NO_64_BIT_STDIO)
3313 #   if FSEEKSIZE == 8 && !defined(USE_64_BIT_STDIO)
3314 #       define USE_64_BIT_STDIO /* implicit */
3315 #   endif
3316 #endif
3317
3318 #ifdef USE_64_BIT_RAWIO
3319 #   ifdef HAS_OFF64_T
3320 #       undef Off_t
3321 #       define Off_t off64_t
3322 #       undef LSEEKSIZE
3323 #       define LSEEKSIZE 8
3324 #   endif
3325 /* Most 64-bit environments have defines like _LARGEFILE_SOURCE that
3326  * will trigger defines like the ones below.  Some 64-bit environments,
3327  * however, do not.  Therefore we have to explicitly mix and match. */
3328 #   if defined(USE_OPEN64)
3329 #       define open open64
3330 #   endif
3331 #   if defined(USE_LSEEK64)
3332 #       define lseek lseek64
3333 #   else
3334 #       if defined(USE_LLSEEK)
3335 #           define lseek llseek
3336 #       endif
3337 #   endif
3338 #   if defined(USE_STAT64)
3339 #       define stat stat64
3340 #   endif
3341 #   if defined(USE_FSTAT64)
3342 #       define fstat fstat64
3343 #   endif
3344 #   if defined(USE_LSTAT64)
3345 #       define lstat lstat64
3346 #   endif
3347 #   if defined(USE_FLOCK64)
3348 #       define flock flock64
3349 #   endif
3350 #   if defined(USE_LOCKF64)
3351 #       define lockf lockf64
3352 #   endif
3353 #   if defined(USE_FCNTL64)
3354 #       define fcntl fcntl64
3355 #   endif
3356 #   if defined(USE_TRUNCATE64)
3357 #       define truncate truncate64
3358 #   endif
3359 #   if defined(USE_FTRUNCATE64)
3360 #       define ftruncate ftruncate64
3361 #   endif
3362 #endif
3363
3364 #ifdef USE_64_BIT_STDIO
3365 #   ifdef HAS_FPOS64_T
3366 #       undef Fpos_t
3367 #       define Fpos_t fpos64_t
3368 #   endif
3369 /* Most 64-bit environments have defines like _LARGEFILE_SOURCE that
3370  * will trigger defines like the ones below.  Some 64-bit environments,
3371  * however, do not. */
3372 #   if defined(USE_FOPEN64)
3373 #       define fopen fopen64
3374 #   endif
3375 #   if defined(USE_FSEEK64)
3376 #       define fseek fseek64 /* don't do fseeko here, see perlio.c */
3377 #   endif
3378 #   if defined(USE_FTELL64)
3379 #       define ftell ftell64 /* don't do ftello here, see perlio.c */
3380 #   endif
3381 #   if defined(USE_FSETPOS64)
3382 #       define fsetpos fsetpos64
3383 #   endif
3384 #   if defined(USE_FGETPOS64)
3385 #       define fgetpos fgetpos64
3386 #   endif
3387 #   if defined(USE_TMPFILE64)
3388 #       define tmpfile tmpfile64
3389 #   endif
3390 #   if defined(USE_FREOPEN64)
3391 #       define freopen freopen64
3392 #   endif
3393 #endif
3394
3395 #if defined(OS2)
3396 #  include "iperlsys.h"
3397 #endif
3398
3399 #ifdef DOSISH
3400 #   if defined(OS2)
3401 #       include "os2ish.h"
3402 #   else
3403 #       include "dosish.h"
3404 #   endif
3405 #elif defined(VMS)
3406 #   include "vmsish.h"
3407 #elif defined(PLAN9)
3408 #   include "./plan9/plan9ish.h"
3409 #elif defined(__VOS__)
3410 #   ifdef __GNUC__
3411 #     include "./vos/vosish.h"
3412 #   else
3413 #     include "vos/vosish.h"
3414 #   endif
3415 #elif defined(__HAIKU__)
3416 #   include "haiku/haikuish.h"
3417 #else
3418 #   include "unixish.h"
3419 #endif
3420
3421 #ifdef __amigaos4__
3422 #    include "amigaos.h"
3423 #    undef FD_CLOEXEC /* a lie in AmigaOS */
3424 #endif
3425
3426 /* NSIG logic from Configure --> */
3427 #ifndef NSIG
3428 #  ifdef _NSIG
3429 #    define NSIG (_NSIG)
3430 #  elif defined(SIGMAX)
3431 #    define NSIG (SIGMAX+1)
3432 #  elif defined(SIG_MAX)
3433 #    define NSIG (SIG_MAX+1)
3434 #  elif defined(_SIG_MAX)
3435 #    define NSIG (_SIG_MAX+1)
3436 #  elif defined(MAXSIG)
3437 #    define NSIG (MAXSIG+1)
3438 #  elif defined(MAX_SIG)
3439 #    define NSIG (MAX_SIG+1)
3440 #  elif defined(SIGARRAYSIZE)
3441 #    define NSIG SIGARRAYSIZE /* Assume ary[SIGARRAYSIZE] */
3442 #  elif defined(_sys_nsig)
3443 #    define NSIG (_sys_nsig) /* Solaris 2.5 */
3444 #  else
3445      /* Default to some arbitrary number that's big enough to get most
3446       * of the common signals.  */
3447 #    define NSIG 50
3448 #  endif
3449 #endif
3450 /* <-- NSIG logic from Configure */
3451
3452 #ifndef NO_ENVIRON_ARRAY
3453 #  define USE_ENVIRON_ARRAY
3454 #endif
3455
3456 #if defined(HAS_SIGACTION) && defined(SA_SIGINFO)
3457     /* having sigaction(2) means that the OS supports both 1-arg and 3-arg
3458      * signal handlers. But the perl core itself only fully supports 1-arg
3459      * handlers, so don't enable for now.
3460      * NB: POSIX::sigaction() supports both.
3461      *
3462      * # define PERL_USE_3ARG_SIGHANDLER
3463      */
3464 #endif
3465
3466 /* Siginfo_t:
3467  * This is an alias for the OS's siginfo_t, except that where the OS
3468  * doesn't support it, declare a dummy version instead. This allows us to
3469  * have signal handler functions which always have a Siginfo_t parameter
3470  * regardless of platform, (and which will just be passed a NULL value
3471  * where the OS doesn't support HAS_SIGACTION).
3472  */
3473
3474 #if defined(HAS_SIGACTION) && defined(SA_SIGINFO)
3475     typedef siginfo_t Siginfo_t;
3476 #else
3477 #ifdef si_signo /* minix */
3478 #undef si_signo
3479 #endif
3480     typedef struct {
3481         int si_signo;
3482     } Siginfo_t;
3483 #endif
3484
3485
3486 /*
3487  * initialise to avoid floating-point exceptions from overflow, etc
3488  */
3489 #ifndef PERL_FPU_INIT
3490 #  ifdef HAS_FPSETMASK
3491 #    if HAS_FLOATINGPOINT_H
3492 #      include <floatingpoint.h>
3493 #    endif
3494 /* Some operating systems have this as a macro, which in turn expands to a comma
3495    expression, and the last sub-expression is something that gets calculated,
3496    and then they have the gall to warn that a value computed is not used. Hence
3497    cast to void.  */
3498 #    define PERL_FPU_INIT (void)fpsetmask(0)
3499 #  elif defined(SIGFPE) && defined(SIG_IGN)
3500 #    define PERL_FPU_INIT       PL_sigfpe_saved = (Sighandler_t) signal(SIGFPE, SIG_IGN)
3501 #    define PERL_FPU_PRE_EXEC   { Sigsave_t xfpe; rsignal_save(SIGFPE, PL_sigfpe_saved, &xfpe);
3502 #    define PERL_FPU_POST_EXEC    rsignal_restore(SIGFPE, &xfpe); }
3503 #  else
3504 #    define PERL_FPU_INIT
3505 #  endif
3506 #endif
3507 #ifndef PERL_FPU_PRE_EXEC
3508 #  define PERL_FPU_PRE_EXEC   {
3509 #  define PERL_FPU_POST_EXEC  }
3510 #endif
3511
3512 /* In Tru64 the cc -ieee enables the IEEE math but disables traps.
3513  * We need to reenable the "invalid" trap because otherwise generation
3514  * of NaN values leaves the IEEE fp flags in bad state, leaving any further
3515  * fp ops behaving strangely (Inf + 1 resulting in zero, for example). */
3516 #ifdef __osf__
3517 #  include <machine/fpu.h>
3518 #  define PERL_SYS_FPU_INIT \
3519      STMT_START { \
3520          ieee_set_fp_control(IEEE_TRAP_ENABLE_INV); \
3521          signal(SIGFPE, SIG_IGN); \
3522      } STMT_END
3523 #endif
3524 /* In IRIX the default for Flush to Zero bit is true,
3525  * which means that results going below the minimum of normal
3526  * floating points go to zero, instead of going denormal/subnormal.
3527  * This is unlike almost any other system running Perl, so let's clear it.
3528  * [perl #123767] IRIX64 blead (ddce084a) opbasic/arith.t failure, originally
3529  * [perl #120426] small numbers shouldn't round to zero if they have extra floating digits
3530  *
3531  * XXX The flush-to-zero behaviour should be a Configure scan.
3532  * To change the behaviour usually requires some system-specific
3533  * incantation, though, like the below. */
3534 #ifdef __sgi
3535 #  include <sys/fpu.h>
3536 #  define PERL_SYS_FPU_INIT \
3537      STMT_START { \
3538          union fpc_csr csr; \
3539          csr.fc_word = get_fpc_csr(); \
3540          csr.fc_struct.flush = 0; \
3541          set_fpc_csr(csr.fc_word); \
3542      } STMT_END
3543 #endif
3544
3545 #ifndef PERL_SYS_FPU_INIT
3546 #  define PERL_SYS_FPU_INIT NOOP
3547 #endif
3548
3549 #ifndef PERL_SYS_INIT3_BODY
3550 #  define PERL_SYS_INIT3_BODY(argvp,argcp,envp) PERL_SYS_INIT_BODY(argvp,argcp)
3551 #endif
3552
3553 /*
3554 =for apidoc_section $embedding
3555
3556 =for apidoc   Am|void|PERL_SYS_INIT |int *argc|char*** argv
3557 =for apidoc_item|    |PERL_SYS_INIT3|int *argc|char*** argv|char*** env
3558
3559 These provide system-specific tune up of the C runtime environment necessary to
3560 run Perl interpreters.  Only one should be used, and it should be called only
3561 once, before creating any Perl interpreters.
3562
3563 They differ in that C<PERL_SYS_INIT3> also initializes C<env>.
3564
3565 =for apidoc Am|void|PERL_SYS_TERM|
3566 Provides system-specific clean up of the C runtime environment after
3567 running Perl interpreters.  This should be called only once, after
3568 freeing any remaining Perl interpreters.
3569
3570 =cut
3571  */
3572
3573 #define PERL_SYS_INIT(argc, argv)       Perl_sys_init(argc, argv)
3574 #define PERL_SYS_INIT3(argc, argv, env) Perl_sys_init3(argc, argv, env)
3575 #define PERL_SYS_TERM()                 Perl_sys_term()
3576
3577 #ifndef PERL_WRITE_MSG_TO_CONSOLE
3578 #  define PERL_WRITE_MSG_TO_CONSOLE(io, msg, len) PerlIO_write(io, msg, len)
3579 #endif
3580
3581 #ifndef MAXPATHLEN
3582 #  ifdef PATH_MAX
3583 #    ifdef _POSIX_PATH_MAX
3584 #       if PATH_MAX > _POSIX_PATH_MAX
3585 /* POSIX 1990 (and pre) was ambiguous about whether PATH_MAX
3586  * included the null byte or not.  Later amendments of POSIX,
3587  * XPG4, the Austin Group, and the Single UNIX Specification
3588  * all explicitly include the null byte in the PATH_MAX.
3589  * Ditto for _POSIX_PATH_MAX. */
3590 #         define MAXPATHLEN PATH_MAX
3591 #       else
3592 #         define MAXPATHLEN _POSIX_PATH_MAX
3593 #       endif
3594 #    else
3595 #      define MAXPATHLEN (PATH_MAX+1)
3596 #    endif
3597 #  else
3598 #    define MAXPATHLEN 1024     /* Err on the large side. */
3599 #  endif
3600 #endif
3601
3602 /* clang Thread Safety Analysis/Annotations/Attributes
3603  * http://clang.llvm.org/docs/ThreadSafetyAnalysis.html
3604  *
3605  * Available since clang 3.6-ish (appeared in 3.4, but shaky still in 3.5).
3606  * Apple XCode hijacks __clang_major__ and __clang_minor__
3607  * (6.1 means really clang 3.6), so needs extra hijinks
3608  * (could probably also test the contents of __apple_build_version__).
3609  */
3610 #if defined(USE_ITHREADS) && defined(I_PTHREAD) && \
3611     defined(__clang__) && \
3612     !defined(SWIG) && \
3613   ((!defined(__apple_build_version__) &&               \
3614     ((__clang_major__ == 3 && __clang_minor__ >= 6) || \
3615      (__clang_major__ >= 4))) || \
3616    (defined(__apple_build_version__) &&                \
3617     ((__clang_major__ == 6 && __clang_minor__ >= 1) || \
3618      (__clang_major__ >= 7))))
3619 #  define PERL_TSA__(x)   __attribute__((x))
3620 #  define PERL_TSA_ACTIVE
3621 #else
3622 #  define PERL_TSA__(x)   /* No TSA, make TSA attributes no-ops. */
3623 #  undef PERL_TSA_ACTIVE
3624 #endif
3625
3626 /* PERL_TSA_CAPABILITY() is used to annotate typedefs.
3627  * typedef old_type PERL_TSA_CAPABILITY("mutex") new_type;
3628  */
3629 #define PERL_TSA_CAPABILITY(x) \
3630     PERL_TSA__(capability(x))
3631
3632 /* In the below examples the mutex must be lexically visible, usually
3633  * either as global variables, or as function arguments. */
3634
3635 /* PERL_TSA_GUARDED_BY() is used to annotate global variables.
3636  *
3637  * Foo foo PERL_TSA_GUARDED_BY(mutex);
3638  */
3639 #define PERL_TSA_GUARDED_BY(x) \
3640     PERL_TSA__(guarded_by(x))
3641
3642 /* PERL_TSA_PT_GUARDED_BY() is used to annotate global pointers.
3643  * The data _behind_ the pointer is guarded.
3644  *
3645  * Foo* ptr PERL_TSA_PT_GUARDED_BY(mutex);
3646  */
3647 #define PERL_TSA_PT_GUARDED_BY(x) \
3648     PERL_TSA__(pt_guarded_by(x))
3649
3650 /* PERL_TSA_REQUIRES() is used to annotate functions.
3651  * The caller MUST hold the resource when calling the function.
3652  *
3653  * void Foo() PERL_TSA_REQUIRES(mutex);
3654  */
3655 #define PERL_TSA_REQUIRES(x) \
3656     PERL_TSA__(requires_capability(x))
3657
3658 /* PERL_TSA_EXCLUDES() is used to annotate functions.
3659  * The caller MUST NOT hold resource when calling the function.
3660  *
3661  * EXCLUDES should be used when the function first acquires
3662  * the resource and then releases it.  Use to avoid deadlock.
3663  *
3664  * void Foo() PERL_TSA_EXCLUDES(mutex);
3665  */
3666 #define PERL_TSA_EXCLUDES(x) \
3667     PERL_TSA__(locks_excluded(x))
3668
3669 /* PERL_TSA_ACQUIRE() is used to annotate functions.
3670  * The caller MUST NOT hold the resource when calling the function,
3671  * and the function will acquire the resource.
3672  *
3673  * void Foo() PERL_TSA_ACQUIRE(mutex);
3674  */
3675 #define PERL_TSA_ACQUIRE(x) \
3676     PERL_TSA__(acquire_capability(x))
3677
3678 /* PERL_TSA_RELEASE() is used to annotate functions.
3679  * The caller MUST hold the resource when calling the function,
3680  * and the function will release the resource.
3681  *
3682  * void Foo() PERL_TSA_RELEASE(mutex);
3683  */
3684 #define PERL_TSA_RELEASE(x) \
3685     PERL_TSA__(release_capability(x))
3686
3687 /* PERL_TSA_NO_TSA is used to annotate functions.
3688  * Used when being intentionally unsafe, or when the code is too
3689  * complicated for the analysis.  Use sparingly.
3690  *
3691  * void Foo() PERL_TSA_NO_TSA;
3692  */
3693 #define PERL_TSA_NO_TSA \
3694     PERL_TSA__(no_thread_safety_analysis)
3695
3696 /* There are more annotations/attributes available, see the clang
3697  * documentation for details. */
3698
3699 #if defined(USE_ITHREADS)
3700 #  if   defined(WIN32)
3701 #    include <win32thread.h>
3702 #  elif defined(OS2)
3703 #    include "os2thread.h"
3704 #  elif defined(I_MACH_CTHREADS)
3705 #    include <mach/cthreads.h>
3706 typedef cthread_t       perl_os_thread;
3707 typedef mutex_t         perl_mutex;
3708 typedef condition_t     perl_cond;
3709 typedef void *          perl_key;
3710 #  elif defined(I_PTHREAD) /* Posix threads */
3711 #    include <pthread.h>
3712 typedef pthread_t       perl_os_thread;
3713 typedef pthread_mutex_t PERL_TSA_CAPABILITY("mutex") perl_mutex;
3714 typedef pthread_cond_t  perl_cond;
3715 typedef pthread_key_t   perl_key;
3716 #  endif
3717
3718 /* Many readers; single writer */
3719 typedef struct {
3720     perl_mutex lock;
3721     perl_cond  wakeup;
3722     SSize_t    readers_count;
3723 } perl_RnW1_mutex_t;
3724
3725
3726 #endif /* USE_ITHREADS */
3727
3728 #ifdef PERL_TSA_ACTIVE
3729 /* Since most pthread mutex interfaces have not been annotated, we
3730  * need to have these wrappers. The NO_TSA annotation is quite ugly
3731  * but it cannot be avoided in plain C, unlike in C++, where one could
3732  * e.g. use ACQUIRE() with no arg on a mutex lock method.
3733  *
3734  * The bodies of these wrappers are in util.c
3735  *
3736  * TODO: however, some platforms are starting to get these clang
3737  * thread safety annotations for pthreads, for example FreeBSD.
3738  * Do we need a way to a bypass these wrappers? */
3739 EXTERN_C int perl_tsa_mutex_lock(perl_mutex* mutex)
3740   PERL_TSA_ACQUIRE(*mutex)
3741   PERL_TSA_NO_TSA;
3742 EXTERN_C int perl_tsa_mutex_unlock(perl_mutex* mutex)
3743   PERL_TSA_RELEASE(*mutex)
3744   PERL_TSA_NO_TSA;
3745 #endif
3746
3747 #if defined(WIN32)
3748 #  include "win32.h"
3749 #endif
3750
3751 #define STATUS_UNIX     PL_statusvalue
3752 #ifdef VMS
3753 #   define STATUS_NATIVE        PL_statusvalue_vms
3754 /*
3755  * vaxc$errno is only guaranteed to be valid if errno == EVMSERR, otherwise
3756  * its contents can not be trusted.  Unfortunately, Perl seems to check
3757  * it on exit, so it when PL_statusvalue_vms is updated, vaxc$errno should
3758  * be updated also.
3759  */
3760 #  include <stsdef.h>
3761 #  include <ssdef.h>
3762 /* Presume this because if VMS changes it, it will require a new
3763  * set of APIs for waiting on children for binary compatibility.
3764  */
3765 #  define child_offset_bits (8)
3766 #  ifndef C_FAC_POSIX
3767 #  define C_FAC_POSIX 0x35A000
3768 #  endif
3769
3770 /*  STATUS_EXIT - validates and returns a NATIVE exit status code for the
3771  * platform from the existing UNIX or Native status values.
3772  */
3773
3774 #   define STATUS_EXIT \
3775         (((I32)PL_statusvalue_vms == -1 ? SS$_ABORT : PL_statusvalue_vms) | \
3776            (VMSISH_HUSHED ? STS$M_INHIB_MSG : 0))
3777
3778
3779 /* STATUS_NATIVE_CHILD_SET - Calculate UNIX status that matches the child
3780  * exit code and shifts the UNIX value over the correct number of bits to
3781  * be a child status.  Usually the number of bits is 8, but that could be
3782  * platform dependent.  The NATIVE status code is presumed to have either
3783  * from a child process.
3784  */
3785
3786 /* This is complicated.  The child processes return a true native VMS
3787    status which must be saved.  But there is an assumption in Perl that
3788    the UNIX child status has some relationship to errno values, so
3789    Perl tries to translate it to text in some of the tests.
3790    In order to get the string translation correct, for the error, errno
3791    must be EVMSERR, but that generates a different text message
3792    than what the test programs are expecting.  So an errno value must
3793    be derived from the native status value when an error occurs.
3794    That will hide the true native status message.  With this version of
3795    perl, the true native child status can always be retrieved so that
3796    is not a problem.  But in this case, Pl_statusvalue and errno may
3797    have different values in them.
3798  */
3799
3800 #   define STATUS_NATIVE_CHILD_SET(n) \
3801         STMT_START {                                                    \
3802             I32 evalue = (I32)n;                                        \
3803             if (evalue == EVMSERR) {                                    \
3804               PL_statusvalue_vms = vaxc$errno;                          \
3805               PL_statusvalue = evalue;                                  \
3806             } else {                                                    \
3807               PL_statusvalue_vms = evalue;                              \
3808               if (evalue == -1) {                                       \
3809                 PL_statusvalue = -1;                                    \
3810                 PL_statusvalue_vms = SS$_ABORT; /* Should not happen */ \
3811               } else                                                    \
3812                 PL_statusvalue = Perl_vms_status_to_unix(evalue, 1);    \
3813               set_vaxc_errno(evalue);                                   \
3814               if ((PL_statusvalue_vms & C_FAC_POSIX) == C_FAC_POSIX)    \
3815                   set_errno(EVMSERR);                                   \
3816               else set_errno(Perl_vms_status_to_unix(evalue, 0));       \
3817               PL_statusvalue = PL_statusvalue << child_offset_bits;     \
3818             }                                                           \
3819         } STMT_END
3820
3821 #   ifdef VMSISH_STATUS
3822 #       define STATUS_CURRENT   (VMSISH_STATUS ? STATUS_NATIVE : STATUS_UNIX)
3823 #   else
3824 #       define STATUS_CURRENT   STATUS_UNIX
3825 #   endif
3826
3827   /* STATUS_UNIX_SET - takes a UNIX/POSIX errno value and attempts to update
3828    * the NATIVE status to an equivalent value.  Can not be used to translate
3829    * exit code values as exit code values are not guaranteed to have any
3830    * relationship at all to errno values.
3831    * This is used when Perl is forcing errno to have a specific value.
3832    */
3833 #   define STATUS_UNIX_SET(n)                           \
3834         STMT_START {                                    \
3835             I32 evalue = (I32)n;                        \
3836             PL_statusvalue = evalue;                    \
3837             if (PL_statusvalue != -1) {                 \
3838                 if (PL_statusvalue != EVMSERR) {        \
3839                   PL_statusvalue &= 0xFFFF;             \
3840                   if (MY_POSIX_EXIT)                    \
3841                     PL_statusvalue_vms=PL_statusvalue ? SS$_ABORT : SS$_NORMAL;\
3842                   else PL_statusvalue_vms = Perl_unix_status_to_vms(evalue); \
3843                 }                                       \
3844                 else {                                  \
3845                   PL_statusvalue_vms = vaxc$errno;      \
3846                 }                                       \
3847             }                                           \
3848             else PL_statusvalue_vms = SS$_ABORT;        \
3849             set_vaxc_errno(PL_statusvalue_vms);         \
3850         } STMT_END
3851
3852   /* STATUS_UNIX_EXIT_SET - Takes a UNIX/POSIX exit code and sets
3853    * the NATIVE error status based on it.
3854    *
3855    * When in the default mode to comply with the Perl VMS documentation,
3856    * 0 is a success and any other code sets the NATIVE status to a failure
3857    * code of SS$_ABORT.
3858    *
3859    * In the new POSIX EXIT mode, native status will be set so that the
3860    * actual exit code will can be retrieved by the calling program or
3861    * shell.
3862    *
3863    * If the exit code is not clearly a UNIX parent or child exit status,
3864    * it will be passed through as a VMS status.
3865    */
3866
3867 #   define STATUS_UNIX_EXIT_SET(n)                      \
3868         STMT_START {                                    \
3869             I32 evalue = (I32)n;                        \
3870             PL_statusvalue = evalue;                    \
3871             if (MY_POSIX_EXIT) { \
3872               if (evalue <= 0xFF00) {           \
3873                   if (evalue > 0xFF)                    \
3874                     evalue = ((U8) (evalue >> child_offset_bits)); \
3875                   PL_statusvalue_vms =          \
3876                     (C_FAC_POSIX | (evalue << 3 ) |     \
3877                     ((evalue == 1) ? (STS$K_ERROR | STS$M_INHIB_MSG) : 1)); \
3878               } else /* forgive them Perl, for they have sinned */ \
3879                 PL_statusvalue_vms = evalue; \
3880             } else { \
3881               if (evalue == 0)                  \
3882                 PL_statusvalue_vms = SS$_NORMAL;        \
3883               else if (evalue <= 0xFF00) \
3884                 PL_statusvalue_vms = SS$_ABORT; \
3885               else { /* forgive them Perl, for they have sinned */ \
3886                   if (evalue != EVMSERR) PL_statusvalue_vms = evalue; \
3887                   else PL_statusvalue_vms = vaxc$errno; \
3888                   /* And obviously used a VMS status value instead of UNIX */ \
3889                   PL_statusvalue = EVMSERR;             \
3890               } \
3891               set_vaxc_errno(PL_statusvalue_vms);       \
3892             }                                           \
3893         } STMT_END
3894
3895
3896   /* STATUS_EXIT_SET - Takes a NATIVE/UNIX/POSIX exit code
3897    * and sets the NATIVE error status based on it.  This special case
3898    * is needed to maintain compatibility with past VMS behavior.
3899    *
3900    * In the default mode on VMS, this number is passed through as
3901    * both the NATIVE and UNIX status.  Which makes it different
3902    * that the STATUS_UNIX_EXIT_SET.
3903    *
3904    * In the new POSIX EXIT mode, native status will be set so that the
3905    * actual exit code will can be retrieved by the calling program or
3906    * shell.
3907    *
3908    * A POSIX exit code is from 0 to 255.  If the exit code is higher
3909    * than this, it needs to be assumed that it is a VMS exit code and
3910    * passed through.
3911    */
3912
3913 #   define STATUS_EXIT_SET(n)                           \
3914         STMT_START {                                    \
3915             I32 evalue = (I32)n;                        \
3916             PL_statusvalue = evalue;                    \
3917             if (MY_POSIX_EXIT)                          \
3918                 if (evalue > 255) PL_statusvalue_vms = evalue; else {   \
3919                   PL_statusvalue_vms = \
3920                     (C_FAC_POSIX | (evalue << 3 ) |     \
3921                      ((evalue == 1) ? (STS$K_ERROR | STS$M_INHIB_MSG) : 1));} \
3922             else                                        \
3923                 PL_statusvalue_vms = evalue ? evalue : SS$_NORMAL; \
3924             set_vaxc_errno(PL_statusvalue_vms);         \
3925         } STMT_END
3926
3927
3928  /* This macro forces a success status */
3929 #   define STATUS_ALL_SUCCESS   \
3930         (PL_statusvalue = 0, PL_statusvalue_vms = SS$_NORMAL)
3931
3932  /* This macro forces a failure status */
3933 #   define STATUS_ALL_FAILURE   (PL_statusvalue = 1, \
3934      vaxc$errno = PL_statusvalue_vms = MY_POSIX_EXIT ? \
3935         (C_FAC_POSIX | (1 << 3) | STS$K_ERROR | STS$M_INHIB_MSG) : SS$_ABORT)
3936
3937 #elif defined(__amigaos4__)
3938  /* A somewhat experimental attempt to simulate posix return code values */
3939 #   define STATUS_NATIVE        PL_statusvalue_posix
3940 #   define STATUS_NATIVE_CHILD_SET(n)                      \
3941         STMT_START {                                       \
3942             PL_statusvalue_posix = (n);                    \
3943             if (PL_statusvalue_posix < 0) {                \
3944                 PL_statusvalue = -1;                       \
3945             }                                              \
3946             else {                                         \
3947                 PL_statusvalue = n << 8;                   \
3948             }                                              \
3949         } STMT_END
3950 #   define STATUS_UNIX_SET(n)           \
3951         STMT_START {                    \
3952             PL_statusvalue = (n);               \
3953             if (PL_statusvalue != -1)   \
3954                 PL_statusvalue &= 0xFFFF;       \
3955         } STMT_END
3956 #   define STATUS_UNIX_EXIT_SET(n) STATUS_UNIX_SET(n)
3957 #   define STATUS_EXIT_SET(n) STATUS_UNIX_SET(n)
3958 #   define STATUS_CURRENT STATUS_UNIX
3959 #   define STATUS_EXIT STATUS_UNIX
3960 #   define STATUS_ALL_SUCCESS   (PL_statusvalue = 0, PL_statusvalue_posix = 0)
3961 #   define STATUS_ALL_FAILURE   (PL_statusvalue = 1, PL_statusvalue_posix = 1)
3962
3963 #else
3964 #   define STATUS_NATIVE        PL_statusvalue_posix
3965 #   if defined(WCOREDUMP)
3966 #       define STATUS_NATIVE_CHILD_SET(n)                  \
3967             STMT_START {                                   \
3968                 PL_statusvalue_posix = (n);                \
3969                 if (PL_statusvalue_posix == -1)            \
3970                     PL_statusvalue = -1;                   \
3971                 else {                                     \
3972                     PL_statusvalue =                       \
3973                         (WIFEXITED(PL_statusvalue_posix) ? (WEXITSTATUS(PL_statusvalue_posix) << 8) : 0) |  \
3974                         (WIFSIGNALED(PL_statusvalue_posix) ? (WTERMSIG(PL_statusvalue_posix) & 0x7F) : 0) | \
3975                         (WIFSIGNALED(PL_statusvalue_posix) && WCOREDUMP(PL_statusvalue_posix) ? 0x80 : 0);  \
3976                 }                                          \
3977             } STMT_END
3978 #   elif defined(WIFEXITED)
3979 #       define STATUS_NATIVE_CHILD_SET(n)                  \
3980             STMT_START {                                   \
3981                 PL_statusvalue_posix = (n);                \
3982                 if (PL_statusvalue_posix == -1)            \
3983                     PL_statusvalue = -1;                   \
3984                 else {                                     \
3985                     PL_statusvalue =                       \
3986                         (WIFEXITED(PL_statusvalue_posix) ? (WEXITSTATUS(PL_statusvalue_posix) << 8) : 0) |  \
3987                         (WIFSIGNALED(PL_statusvalue_posix) ? (WTERMSIG(PL_statusvalue_posix) & 0x7F) : 0);  \
3988                 }                                          \
3989             } STMT_END
3990 #   else
3991 #       define STATUS_NATIVE_CHILD_SET(n)                  \
3992             STMT_START {                                   \
3993                 PL_statusvalue_posix = (n);                \
3994                 if (PL_statusvalue_posix == -1)            \
3995                     PL_statusvalue = -1;                   \
3996                 else {                                     \
3997                     PL_statusvalue =                       \
3998                         PL_statusvalue_posix & 0xFFFF;     \
3999                 }                                          \
4000             } STMT_END
4001 #   endif
4002 #   define STATUS_UNIX_SET(n)           \
4003         STMT_START {                    \
4004             PL_statusvalue = (n);               \
4005             if (PL_statusvalue != -1)   \
4006                 PL_statusvalue &= 0xFFFF;       \
4007         } STMT_END
4008 #   define STATUS_UNIX_EXIT_SET(n) STATUS_UNIX_SET(n)
4009 #   define STATUS_EXIT_SET(n) STATUS_UNIX_SET(n)
4010 #   define STATUS_CURRENT STATUS_UNIX
4011 #   define STATUS_EXIT STATUS_UNIX
4012 #   define STATUS_ALL_SUCCESS   (PL_statusvalue = 0, PL_statusvalue_posix = 0)
4013 #   define STATUS_ALL_FAILURE   (PL_statusvalue = 1, PL_statusvalue_posix = 1)
4014 #endif
4015
4016 /* flags in PL_exit_flags for nature of exit() */
4017 #define PERL_EXIT_EXPECTED      0x01
4018 #define PERL_EXIT_DESTRUCT_END  0x02  /* Run END in perl_destruct */
4019 #define PERL_EXIT_WARN          0x04  /* Warn if Perl_my_exit() or Perl_my_failure_exit() called */
4020 #define PERL_EXIT_ABORT         0x08  /* Call abort() if Perl_my_exit() or Perl_my_failure_exit() called */
4021
4022 #ifndef PERL_CORE
4023 /* format to use for version numbers in file/directory names */
4024 /* XXX move to Configure? */
4025 /* This was only ever used for the current version, and that can be done at
4026    compile time, as PERL_FS_VERSION, so should we just delete it?  */
4027 #  ifndef PERL_FS_VER_FMT
4028 #    define PERL_FS_VER_FMT     "%d.%d.%d"
4029 #  endif
4030 #endif
4031
4032 #ifndef PERL_FS_VERSION
4033 #  define PERL_FS_VERSION       PERL_VERSION_STRING
4034 #endif
4035
4036 /*
4037
4038 =for apidoc_section $io
4039 =for apidoc Amn|void|PERL_FLUSHALL_FOR_CHILD
4040
4041 This defines a way to flush all output buffers.  This may be a
4042 performance issue, so we allow people to disable it.  Also, if
4043 we are using stdio, there are broken implementations of fflush(NULL)
4044 out there, Solaris being the most prominent.
4045
4046 =cut
4047  */
4048
4049 #ifndef PERL_FLUSHALL_FOR_CHILD
4050 # if defined(USE_PERLIO) || defined(FFLUSH_NULL)
4051 #  define PERL_FLUSHALL_FOR_CHILD       PerlIO_flush((PerlIO*)NULL)
4052 # elif defined(FFLUSH_ALL)
4053 #  define PERL_FLUSHALL_FOR_CHILD       my_fflush_all()
4054 # else
4055 #  define PERL_FLUSHALL_FOR_CHILD       NOOP
4056 # endif
4057 #endif
4058
4059 #ifndef PERL_WAIT_FOR_CHILDREN
4060 #  define PERL_WAIT_FOR_CHILDREN        NOOP
4061 #endif
4062
4063 /* the traditional thread-unsafe notion of "current interpreter". */
4064 #ifndef PERL_SET_INTERP
4065 #  define PERL_SET_INTERP(i)                                            \
4066             STMT_START { PL_curinterp = (PerlInterpreter*)(i);          \
4067                          PERL_SET_NON_tTHX_CONTEXT(i);                  \
4068             } STMT_END
4069 #endif
4070
4071 #ifndef PERL_GET_INTERP
4072 #  define PERL_GET_INTERP               (PL_curinterp)
4073 #endif
4074
4075 #if defined(MULTIPLICITY) && !defined(PERL_GET_THX)
4076 #  define PERL_GET_THX          ((PerlInterpreter *)PERL_GET_CONTEXT)
4077 #  define PERL_SET_THX(t)               PERL_SET_CONTEXT(t)
4078 #endif
4079
4080 /*
4081     This replaces the previous %_ "hack" by the "%p" hacks.
4082     All that is required is that the perl source does not
4083     use "%-p" or "%-<number>p" or "%<number>p" formats.
4084     These formats will still work in perl code.
4085     See comments in sv.c for further details.
4086
4087     Robin Barker 2005-07-14
4088
4089     No longer use %1p for VDf = %vd.  RMB 2007-10-19
4090 */
4091
4092 #ifndef SVf_
4093 #  define SVf_(n) "-" STRINGIFY(n) "p"
4094 #endif
4095
4096 #ifndef SVf
4097 #  define SVf "-p"
4098 #endif
4099
4100 #ifndef SVf32
4101 #  define SVf32 SVf_(32)
4102 #endif
4103
4104 #ifndef SVf256
4105 #  define SVf256 SVf_(256)
4106 #endif
4107
4108 #define SVfARG(p) ((void*)(p))
4109
4110 /* Render an SV as a quoted and escaped string suitable for an error message.
4111  * Only shows the first PERL_QUOTEDPREFIX_LEN characters, and adds ellipses if the
4112  * string is too long.
4113  */
4114 #ifndef PERL_QUOTEDPREFIX_LEN
4115 # define PERL_QUOTEDPREFIX_LEN 256
4116 #endif
4117 #ifndef SVf_QUOTEDPREFIX
4118 #  define SVf_QUOTEDPREFIX "5p"
4119 #endif
4120
4121 /* like %s but runs through the quoted prefix logic */
4122 #ifndef PVf_QUOTEDPREFIX
4123 #  define PVf_QUOTEDPREFIX "1p"
4124 #endif
4125
4126 #ifndef HEKf
4127 #  define HEKf "2p"
4128 #endif
4129
4130 #ifndef HEKf_QUOTEDPREFIX
4131 #  define HEKf_QUOTEDPREFIX "7p"
4132 #endif
4133
4134 /* Not ideal, but we cannot easily include a number in an already-numeric
4135  * format sequence. */
4136 #ifndef HEKf256
4137 #  define HEKf256 "3p"
4138 #endif
4139
4140 #ifndef HEKf256_QUOTEDPREFIX
4141 #  define HEKf256_QUOTEDPREFIX "8p"
4142 #endif
4143
4144 #define HEKfARG(p) ((void*)(p))
4145
4146 /* Documented in perlguts
4147  *
4148  * %4p and %9p are custom formats for handling UTF8 parameters.
4149  * They only occur when prefixed by specific other formats.
4150  */
4151 #ifndef UTF8f
4152 #  define UTF8f "d%" UVuf "%4p"
4153 #endif
4154 #ifndef UTF8f_QUOTEDPREFIX
4155 #  define UTF8f_QUOTEDPREFIX "d%" UVuf "%9p"
4156 #endif
4157 #define UTF8fARG(u,l,p) (int)cBOOL(u), (UV)(l), (void*)(p)
4158
4159 #define PNf UTF8f
4160 #define PNfARG(pn) (int)1, (UV)PadnameLEN(pn), (void *)PadnamePV(pn)
4161
4162 #define HvNAMEf "6p"
4163 #define HvNAMEf_QUOTEDPREFIX "10p"
4164
4165 #define HvNAMEfARG(hv) ((void*)(hv))
4166
4167 #ifdef PERL_CORE
4168 /* not used; but needed for backward compatibility with XS code? - RMB
4169 =for apidoc_section $io_formats
4170 =for apidoc AmnD|const char *|UVf
4171
4172 Obsolete form of C<UVuf>, which you should convert to instead use
4173
4174 =cut
4175 */
4176 #  undef UVf
4177 #elif !defined(UVf)
4178 #  define UVf UVuf
4179 #endif
4180
4181 #if !defined(DEBUGGING) && !defined(NDEBUG)
4182 #  define NDEBUG 1
4183 #endif
4184 #include <assert.h>
4185
4186 /* For functions that are marked as __attribute__noreturn__, it's not
4187    appropriate to call return.  In either case, include the lint directive.
4188  */
4189 #ifdef HASATTRIBUTE_NORETURN
4190 #  define NORETURN_FUNCTION_END NOT_REACHED;
4191 #else
4192 #  define NORETURN_FUNCTION_END NOT_REACHED; return 0
4193 #endif
4194
4195 #ifdef HAS_BUILTIN_EXPECT
4196 #  define EXPECT(expr,val)                  __builtin_expect(expr,val)
4197 #else
4198 #  define EXPECT(expr,val)                  (expr)
4199 #endif
4200
4201 /*
4202 =for apidoc_section $directives
4203
4204 =for apidoc Am||LIKELY|bool expr
4205
4206 Returns the input unchanged, but at the same time it gives a branch prediction
4207 hint to the compiler that this condition is likely to be true.
4208
4209 =for apidoc Am||UNLIKELY|bool expr
4210
4211 Returns the input unchanged, but at the same time it gives a branch prediction
4212 hint to the compiler that this condition is likely to be false.
4213
4214 =cut
4215 */
4216 #define LIKELY(cond)                        EXPECT(cBOOL(cond),TRUE)
4217 #define UNLIKELY(cond)                      EXPECT(cBOOL(cond),FALSE)
4218
4219 #ifdef HAS_BUILTIN_CHOOSE_EXPR
4220 /* placeholder */
4221 #endif
4222
4223 /* STATIC_ASSERT_DECL/STATIC_ASSERT_STMT are like assert(), but for compile
4224    time invariants. That is, their argument must be a constant expression that
4225    can be verified by the compiler. This expression can contain anything that's
4226    known to the compiler, e.g. #define constants, enums, or sizeof (...). If
4227    the expression evaluates to 0, compilation fails.
4228    Because they generate no runtime code (i.e.  their use is "free"), they're
4229    always active, even under non-DEBUGGING builds.
4230    STATIC_ASSERT_DECL expands to a declaration and is suitable for use at
4231    file scope (outside of any function).
4232    STATIC_ASSERT_STMT expands to a statement and is suitable for use inside a
4233    function.
4234 */
4235 #if (! defined(__IBMC__) || __IBMC__ >= 1210)                               \
4236  && ((   defined(static_assert) && (   defined(_ISOC11_SOURCE)              \
4237                                     || (__STDC_VERSION__ - 0) >= 201101L))  \
4238      || (defined(__cplusplus) && __cplusplus >= 201103L))
4239 /* XXX static_assert is a macro defined in <assert.h> in C11 or a compiler
4240    builtin in C++11.  But IBM XL C V11 does not support _Static_assert, no
4241    matter what <assert.h> says.
4242 */
4243 #  define STATIC_ASSERT_DECL(COND) static_assert(COND, #COND)
4244 #else
4245 /* We use a bit-field instead of an array because gcc accepts
4246    'typedef char x[n]' where n is not a compile-time constant.
4247    We want to enforce constantness.
4248 */
4249 #  define STATIC_ASSERT_2(COND, SUFFIX) \
4250     typedef struct { \
4251         unsigned int _static_assertion_failed_##SUFFIX : (COND) ? 1 : -1; \
4252     } _static_assertion_failed_##SUFFIX PERL_UNUSED_DECL
4253 #  define STATIC_ASSERT_1(COND, SUFFIX) STATIC_ASSERT_2(COND, SUFFIX)
4254 #  define STATIC_ASSERT_DECL(COND)    STATIC_ASSERT_1(COND, __LINE__)
4255 #endif
4256 /* We need this wrapper even in C11 because 'case X: static_assert(...);' is an
4257    error (static_assert is a declaration, and only statements can have labels).
4258 */
4259 #define STATIC_ASSERT_STMT(COND)      STMT_START { STATIC_ASSERT_DECL(COND); } STMT_END
4260
4261 #ifndef __has_builtin
4262 #  define __has_builtin(x) 0 /* not a clang style compiler */
4263 #endif
4264
4265 /*
4266 =for apidoc Am||ASSUME|bool expr
4267 C<ASSUME> is like C<assert()>, but it has a benefit in a release build. It is a
4268 hint to a compiler about a statement of fact in a function call free
4269 expression, which allows the compiler to generate better machine code.  In a
4270 debug build, C<ASSUME(x)> is a synonym for C<assert(x)>. C<ASSUME(0)> means the
4271 control path is unreachable. In a for loop, C<ASSUME> can be used to hint that
4272 a loop will run at least X times. C<ASSUME> is based off MSVC's C<__assume>
4273 intrinsic function, see its documents for more details.
4274
4275 =cut
4276 */
4277
4278 #if __has_builtin(__builtin_unreachable)
4279 #    define HAS_BUILTIN_UNREACHABLE
4280 #elif PERL_GCC_VERSION_GE(4,5,0)
4281 #    define HAS_BUILTIN_UNREACHABLE
4282 #endif
4283
4284 #ifdef DEBUGGING
4285 #  define ASSUME(x) assert(x)
4286 #elif __has_builtin(__builtin_assume)
4287 #  if defined(__clang__) || defined(__clang)
4288 #    define ASSUME(x)  CLANG_DIAG_IGNORE(-Wassume)      \
4289                        __builtin_assume (x)             \
4290                        CLANG_DIAG_RESTORE
4291 #  else
4292 #    define ASSUME(x)  __builtin_assume(x)
4293 #  endif
4294 #elif defined(_MSC_VER)
4295 #  define ASSUME(x) __assume(x)
4296 #elif defined(__ARMCC_VERSION) /* untested */
4297 #  define ASSUME(x) __promise(x)
4298 #elif defined(HAS_BUILTIN_UNREACHABLE)
4299     /* Compilers can take the hint from something being unreachable */
4300 #    define ASSUME(x) ((x) ? (void) 0 : __builtin_unreachable())
4301 #else
4302     /* Not DEBUGGING, so assert() is a no-op, but a random compiler might
4303      * define assert() to its own special optimization token so pass it through
4304      * to C lib as a last resort */
4305 #  define ASSUME(x) assert(x)
4306 #endif
4307
4308 #ifdef HAS_BUILTIN_UNREACHABLE
4309 #  define NOT_REACHED                                                       \
4310         STMT_START {                                                        \
4311             ASSUME(!"UNREACHABLE"); __builtin_unreachable();                \
4312         } STMT_END
4313 #  undef HAS_BUILTIN_UNREACHABLE /* Don't leak out this internal symbol */
4314 #elif ! defined(__GNUC__) && (defined(__sun) || defined(__hpux))
4315     /* These just complain that NOT_REACHED isn't reached */
4316 #  define NOT_REACHED
4317 #else
4318 #  define NOT_REACHED  ASSUME(!"UNREACHABLE")
4319 #endif
4320
4321 /* Some unistd.h's give a prototype for pause() even though
4322    HAS_PAUSE ends up undefined.  This causes the #define
4323    below to be rejected by the compiler.  Sigh.
4324 */
4325 #ifdef HAS_PAUSE
4326 #define Pause   pause
4327 #else
4328 #define Pause() sleep((32767<<16)+32767)
4329 #endif
4330
4331 #ifndef IOCPARM_LEN
4332 #   ifdef IOCPARM_MASK
4333         /* on BSDish systems we're safe */
4334 #       define IOCPARM_LEN(x)  (((x) >> 16) & IOCPARM_MASK)
4335 #   elif defined(_IOC_SIZE) && defined(__GLIBC__)
4336         /* on Linux systems we're safe; except when we're not [perl #38223] */
4337 #       define IOCPARM_LEN(x) (_IOC_SIZE(x) < 256 ? 256 : _IOC_SIZE(x))
4338 #   else
4339         /* otherwise guess at what's safe */
4340 #       define IOCPARM_LEN(x)   256
4341 #   endif
4342 #endif
4343
4344 #if defined(__CYGWIN__)
4345 /* USEMYBINMODE
4346  *   This symbol, if defined, indicates that the program should
4347  *   use the routine my_binmode(FILE *fp, char iotype, int mode) to insure
4348  *   that a file is in "binary" mode -- that is, that no translation
4349  *   of bytes occurs on read or write operations.
4350  */
4351 #  define USEMYBINMODE /**/
4352 #  include <io.h> /* for setmode() prototype */
4353 #  define my_binmode(fp, iotype, mode) \
4354             cBOOL(PerlLIO_setmode(fileno(fp), mode) != -1)
4355 #endif
4356
4357 #ifdef __CYGWIN__
4358 void init_os_extras(void);
4359 #endif
4360
4361 #ifdef UNION_ANY_DEFINITION
4362 UNION_ANY_DEFINITION;
4363 #else
4364 union any {
4365     void*       any_ptr;
4366     SV*         any_sv;
4367     SV**        any_svp;
4368     GV*         any_gv;
4369     AV*         any_av;
4370     HV*         any_hv;
4371     OP*         any_op;
4372     char*       any_pv;
4373     char**      any_pvp;
4374     I32         any_i32;
4375     U32         any_u32;
4376     IV          any_iv;
4377     UV          any_uv;
4378     long        any_long;
4379     bool        any_bool;
4380     Size_t      any_size;
4381     SSize_t     any_ssize;
4382     STRLEN      any_strlen;
4383     void        (*any_dptr) (void*);
4384     void        (*any_dxptr) (pTHX_ void*);
4385 };
4386 #endif
4387
4388 typedef I32 (*filter_t) (pTHX_ int, SV *, int);
4389
4390 #define FILTER_READ(idx, sv, len)  filter_read(idx, sv, len)
4391 #define FILTER_DATA(idx) \
4392             (PL_parser ? AvARRAY(PL_parser->rsfp_filters)[idx] : NULL)
4393 #define FILTER_ISREADER(idx) \
4394             (PL_parser && PL_parser->rsfp_filters \
4395                 && idx >= AvFILLp(PL_parser->rsfp_filters))
4396 #define PERL_FILTER_EXISTS(i) \
4397             (PL_parser && PL_parser->rsfp_filters \
4398                 && (Size_t) (i) < av_count(PL_parser->rsfp_filters))
4399
4400 #if defined(_AIX) && !defined(_AIX43)
4401 #if defined(USE_REENTRANT) || defined(_REENTRANT) || defined(_THREAD_SAFE)
4402 /* We cannot include <crypt.h> to get the struct crypt_data
4403  * because of setkey prototype problems when threading */
4404 typedef        struct crypt_data {     /* straight from /usr/include/crypt.h */
4405     /* From OSF, Not needed in AIX
4406        char C[28], D[28];
4407     */
4408     char E[48];
4409     char KS[16][48];
4410     char block[66];
4411     char iobuf[16];
4412 } CRYPTD;
4413 #endif /* threading */
4414 #endif /* AIX */
4415
4416 #ifndef PERL_CALLCONV
4417 #  ifdef __cplusplus
4418 #    define PERL_CALLCONV  EXTERN_C
4419 #  else
4420 #    define PERL_CALLCONV
4421 #  endif
4422 #endif
4423 #ifndef PERL_CALLCONV_NO_RET
4424 #    define PERL_CALLCONV_NO_RET PERL_CALLCONV
4425 #endif
4426
4427 /* PERL_STATIC_NO_RET is supposed to be equivalent to STATIC on builds that
4428    dont have a noreturn as a declaration specifier
4429 */
4430 #ifndef PERL_STATIC_NO_RET
4431 #  define PERL_STATIC_NO_RET STATIC
4432 #endif
4433
4434 /* PERL_STATIC_INLINE_NO_RET is supposed to be equivalent to PERL_STATIC_INLINE
4435  * on builds that dont have a noreturn as a declaration specifier
4436 */
4437 #ifndef PERL_STATIC_INLINE_NO_RET
4438 #  define PERL_STATIC_INLINE_NO_RET PERL_STATIC_INLINE
4439 #endif
4440
4441 #ifndef PERL_STATIC_FORCE_INLINE
4442 #  define PERL_STATIC_FORCE_INLINE PERL_STATIC_INLINE
4443 #endif
4444
4445 #ifndef PERL_STATIC_FORCE_INLINE_NO_RET
4446 #  define PERL_STATIC_FORCE_INLINE_NO_RET PERL_STATIC_INLINE
4447 #endif
4448
4449 #if !defined(OS2)
4450 #  include "iperlsys.h"
4451 #endif
4452
4453 #ifdef __LIBCATAMOUNT__
4454 #undef HAS_PASSWD  /* unixish.h but not unixish enough. */
4455 #undef HAS_GROUP
4456 #define FAKE_BIT_BUCKET
4457 #endif
4458
4459 /* [perl #22371] Algorithmic Complexity Attack on Perl 5.6.1, 5.8.0.
4460  * Note that the USE_HASH_SEED and similar defines are *NOT* defined by
4461  * Configure, despite their names being similar to other defines like
4462  * USE_ITHREADS.  Configure in fact knows nothing about the randomised
4463  * hashes.  Therefore to enable/disable the hash randomisation defines
4464  * use the Configure -Accflags=... instead. */
4465 #if !defined(NO_HASH_SEED) && !defined(USE_HASH_SEED)
4466 #  define USE_HASH_SEED
4467 #endif
4468
4469 #include "perly.h"
4470
4471
4472 /* macros to define bit-fields in structs. */
4473 #ifndef PERL_BITFIELD8
4474 #  ifdef HAS_NON_INT_BITFIELDS
4475 #  define PERL_BITFIELD8 U8
4476 #  else
4477 #    define PERL_BITFIELD8 unsigned
4478 #  endif
4479 #endif
4480 #ifndef PERL_BITFIELD16
4481 #  ifdef HAS_NON_INT_BITFIELDS
4482 #  define PERL_BITFIELD16 U16
4483 #  else
4484 #    define PERL_BITFIELD16 unsigned
4485 #  endif
4486 #endif
4487 #ifndef PERL_BITFIELD32
4488 #  ifdef HAS_NON_INT_BITFIELDS
4489 #  define PERL_BITFIELD32 U32
4490 #  else
4491 #    define PERL_BITFIELD32 unsigned
4492 #  endif
4493 #endif
4494
4495 #include "sv.h"
4496 #include "regexp.h"
4497 #include "util.h"
4498 #include "form.h"
4499 #include "gv.h"
4500 #include "pad.h"
4501 #include "cv.h"
4502 #include "opnames.h"
4503 #include "op.h"
4504 #include "hv.h"
4505 #include "cop.h"
4506 #include "av.h"
4507 #include "mg.h"
4508 #include "scope.h"
4509 #include "warnings.h"
4510 #include "utf8.h"
4511
4512 /* these would be in doio.h if there was such a file */
4513 #define my_stat()  my_stat_flags(SV_GMAGIC)
4514 #define my_lstat() my_lstat_flags(SV_GMAGIC)
4515
4516 /* defined in sv.c, but also used in [ach]v.c */
4517 #undef _XPV_HEAD
4518 #undef _XPVMG_HEAD
4519 #undef _XPVCV_COMMON
4520
4521 #include "parser.h"
4522
4523 typedef struct magic_state MGS; /* struct magic_state defined in mg.c */
4524
4525 #if defined(PERL_IN_REGEX_ENGINE) || defined(PERL_EXT_RE_BUILD)
4526
4527 /* These have to be predeclared, as they are used in proto.h which is #included
4528  * before their definitions in regcomp.h. */
4529
4530 struct scan_data_t;
4531 typedef struct regnode_charclass regnode_charclass;
4532
4533 /* A hopefully less confusing name.  The sub-classes are all Posix classes only
4534  * used under /l matching */
4535 typedef struct regnode_charclass_posixl regnode_charclass_class;
4536 typedef struct regnode_charclass_posixl regnode_charclass_posixl;
4537
4538 typedef struct regnode_ssc regnode_ssc;
4539 typedef struct RExC_state_t RExC_state_t;
4540 struct _reg_trie_data;
4541 typedef struct scan_data_t scan_data_t;
4542
4543 #endif
4544
4545 struct ptr_tbl_ent {
4546     struct ptr_tbl_ent*         next;
4547     const void*                 oldval;
4548     void*                       newval;
4549 };
4550
4551 struct ptr_tbl {
4552     struct ptr_tbl_ent**        tbl_ary;
4553     UV                          tbl_max;
4554     UV                          tbl_items;
4555     struct ptr_tbl_arena        *tbl_arena;
4556     struct ptr_tbl_ent          *tbl_arena_next;
4557     struct ptr_tbl_ent          *tbl_arena_end;
4558 };
4559
4560 #if defined(htonl) && !defined(HAS_HTONL)
4561 #define HAS_HTONL
4562 #endif
4563 #if defined(htons) && !defined(HAS_HTONS)
4564 #define HAS_HTONS
4565 #endif
4566 #if defined(ntohl) && !defined(HAS_NTOHL)
4567 #define HAS_NTOHL
4568 #endif
4569 #if defined(ntohs) && !defined(HAS_NTOHS)
4570 #define HAS_NTOHS
4571 #endif
4572 #ifndef HAS_HTONL
4573 #define HAS_HTONS
4574 #define HAS_HTONL
4575 #define HAS_NTOHS
4576 #define HAS_NTOHL
4577 #  if (BYTEORDER & 0xffff) == 0x4321
4578 /* Big endian system, so ntohl, ntohs, htonl and htons do not need to
4579    re-order their values. However, to behave identically to the alternative
4580    implementations, they should truncate to the correct size.  */
4581 #    define ntohl(x)    ((x)&0xFFFFFFFF)
4582 #    define htonl(x)    ntohl(x)
4583 #    define ntohs(x)    ((x)&0xFFFF)
4584 #    define htons(x)    ntohs(x)
4585 #  elif BYTEORDER == 0x1234 || BYTEORDER == 0x12345678
4586
4587 /* Note that we can't straight out declare our own htonl and htons because
4588    the Win32 build process forcibly undefines HAS_HTONL etc for its miniperl,
4589    to avoid the overhead of initialising the socket subsystem, but the headers
4590    that *declare* the various functions are still seen. If we declare our own
4591    htonl etc they will clash with the declarations in the Win32 headers.  */
4592
4593 PERL_STATIC_INLINE U32
4594 my_swap32(const U32 x) {
4595     return ((x & 0xFF) << 24) | ((x >> 24) & 0xFF)
4596         | ((x & 0x0000FF00) << 8) | ((x & 0x00FF0000) >> 8);
4597 }
4598
4599 PERL_STATIC_INLINE U16
4600 my_swap16(const U16 x) {
4601     return ((x & 0xFF) << 8) | ((x >> 8) & 0xFF);
4602 }
4603
4604 #    define htonl(x)    my_swap32(x)
4605 #    define ntohl(x)    my_swap32(x)
4606 #    define ntohs(x)    my_swap16(x)
4607 #    define htons(x)    my_swap16(x)
4608 #  else
4609 #    error "Unsupported byteorder"
4610 /* The C pre-processor doesn't let us return the value of BYTEORDER as part of
4611    the error message. Please check the value of the macro BYTEORDER, as defined
4612    in config.h. The values of BYTEORDER we expect are
4613
4614             big endian  little endian
4615    32 bit       0x4321  0x1234
4616    64 bit   0x87654321  0x12345678
4617
4618    If you have a system with a different byte order, please see
4619    pod/perlhack.pod for how to submit a patch to add supporting code.
4620 */
4621 #  endif
4622 #endif
4623
4624 /*
4625  * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
4626  * -DWS
4627  */
4628 #if BYTEORDER == 0x1234 || BYTEORDER == 0x12345678
4629 /* Little endian system, so vtohl, vtohs, htovl and htovs do not need to
4630    re-order their values. However, to behave identically to the alternative
4631    implementations, they should truncate to the correct size.  */
4632 #  define vtohl(x)      ((x)&0xFFFFFFFF)
4633 #  define vtohs(x)      ((x)&0xFFFF)
4634 #  define htovl(x)      vtohl(x)
4635 #  define htovs(x)      vtohs(x)
4636 #elif BYTEORDER == 0x4321 || BYTEORDER == 0x87654321
4637 #  define vtohl(x)      ((((x)&0xFF)<<24)       \
4638                         +(((x)>>24)&0xFF)       \
4639                         +(((x)&0x0000FF00)<<8)  \
4640                         +(((x)&0x00FF0000)>>8)  )
4641 #  define vtohs(x)      ((((x)&0xFF)<<8) + (((x)>>8)&0xFF))
4642 #  define htovl(x)      vtohl(x)
4643 #  define htovs(x)      vtohs(x)
4644 #else
4645 #  error "Unsupported byteorder"
4646 /* If you have need for current perl on PDP-11 or similar, and can help test
4647    that blead keeps working on a mixed-endian system, then see
4648    pod/perlhack.pod for how to submit patches to things working again.  */
4649 #endif
4650
4651 /* *MAX Plus 1. A floating point value.
4652    Hopefully expressed in a way that dodgy floating point can't mess up.
4653    >> 2 rather than 1, so that value is safely less than I32_MAX after 1
4654    is added to it
4655    May find that some broken compiler will want the value cast to I32.
4656    [after the shift, as signed >> may not be as secure as unsigned >>]
4657 */
4658 #define I32_MAX_P1 (2.0 * (1 + (((U32)I32_MAX) >> 1)))
4659 #define U32_MAX_P1 (4.0 * (1 + ((U32_MAX) >> 2)))
4660 /* For compilers that can't correctly cast NVs over 0x7FFFFFFF (or
4661    0x7FFFFFFFFFFFFFFF) to an unsigned integer. In the future, sizeof(UV)
4662    may be greater than sizeof(IV), so don't assume that half max UV is max IV.
4663 */
4664 #define U32_MAX_P1_HALF (2.0 * (1 + ((U32_MAX) >> 2)))
4665
4666 #define UV_MAX_P1 (4.0 * (1 + ((UV_MAX) >> 2)))
4667 #define IV_MAX_P1 (2.0 * (1 + (((UV)IV_MAX) >> 1)))
4668 #define UV_MAX_P1_HALF (2.0 * (1 + ((UV_MAX) >> 2)))
4669
4670 /* This may look like unnecessary jumping through hoops, but converting
4671    out of range floating point values to integers *is* undefined behaviour,
4672    and it is starting to bite.
4673
4674 =for apidoc_section $casting
4675 =for apidoc Am|I32|I_32|NV what
4676 Cast an NV to I32 while avoiding undefined C behavior
4677
4678 =for apidoc Am|U32|U_32|NV what
4679 Cast an NV to U32 while avoiding undefined C behavior
4680
4681 =for apidoc Am|IV|I_V|NV what
4682 Cast an NV to IV while avoiding undefined C behavior
4683
4684 =for apidoc Am|UV|U_V|NV what
4685 Cast an NV to UV while avoiding undefined C behavior
4686
4687 =cut
4688 */
4689 #ifndef CAST_INLINE
4690 #define I_32(what) (cast_i32((NV)(what)))
4691 #define U_32(what) (cast_ulong((NV)(what)))
4692 #define I_V(what) (cast_iv((NV)(what)))
4693 #define U_V(what) (cast_uv((NV)(what)))
4694 #else
4695 #define I_32(n) ((n) < I32_MAX_P1 ? ((n) < I32_MIN ? I32_MIN : (I32) (n)) \
4696                   : ((n) < U32_MAX_P1 ? (I32)(U32) (n) \
4697                      : ((n) > 0 ? (I32) U32_MAX : 0 /* NaN */)))
4698 #define U_32(n) ((n) < 0.0 ? ((n) < I32_MIN ? (UV) I32_MIN : (U32)(I32) (n)) \
4699                   : ((n) < U32_MAX_P1 ? (U32) (n) \
4700                      : ((n) > 0 ? U32_MAX : 0 /* NaN */)))
4701 #define I_V(n) (LIKELY((n) < IV_MAX_P1) ? (UNLIKELY((n) < IV_MIN) ? IV_MIN : (IV) (n)) \
4702                   : (LIKELY((n) < UV_MAX_P1) ? (IV)(UV) (n) \
4703                      : ((n) > 0 ? (IV)UV_MAX : 0 /* NaN */)))
4704 #define U_V(n) ((n) < 0.0 ? (UNLIKELY((n) < IV_MIN) ? (UV) IV_MIN : (UV)(IV) (n)) \
4705                   : (LIKELY((n) < UV_MAX_P1) ? (UV) (n) \
4706                      : ((n) > 0 ? UV_MAX : 0 /* NaN */)))
4707 #endif
4708
4709 #define U_S(what) ((U16)U_32(what))
4710 #define U_I(what) ((unsigned int)U_32(what))
4711 #define U_L(what) U_32(what)
4712
4713 /*
4714 =for apidoc_section $integer
4715 =for apidoc Amn|IV|IV_MAX
4716 The largest signed integer that fits in an IV on this platform.
4717
4718 =for apidoc Amn|IV|IV_MIN
4719 The negative signed integer furthest away from 0 that fits in an IV on this
4720 platform.
4721
4722 =for apidoc Amn|UV|UV_MAX
4723 The largest unsigned integer that fits in a UV on this platform.
4724
4725 =for apidoc Amn|UV|UV_MIN
4726 The smallest unsigned integer that fits in a UV on this platform.  It should
4727 equal zero.
4728
4729 =cut
4730 */
4731
4732 #ifdef HAS_SIGNBIT
4733 #  ifndef Perl_signbit
4734 #    define Perl_signbit signbit
4735 #  endif
4736 #endif
4737
4738 /* These do not care about the fractional part, only about the range. */
4739 #define NV_WITHIN_IV(nv) (I_V(nv) >= IV_MIN && I_V(nv) <= IV_MAX)
4740 #define NV_WITHIN_UV(nv) ((nv)>=0.0 && U_V(nv) >= UV_MIN && U_V(nv) <= UV_MAX)
4741
4742 /* Used with UV/IV arguments: */
4743                                         /* XXXX: need to speed it up */
4744 #define CLUMP_2UV(iv)   ((iv) < 0 ? 0 : (UV)(iv))
4745 #define CLUMP_2IV(uv)   ((uv) > (UV)IV_MAX ? IV_MAX : (IV)(uv))
4746
4747 #ifndef MAXSYSFD
4748 #   define MAXSYSFD 2
4749 #endif
4750
4751 #ifndef __cplusplus
4752 #if !defined(WIN32)
4753 Uid_t getuid (void);
4754 Uid_t geteuid (void);
4755 Gid_t getgid (void);
4756 Gid_t getegid (void);
4757 #endif
4758 #endif
4759
4760 #ifndef Perl_debug_log
4761 #  define Perl_debug_log        PerlIO_stderr()
4762 #endif
4763
4764 #ifndef Perl_error_log
4765 #  define Perl_error_log        (PL_stderrgv                    \
4766                                  && isGV(PL_stderrgv)           \
4767                                  && GvIOp(PL_stderrgv)          \
4768                                  && IoOFP(GvIOp(PL_stderrgv))   \
4769                                  ? IoOFP(GvIOp(PL_stderrgv))    \
4770                                  : PerlIO_stderr())
4771 #endif
4772
4773
4774 #define DEBUG_p_FLAG            0x00000001 /*      1 */
4775 #define DEBUG_s_FLAG            0x00000002 /*      2 */
4776 #define DEBUG_l_FLAG            0x00000004 /*      4 */
4777 #define DEBUG_t_FLAG            0x00000008 /*      8 */
4778 #define DEBUG_o_FLAG            0x00000010 /*     16 */
4779 #define DEBUG_c_FLAG            0x00000020 /*     32 */
4780 #define DEBUG_P_FLAG            0x00000040 /*     64 */
4781 #define DEBUG_m_FLAG            0x00000080 /*    128 */
4782 #define DEBUG_f_FLAG            0x00000100 /*    256 */
4783 #define DEBUG_r_FLAG            0x00000200 /*    512 */
4784 #define DEBUG_x_FLAG            0x00000400 /*   1024 */
4785 #define DEBUG_u_FLAG            0x00000800 /*   2048 */
4786 /* U is reserved for Unofficial, exploratory hacking */
4787 #define DEBUG_U_FLAG            0x00001000 /*   4096 */
4788 #define DEBUG_h_FLAG            0x00002000 /*   8192 */
4789 #define DEBUG_X_FLAG            0x00004000 /*  16384 */
4790 #define DEBUG_D_FLAG            0x00008000 /*  32768 */
4791 #define DEBUG_S_FLAG            0x00010000 /*  65536 */
4792 #define DEBUG_T_FLAG            0x00020000 /* 131072 */
4793 #define DEBUG_R_FLAG            0x00040000 /* 262144 */
4794 #define DEBUG_J_FLAG            0x00080000 /* 524288 */
4795 #define DEBUG_v_FLAG            0x00100000 /*1048576 */
4796 #define DEBUG_C_FLAG            0x00200000 /*2097152 */
4797 #define DEBUG_A_FLAG            0x00400000 /*4194304 */
4798 #define DEBUG_q_FLAG            0x00800000 /*8388608 */
4799 #define DEBUG_M_FLAG            0x01000000 /*16777216*/
4800 #define DEBUG_B_FLAG            0x02000000 /*33554432*/
4801 #define DEBUG_L_FLAG            0x04000000 /*67108864*/
4802 #define DEBUG_i_FLAG            0x08000000 /*134217728*/
4803 #define DEBUG_y_FLAG            0x10000000 /*268435456*/
4804 #define DEBUG_MASK              0x1FFFEFFF /* mask of all the standard flags */
4805
4806 #define DEBUG_DB_RECURSE_FLAG   0x40000000
4807 #define DEBUG_TOP_FLAG          0x80000000 /* -D was given --> PL_debug |= FLAG */
4808
4809 /* Both flags have to be set */
4810 #  define DEBUG_BOTH_FLAGS_TEST_(flag1, flag2)              \
4811             UNLIKELY((PL_debug & ((flag1)|(flag2)))         \
4812                               == ((flag1)|(flag2)))
4813
4814 #  define DEBUG_p_TEST_ UNLIKELY(PL_debug & DEBUG_p_FLAG)
4815 #  define DEBUG_s_TEST_ UNLIKELY(PL_debug & DEBUG_s_FLAG)
4816 #  define DEBUG_l_TEST_ UNLIKELY(PL_debug & DEBUG_l_FLAG)
4817 #  define DEBUG_t_TEST_ UNLIKELY(PL_debug & DEBUG_t_FLAG)
4818 #  define DEBUG_o_TEST_ UNLIKELY(PL_debug & DEBUG_o_FLAG)
4819 #  define DEBUG_c_TEST_ UNLIKELY(PL_debug & DEBUG_c_FLAG)
4820 #  define DEBUG_P_TEST_ UNLIKELY(PL_debug & DEBUG_P_FLAG)
4821 #  define DEBUG_m_TEST_ UNLIKELY(PL_debug & DEBUG_m_FLAG)
4822 #  define DEBUG_f_TEST_ UNLIKELY(PL_debug & DEBUG_f_FLAG)
4823 #  define DEBUG_r_TEST_ UNLIKELY(PL_debug & DEBUG_r_FLAG)
4824 #  define DEBUG_x_TEST_ UNLIKELY(PL_debug & DEBUG_x_FLAG)
4825 #  define DEBUG_u_TEST_ UNLIKELY(PL_debug & DEBUG_u_FLAG)
4826 #  define DEBUG_U_TEST_ UNLIKELY(PL_debug & DEBUG_U_FLAG)
4827 #  define DEBUG_h_TEST_ UNLIKELY(PL_debug & DEBUG_h_FLAG)
4828 #  define DEBUG_X_TEST_ UNLIKELY(PL_debug & DEBUG_X_FLAG)
4829 #  define DEBUG_D_TEST_ UNLIKELY(PL_debug & DEBUG_D_FLAG)
4830 #  define DEBUG_S_TEST_ UNLIKELY(PL_debug & DEBUG_S_FLAG)
4831 #  define DEBUG_T_TEST_ UNLIKELY(PL_debug & DEBUG_T_FLAG)
4832 #  define DEBUG_R_TEST_ UNLIKELY(PL_debug & DEBUG_R_FLAG)
4833 #  define DEBUG_J_TEST_ UNLIKELY(PL_debug & DEBUG_J_FLAG)
4834 #  define DEBUG_v_TEST_ UNLIKELY(PL_debug & DEBUG_v_FLAG)
4835 #  define DEBUG_C_TEST_ UNLIKELY(PL_debug & DEBUG_C_FLAG)
4836 #  define DEBUG_A_TEST_ UNLIKELY(PL_debug & DEBUG_A_FLAG)
4837 #  define DEBUG_q_TEST_ UNLIKELY(PL_debug & DEBUG_q_FLAG)
4838 #  define DEBUG_M_TEST_ UNLIKELY(PL_debug & DEBUG_M_FLAG)
4839 #  define DEBUG_B_TEST_ UNLIKELY(PL_debug & DEBUG_B_FLAG)
4840
4841 /* Locale initialization comes earlier than PL_debug gets set,
4842  * DEBUG_LOCALE_INITIALIZATION_, if defined, will be set early enough */
4843 #  ifndef DEBUG_LOCALE_INITIALIZATION_
4844 #    define DEBUG_LOCALE_INITIALIZATION_ 0
4845 #  endif
4846 #  define DEBUG_L_TEST_                                                 \
4847         (   UNLIKELY(DEBUG_LOCALE_INITIALIZATION_)                      \
4848          || UNLIKELY(PL_debug & DEBUG_L_FLAG))
4849 #  define DEBUG_Lv_TEST_                                                \
4850         (   UNLIKELY(DEBUG_LOCALE_INITIALIZATION_)                      \
4851          || UNLIKELY(DEBUG_BOTH_FLAGS_TEST_(DEBUG_L_FLAG, DEBUG_v_FLAG)))
4852 #  define DEBUG_i_TEST_ UNLIKELY(PL_debug & DEBUG_i_FLAG)
4853 #  define DEBUG_y_TEST_ UNLIKELY(PL_debug & DEBUG_y_FLAG)
4854 #  define DEBUG_Xv_TEST_ DEBUG_BOTH_FLAGS_TEST_(DEBUG_X_FLAG, DEBUG_v_FLAG)
4855 #  define DEBUG_Uv_TEST_ DEBUG_BOTH_FLAGS_TEST_(DEBUG_U_FLAG, DEBUG_v_FLAG)
4856 #  define DEBUG_Pv_TEST_ DEBUG_BOTH_FLAGS_TEST_(DEBUG_P_FLAG, DEBUG_v_FLAG)
4857 #  define DEBUG_yv_TEST_ DEBUG_BOTH_FLAGS_TEST_(DEBUG_y_FLAG, DEBUG_v_FLAG)
4858
4859 #ifdef DEBUGGING
4860
4861 #  define DEBUG_p_TEST DEBUG_p_TEST_
4862 #  define DEBUG_s_TEST DEBUG_s_TEST_
4863 #  define DEBUG_l_TEST DEBUG_l_TEST_
4864 #  define DEBUG_t_TEST DEBUG_t_TEST_
4865 #  define DEBUG_o_TEST DEBUG_o_TEST_
4866 #  define DEBUG_c_TEST DEBUG_c_TEST_
4867 #  define DEBUG_P_TEST DEBUG_P_TEST_
4868 #  define DEBUG_m_TEST DEBUG_m_TEST_
4869 #  define DEBUG_f_TEST DEBUG_f_TEST_
4870 #  define DEBUG_r_TEST DEBUG_r_TEST_
4871 #  define DEBUG_x_TEST DEBUG_x_TEST_
4872 #  define DEBUG_u_TEST DEBUG_u_TEST_
4873 #  define DEBUG_U_TEST DEBUG_U_TEST_
4874 #  define DEBUG_h_TEST DEBUG_h_TEST_
4875 #  define DEBUG_X_TEST DEBUG_X_TEST_
4876 #  define DEBUG_D_TEST DEBUG_D_TEST_
4877 #  define DEBUG_S_TEST DEBUG_S_TEST_
4878 #  define DEBUG_T_TEST DEBUG_T_TEST_
4879 #  define DEBUG_R_TEST DEBUG_R_TEST_
4880 #  define DEBUG_J_TEST DEBUG_J_TEST_
4881 #  define DEBUG_v_TEST DEBUG_v_TEST_
4882 #  define DEBUG_C_TEST DEBUG_C_TEST_
4883 #  define DEBUG_A_TEST DEBUG_A_TEST_
4884 #  define DEBUG_q_TEST DEBUG_q_TEST_
4885 #  define DEBUG_M_TEST DEBUG_M_TEST_
4886 #  define DEBUG_B_TEST DEBUG_B_TEST_
4887 #  define DEBUG_L_TEST DEBUG_L_TEST_
4888 #  define DEBUG_i_TEST DEBUG_i_TEST_
4889 #  define DEBUG_y_TEST DEBUG_y_TEST_
4890 #  define DEBUG_Xv_TEST DEBUG_Xv_TEST_
4891 #  define DEBUG_Uv_TEST DEBUG_Uv_TEST_
4892 #  define DEBUG_Pv_TEST DEBUG_Pv_TEST_
4893 #  define DEBUG_Lv_TEST DEBUG_Lv_TEST_
4894 #  define DEBUG_yv_TEST DEBUG_yv_TEST_
4895
4896 #  define PERL_DEB(a)                  a
4897 #  define PERL_DEB2(a,b)               a
4898 #  define PERL_DEBUG(a) if (PL_debug)  a
4899 #  define DEBUG_p(a) if (DEBUG_p_TEST) a
4900 #  define DEBUG_s(a) if (DEBUG_s_TEST) a
4901 #  define DEBUG_l(a) if (DEBUG_l_TEST) a
4902 #  define DEBUG_t(a) if (DEBUG_t_TEST) a
4903 #  define DEBUG_o(a) if (DEBUG_o_TEST) a
4904 #  define DEBUG_c(a) if (DEBUG_c_TEST) a
4905 #  define DEBUG_P(a) if (DEBUG_P_TEST) a
4906
4907      /* Temporarily turn off memory debugging in case the a
4908       * does memory allocation, either directly or indirectly. */
4909 #  define DEBUG_m(a)  \
4910     STMT_START {                                                        \
4911         if (PERL_GET_INTERP) {                                          \
4912                                 dTHX;                                   \
4913                                 if (DEBUG_m_TEST) {                     \
4914                                     PL_debug &= ~DEBUG_m_FLAG;          \
4915                                     a;                                  \
4916                                     PL_debug |= DEBUG_m_FLAG;           \
4917                                 }                                       \
4918                               }                                         \
4919     } STMT_END
4920
4921 /* These allow you to customize your debugging output  for specialized,
4922  * generally temporary ad-hoc purposes.  For example, if you need 'errno'
4923  * preserved, you can add definitions to these macros (either in this file for
4924  * the whole program, or before the #include "perl.h" in a particular .c file
4925  * you're trying to debug) and recompile:
4926  *
4927  * #define DEBUG_PRE_STMTS   dSAVE_ERRNO;
4928  * #define DEBUG_POST_STMTS  RESTORE_ERRNO;
4929  *
4930  * Other potential things include displaying timestamps, location information,
4931  * which thread, etc.  Here's an example with both errno and location info:
4932  *
4933  * #define DEBUG_PRE_STMTS   dSAVE_ERRNO;  \
4934  *              PerlIO_printf(Perl_debug_log, "%s:%d: ", __FILE__, __LINE__);
4935  * #define DEBUG_POST  RESTORE_ERRNO;
4936  *
4937  * All DEBUG statements in the compiled scope will have these extra statements
4938  * compiled in; they will be executed only for the DEBUG statements whose flags
4939  * are turned on.
4940  */
4941 #ifndef DEBUG_PRE_STMTS
4942 #  define DEBUG_PRE_STMTS
4943 #endif
4944 #ifndef DEBUG_POST_STMTS
4945 #  define DEBUG_POST_STMTS
4946 #endif
4947
4948 #  define DEBUG__(t, a)                                                 \
4949         STMT_START {                                                    \
4950             if (t) {                                                    \
4951                 DEBUG_PRE_STMTS a; DEBUG_POST_STMTS                     \
4952             }                                                           \
4953         } STMT_END
4954
4955 #  define DEBUG_f(a) DEBUG__(DEBUG_f_TEST, a)
4956
4957 /* For re_comp.c, re_exec.c, assume -Dr has been specified */
4958 #  ifdef PERL_EXT_RE_BUILD
4959 #    define DEBUG_r(a) STMT_START {                                     \
4960                             DEBUG_PRE_STMTS a; DEBUG_POST_STMTS         \
4961                        } STMT_END;
4962 #  else
4963 #    define DEBUG_r(a) DEBUG__(DEBUG_r_TEST, a)
4964 #  endif /* PERL_EXT_RE_BUILD */
4965
4966 #  define DEBUG_x(a) DEBUG__(DEBUG_x_TEST, a)
4967 #  define DEBUG_u(a) DEBUG__(DEBUG_u_TEST, a)
4968 #  define DEBUG_U(a) DEBUG__(DEBUG_U_TEST, a)
4969 #  define DEBUG_X(a) DEBUG__(DEBUG_X_TEST, a)
4970 #  define DEBUG_D(a) DEBUG__(DEBUG_D_TEST, a)
4971 #  define DEBUG_Xv(a) DEBUG__(DEBUG_Xv_TEST, a)
4972 #  define DEBUG_Uv(a) DEBUG__(DEBUG_Uv_TEST, a)
4973 #  define DEBUG_Pv(a) DEBUG__(DEBUG_Pv_TEST, a)
4974 #  define DEBUG_Lv(a) DEBUG__(DEBUG_Lv_TEST, a)
4975 #  define DEBUG_yv(a) DEBUG__(DEBUG_yv_TEST, a)
4976
4977 #  define DEBUG_S(a) DEBUG__(DEBUG_S_TEST, a)
4978 #  define DEBUG_T(a) DEBUG__(DEBUG_T_TEST, a)
4979 #  define DEBUG_R(a) DEBUG__(DEBUG_R_TEST, a)
4980 #  define DEBUG_v(a) DEBUG__(DEBUG_v_TEST, a)
4981 #  define DEBUG_C(a) DEBUG__(DEBUG_C_TEST, a)
4982 #  define DEBUG_A(a) DEBUG__(DEBUG_A_TEST, a)
4983 #  define DEBUG_q(a) DEBUG__(DEBUG_q_TEST, a)
4984 #  define DEBUG_M(a) DEBUG__(DEBUG_M_TEST, a)
4985 #  define DEBUG_B(a) DEBUG__(DEBUG_B_TEST, a)
4986 #  define DEBUG_L(a) DEBUG__(DEBUG_L_TEST, a)
4987 #  define DEBUG_i(a) DEBUG__(DEBUG_i_TEST, a)
4988 #  define DEBUG_y(a) DEBUG__(DEBUG_y_TEST, a)
4989
4990 #else /* ! DEBUGGING below */
4991
4992 #  define DEBUG_p_TEST (0)
4993 #  define DEBUG_s_TEST (0)
4994 #  define DEBUG_l_TEST (0)
4995 #  define DEBUG_t_TEST (0)
4996 #  define DEBUG_o_TEST (0)
4997 #  define DEBUG_c_TEST (0)
4998 #  define DEBUG_P_TEST (0)
4999 #  define DEBUG_m_TEST (0)
5000 #  define DEBUG_f_TEST (0)
5001 #  define DEBUG_r_TEST (0)
5002 #  define DEBUG_x_TEST (0)
5003 #  define DEBUG_u_TEST (0)
5004 #  define DEBUG_U_TEST (0)
5005 #  define DEBUG_h_TEST (0)
5006 #  define DEBUG_X_TEST (0)
5007 #  define DEBUG_D_TEST (0)
5008 #  define DEBUG_S_TEST (0)
5009 #  define DEBUG_T_TEST (0)
5010 #  define DEBUG_R_TEST (0)
5011 #  define DEBUG_J_TEST (0)
5012 #  define DEBUG_v_TEST (0)
5013 #  define DEBUG_C_TEST (0)
5014 #  define DEBUG_A_TEST (0)
5015 #  define DEBUG_q_TEST (0)
5016 #  define DEBUG_M_TEST (0)
5017 #  define DEBUG_B_TEST (0)
5018 #  define DEBUG_L_TEST (0)
5019 #  define DEBUG_i_TEST (0)
5020 #  define DEBUG_y_TEST (0)
5021 #  define DEBUG_Xv_TEST (0)
5022 #  define DEBUG_Uv_TEST (0)
5023 #  define DEBUG_Pv_TEST (0)
5024 #  define DEBUG_Lv_TEST (0)
5025 #  define DEBUG_yv_TEST (0)
5026
5027 #  define PERL_DEB(a)
5028 #  define PERL_DEB2(a,b)               b
5029 #  define PERL_DEBUG(a)
5030 #  define DEBUG_p(a)
5031 #  define DEBUG_s(a)
5032 #  define DEBUG_l(a)
5033 #  define DEBUG_t(a)
5034 #  define DEBUG_o(a)
5035 #  define DEBUG_c(a)
5036 #  define DEBUG_P(a)
5037 #  define DEBUG_m(a)
5038 #  define DEBUG_f(a)
5039 #  define DEBUG_r(a)
5040 #  define DEBUG_x(a)
5041 #  define DEBUG_u(a)
5042 #  define DEBUG_U(a)
5043 #  define DEBUG_X(a)
5044 #  define DEBUG_D(a)
5045 #  define DEBUG_S(a)
5046 #  define DEBUG_T(a)
5047 #  define DEBUG_R(a)
5048 #  define DEBUG_v(a)
5049 #  define DEBUG_C(a)
5050 #  define DEBUG_A(a)
5051 #  define DEBUG_q(a)
5052 #  define DEBUG_M(a)
5053 #  define DEBUG_B(a)
5054 #  define DEBUG_L(a)
5055 #  define DEBUG_i(a)
5056 #  define DEBUG_y(a)
5057 #  define DEBUG_Xv(a)
5058 #  define DEBUG_Uv(a)
5059 #  define DEBUG_Pv(a)
5060 #  define DEBUG_Lv(a)
5061 #  define DEBUG_yv(a)
5062 #endif /* DEBUGGING */
5063
5064
5065 #define DEBUG_SCOPE(where) \
5066     DEBUG_l( \
5067     Perl_deb(aTHX_ "%s scope %ld (savestack=%ld) at %s:%d\n",   \
5068                     where, (long)PL_scopestack_ix, (long)PL_savestack_ix, \
5069                     __FILE__, __LINE__));
5070
5071 /* Keep the old croak based assert for those who want it, and as a fallback if
5072    the platform is so heretically non-ANSI that it can't assert.  */
5073
5074 #define Perl_assert(what)       PERL_DEB2(                              \
5075         ((what) ? ((void) 0) :                                          \
5076             (Perl_croak_nocontext("Assertion %s failed: file \"" __FILE__ \
5077                         "\", line %d", STRINGIFY(what), __LINE__),      \
5078              (void) 0)), ((void)0))
5079
5080 /* assert() gets defined if DEBUGGING.
5081  * If no DEBUGGING, the <assert.h> has not been included. */
5082 #ifndef assert
5083 #  define assert(what)  Perl_assert(what)
5084 #endif
5085 #ifdef DEBUGGING
5086 #  define assert_(what) assert(what),
5087 #else
5088 #  define assert_(what)
5089 #endif
5090
5091 struct ufuncs {
5092     I32 (*uf_val)(pTHX_ IV, SV*);
5093     I32 (*uf_set)(pTHX_ IV, SV*);
5094     IV uf_index;
5095 };
5096
5097 /* In pre-5.7-Perls the PERL_MAGIC_uvar magic didn't get the thread context.
5098  * XS code wanting to be backward compatible can do something
5099  * like the following:
5100
5101 #ifndef PERL_MG_UFUNC
5102 #define PERL_MG_UFUNC(name,ix,sv) I32 name(IV ix, SV *sv)
5103 #endif
5104
5105 static PERL_MG_UFUNC(foo_get, index, val)
5106 {
5107     sv_setsv(val, ...);
5108     return TRUE;
5109 }
5110
5111 -- Doug MacEachern
5112
5113 */
5114
5115 #ifndef PERL_MG_UFUNC
5116 #define PERL_MG_UFUNC(name,ix,sv) I32 name(pTHX_ IV ix, SV *sv)
5117 #endif
5118
5119 #include <math.h>
5120 #ifdef __VMS
5121      /* isfinite and others are here rather than in math.h as C99 stipulates */
5122 #    include <fp.h>
5123 #endif
5124
5125 #ifndef __cplusplus
5126 #  if !defined(WIN32) && !defined(VMS)
5127 #ifndef crypt
5128 char *crypt (const char*, const char*);
5129 #endif
5130 #  endif /* !WIN32 */
5131 #  ifndef WIN32
5132 #    ifndef getlogin
5133 char *getlogin (void);
5134 #    endif
5135 #  endif /* !WIN32 */
5136 #endif /* !__cplusplus */
5137
5138 /* Fixme on VMS.  This needs to be a run-time, not build time options */
5139 /* Also rename() is affected by this */
5140 #ifdef UNLINK_ALL_VERSIONS /* Currently only makes sense for VMS */
5141 #define UNLINK unlnk
5142 I32 unlnk (pTHX_ const char*);
5143 #else
5144 #define UNLINK PerlLIO_unlink
5145 #endif
5146
5147 /* some versions of glibc are missing the setresuid() proto */
5148 #if defined(HAS_SETRESUID) && !defined(HAS_SETRESUID_PROTO)
5149 int setresuid(uid_t ruid, uid_t euid, uid_t suid);
5150 #endif
5151 /* some versions of glibc are missing the setresgid() proto */
5152 #if defined(HAS_SETRESGID) && !defined(HAS_SETRESGID_PROTO)
5153 int setresgid(gid_t rgid, gid_t egid, gid_t sgid);
5154 #endif
5155
5156 #ifndef HAS_SETREUID
5157 #  ifdef HAS_SETRESUID
5158 #    define setreuid(r,e) setresuid(r,e,(Uid_t)-1)
5159 #    define HAS_SETREUID
5160 #  endif
5161 #endif
5162 #ifndef HAS_SETREGID
5163 #  ifdef HAS_SETRESGID
5164 #    define setregid(r,e) setresgid(r,e,(Gid_t)-1)
5165 #    define HAS_SETREGID
5166 #  endif
5167 #endif
5168
5169 /* Sighandler_t defined in iperlsys.h */
5170
5171 #ifdef HAS_SIGACTION
5172 typedef struct sigaction Sigsave_t;
5173 #else
5174 typedef Sighandler_t Sigsave_t;
5175 #endif
5176
5177 #define SCAN_DEF 0
5178 #define SCAN_TR 1
5179 #define SCAN_REPL 2
5180
5181 #ifdef DEBUGGING
5182 # ifndef register
5183 #  define register
5184 # endif
5185 # define RUNOPS_DEFAULT Perl_runops_debug
5186 #else
5187 # define RUNOPS_DEFAULT Perl_runops_standard
5188 #endif
5189
5190 #if defined(USE_PERLIO)
5191 EXTERN_C void PerlIO_teardown(void);
5192 # ifdef USE_ITHREADS
5193 #  define PERLIO_INIT MUTEX_INIT(&PL_perlio_mutex)
5194 #  define PERLIO_TERM                           \
5195         STMT_START {                            \
5196                 PerlIO_teardown();              \
5197                 MUTEX_DESTROY(&PL_perlio_mutex);\
5198         } STMT_END
5199 # else
5200 #  define PERLIO_INIT
5201 #  define PERLIO_TERM   PerlIO_teardown()
5202 # endif
5203 #else
5204 #  define PERLIO_INIT
5205 #  define PERLIO_TERM
5206 #endif
5207
5208 #ifdef MYMALLOC
5209 #  ifdef MUTEX_INIT_CALLS_MALLOC
5210 #    define MALLOC_INIT                                 \
5211         STMT_START {                                    \
5212                 PL_malloc_mutex = NULL;                 \
5213                 MUTEX_INIT(&PL_malloc_mutex);           \
5214         } STMT_END
5215 #    define MALLOC_TERM                                 \
5216         STMT_START {                                    \
5217                 perl_mutex tmp = PL_malloc_mutex;       \
5218                 PL_malloc_mutex = NULL;                 \
5219                 MUTEX_DESTROY(&tmp);                    \
5220         } STMT_END
5221 #  else
5222 #    define MALLOC_INIT MUTEX_INIT(&PL_malloc_mutex)
5223 #    define MALLOC_TERM MUTEX_DESTROY(&PL_malloc_mutex)
5224 #  endif
5225 #else
5226 #  define MALLOC_INIT
5227 #  define MALLOC_TERM
5228 #endif
5229
5230 #if defined(MULTIPLICITY)
5231
5232 struct perl_memory_debug_header;
5233 struct perl_memory_debug_header {
5234   tTHX  interpreter;
5235 #  if defined(PERL_POISON) || defined(PERL_DEBUG_READONLY_COW)
5236   MEM_SIZE size;
5237 #  endif
5238   struct perl_memory_debug_header *prev;
5239   struct perl_memory_debug_header *next;
5240 #  ifdef PERL_DEBUG_READONLY_COW
5241   bool readonly;
5242 #  endif
5243 };
5244
5245 #elif defined(PERL_DEBUG_READONLY_COW)
5246
5247 struct perl_memory_debug_header;
5248 struct perl_memory_debug_header {
5249   MEM_SIZE size;
5250 };
5251
5252 #endif
5253
5254 #if defined (PERL_TRACK_MEMPOOL) || defined (PERL_DEBUG_READONLY_COW)
5255
5256 #  define PERL_MEMORY_DEBUG_HEADER_SIZE \
5257         (sizeof(struct perl_memory_debug_header) + \
5258         (MEM_ALIGNBYTES - sizeof(struct perl_memory_debug_header) \
5259          %MEM_ALIGNBYTES) % MEM_ALIGNBYTES)
5260
5261 #else
5262 #  define PERL_MEMORY_DEBUG_HEADER_SIZE 0
5263 #endif
5264
5265 #ifdef PERL_TRACK_MEMPOOL
5266 # ifdef PERL_DEBUG_READONLY_COW
5267 #  define INIT_TRACK_MEMPOOL(header, interp)                    \
5268         STMT_START {                                            \
5269                 (header).interpreter = (interp);                \
5270                 (header).prev = (header).next = &(header);      \
5271                 (header).readonly = 0;                          \
5272         } STMT_END
5273 # else
5274 #  define INIT_TRACK_MEMPOOL(header, interp)                    \
5275         STMT_START {                                            \
5276                 (header).interpreter = (interp);                \
5277                 (header).prev = (header).next = &(header);      \
5278         } STMT_END
5279 # endif
5280 # else
5281 #  define INIT_TRACK_MEMPOOL(header, interp)
5282 #endif
5283
5284 #ifdef I_MALLOCMALLOC
5285 /* Needed for malloc_size(), malloc_good_size() on some systems */
5286 #  include <malloc/malloc.h>
5287 #endif
5288
5289 #ifdef MYMALLOC
5290 #  define Perl_safesysmalloc_size(where)        Perl_malloced_size(where)
5291 #else
5292 #  if defined(HAS_MALLOC_SIZE) && !defined(PERL_DEBUG_READONLY_COW)
5293 #    ifdef PERL_TRACK_MEMPOOL
5294 #       define Perl_safesysmalloc_size(where)                   \
5295             (malloc_size(((char *)(where)) - PERL_MEMORY_DEBUG_HEADER_SIZE) - PERL_MEMORY_DEBUG_HEADER_SIZE)
5296 #    else
5297 #       define Perl_safesysmalloc_size(where) malloc_size(where)
5298 #    endif
5299 #  endif
5300 #  ifdef HAS_MALLOC_GOOD_SIZE
5301 #    ifdef PERL_TRACK_MEMPOOL
5302 #       define Perl_malloc_good_size(how_much)                  \
5303             (malloc_good_size((how_much) + PERL_MEMORY_DEBUG_HEADER_SIZE) - PERL_MEMORY_DEBUG_HEADER_SIZE)
5304 #    else
5305 #       define Perl_malloc_good_size(how_much) malloc_good_size(how_much)
5306 #    endif
5307 #  else
5308 /* Having this as the identity operation makes some code simpler.  */
5309 #       define Perl_malloc_good_size(how_much)  (how_much)
5310 #  endif
5311 #endif
5312
5313 typedef int (*runops_proc_t)(pTHX);
5314 typedef void (*share_proc_t) (pTHX_ SV *sv);
5315 typedef int  (*thrhook_proc_t) (pTHX);
5316 typedef OP* (*PPADDR_t[]) (pTHX);
5317 typedef bool (*destroyable_proc_t) (pTHX_ SV *sv);
5318 typedef void (*despatch_signals_proc_t) (pTHX);
5319
5320 #if defined(__DYNAMIC__) && defined(PERL_DARWIN) && defined(PERL_CORE)
5321 #  include <crt_externs.h>      /* for the env array */
5322 #  define environ (*_NSGetEnviron())
5323 #elif defined(USE_ENVIRON_ARRAY) && !defined(environ)
5324    /* VMS and some other platforms don't use the environ array */
5325 EXTERN_C char **environ;  /* environment variables supplied via exec */
5326 #endif
5327
5328 #define PERL_PATCHLEVEL_H_IMPLICIT
5329 #include "patchlevel.h"
5330 #undef PERL_PATCHLEVEL_H_IMPLICIT
5331
5332 #define PERL_VERSION_STRING     STRINGIFY(PERL_REVISION) "." \
5333                                 STRINGIFY(PERL_VERSION) "." \
5334                                 STRINGIFY(PERL_SUBVERSION)
5335
5336 #define PERL_API_VERSION_STRING STRINGIFY(PERL_API_REVISION) "." \
5337                                 STRINGIFY(PERL_API_VERSION) "." \
5338                                 STRINGIFY(PERL_API_SUBVERSION)
5339
5340 START_EXTERN_C
5341
5342 /* handy constants */
5343 EXTCONST char PL_warn_uninit[]
5344   INIT("Use of uninitialized value%s%s%s");
5345 EXTCONST char PL_warn_uninit_sv[]
5346   INIT("Use of uninitialized value%" SVf "%s%s");
5347 EXTCONST char PL_warn_nosemi[]
5348   INIT("Semicolon seems to be missing");
5349 EXTCONST char PL_warn_reserved[]
5350   INIT("Unquoted string \"%s\" may clash with future reserved word");
5351 EXTCONST char PL_warn_nl[]
5352   INIT("Unsuccessful %s on filename containing newline");
5353 EXTCONST char PL_no_wrongref[]
5354   INIT("Can't use %s ref as %s ref");
5355 /* The core no longer needs this here. If you require the string constant,
5356    please inline a copy into your own code.  */
5357 EXTCONST char PL_no_symref[] __attribute__deprecated__
5358   INIT("Can't use string (\"%.32s\") as %s ref while \"strict refs\" in use");
5359 EXTCONST char PL_no_symref_sv[]
5360   INIT("Can't use string (\"%" SVf32 "\"%s) as %s ref while \"strict refs\" in use");
5361
5362 EXTCONST char PL_no_usym[]
5363   INIT("Can't use an undefined value as %s reference");
5364 EXTCONST char PL_no_aelem[]
5365   INIT("Modification of non-creatable array value attempted, subscript %d");
5366 EXTCONST char PL_no_helem_sv[]
5367   INIT("Modification of non-creatable hash value attempted, subscript \"%" SVf "\"");
5368 EXTCONST char PL_no_modify[]
5369   INIT("Modification of a read-only value attempted");
5370 EXTCONST char PL_no_mem[sizeof("Out of memory!\n")]
5371   INIT("Out of memory!\n");
5372 EXTCONST char PL_no_security[]
5373   INIT("Insecure dependency in %s%s");
5374 EXTCONST char PL_no_sock_func[]
5375   INIT("Unsupported socket function \"%s\" called");
5376 EXTCONST char PL_no_dir_func[]
5377   INIT("Unsupported directory function \"%s\" called");
5378 EXTCONST char PL_no_func[]
5379   INIT("The %s function is unimplemented");
5380 EXTCONST char PL_no_myglob[]
5381   INIT("\"%s\" %s %s can't be in a package");
5382 EXTCONST char PL_no_localize_ref[]
5383   INIT("Can't localize through a reference");
5384 EXTCONST char PL_memory_wrap[]
5385   INIT("panic: memory wrap");
5386 EXTCONST char PL_extended_cp_format[]
5387   INIT("Code point 0x%" UVXf " is not Unicode, requires a Perl extension,"
5388                              " and so is not portable");
5389 EXTCONST char PL_Yes[]
5390   INIT("1");
5391 EXTCONST char PL_No[]
5392   INIT("");
5393 EXTCONST char PL_Zero[]
5394   INIT("0");
5395
5396 /*
5397 =for apidoc_section $numeric
5398 =for apidoc AmTuU|const char *|PL_hexdigit|U8 value
5399
5400 This array, indexed by an integer, converts that value into the character that
5401 represents it.  For example, if the input is 8, the return will be a string
5402 whose first character is '8'.  What is actually returned is a pointer into a
5403 string.  All you are interested in is the first character of that string.  To
5404 get uppercase letters (for the values 10..15), add 16 to the index.  Hence,
5405 C<PL_hexdigit[11]> is C<'b'>, and C<PL_hexdigit[11+16]> is C<'B'>.  Adding 16
5406 to an index whose representation is '0'..'9' yields the same as not adding 16.
5407 Indices outside the range 0..31 result in (bad) undedefined behavior.
5408
5409 =cut
5410 */
5411 EXTCONST char PL_hexdigit[]
5412   INIT("0123456789abcdef0123456789ABCDEF");
5413
5414 EXT char PL_WARN_ALL
5415   INIT(0);
5416 EXT char PL_WARN_NONE
5417   INIT(0);
5418
5419 /* This is constant on most architectures, a global on OS/2 */
5420 #ifndef OS2
5421 EXTCONST char PL_sh_path[]
5422   INIT(SH_PATH); /* full path of shell */
5423 #endif
5424
5425 #ifdef CSH
5426 EXTCONST char PL_cshname[]
5427   INIT(CSH);
5428 #  define PL_cshlen     (sizeof(CSH "") - 1)
5429 #endif
5430
5431 /* These are baked at compile time into any shared perl library.
5432    In future releases this will allow us in main() to sanity test the
5433    library we're linking against.  */
5434
5435 EXTCONST U8 PL_revision
5436   INIT(PERL_REVISION);
5437 EXTCONST U8 PL_version
5438   INIT(PERL_VERSION);
5439 EXTCONST U8 PL_subversion
5440   INIT(PERL_SUBVERSION);
5441
5442 EXTCONST char PL_uuemap[65]
5443   INIT("`!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_");
5444
5445 /* a special string address whose value is "isa", but which perl knows
5446  * to treat as if it were really "DOES" when printing the method name in
5447  *  the "Can't call method '%s'" error message */
5448 EXTCONST char PL_isa_DOES[]
5449   INIT("isa");
5450
5451 #ifdef DOINIT
5452 EXTCONST char PL_uudmap[256] =
5453 #  include "uudmap.h"
5454 ;
5455 EXTCONST char PL_bitcount[256] =
5456 #  include "bitcount.h"
5457 ;
5458 EXTCONST char* const PL_sig_name[] = { SIG_NAME };
5459 EXTCONST int         PL_sig_num[]  = { SIG_NUM };
5460 #else
5461 EXTCONST char PL_uudmap[256];
5462 EXTCONST char PL_bitcount[256];
5463 EXTCONST char* const PL_sig_name[];
5464 EXTCONST int         PL_sig_num[];
5465 #endif
5466
5467 /* fast conversion and case folding tables.  The folding tables complement the
5468  * fold, so that 'a' maps to 'A' and 'A' maps to 'a', ignoring more complicated
5469  * folds such as outside the range or to multiple characters. */
5470
5471 #ifdef DOINIT
5472 #  ifndef EBCDIC
5473
5474 /* The EBCDIC fold table depends on the code page, and hence is found in
5475  * ebcdic_tables.h */
5476
5477 EXTCONST  unsigned char PL_fold[] = {
5478         0,      1,      2,      3,      4,      5,      6,      7,
5479         8,      9,      10,     11,     12,     13,     14,     15,
5480         16,     17,     18,     19,     20,     21,     22,     23,
5481         24,     25,     26,     27,     28,     29,     30,     31,
5482         32,     33,     34,     35,     36,     37,     38,     39,
5483         40,     41,     42,     43,     44,     45,     46,     47,
5484         48,     49,     50,     51,     52,     53,     54,     55,
5485         56,     57,     58,     59,     60,     61,     62,     63,
5486         64,     'a',    'b',    'c',    'd',    'e',    'f',    'g',
5487         'h',    'i',    'j',    'k',    'l',    'm',    'n',    'o',
5488         'p',    'q',    'r',    's',    't',    'u',    'v',    'w',
5489         'x',    'y',    'z',    91,     92,     93,     94,     95,
5490         96,     'A',    'B',    'C',    'D',    'E',    'F',    'G',
5491         'H',    'I',    'J',    'K',    'L',    'M',    'N',    'O',
5492         'P',    'Q',    'R',    'S',    'T',    'U',    'V',    'W',
5493         'X',    'Y',    'Z',    123,    124,    125,    126,    127,
5494         128,    129,    130,    131,    132,    133,    134,    135,
5495         136,    137,    138,    139,    140,    141,    142,    143,
5496         144,    145,    146,    147,    148,    149,    150,    151,
5497         152,    153,    154,    155,    156,    157,    158,    159,
5498         160,    161,    162,    163,    164,    165,    166,    167,
5499         168,    169,    170,    171,    172,    173,    174,    175,
5500         176,    177,    178,    179,    180,    181,    182,    183,
5501         184,    185,    186,    187,    188,    189,    190,    191,
5502         192,    193,    194,    195,    196,    197,    198,    199,
5503         200,    201,    202,    203,    204,    205,    206,    207,
5504         208,    209,    210,    211,    212,    213,    214,    215,
5505         216,    217,    218,    219,    220,    221,    222,    223,
5506         224,    225,    226,    227,    228,    229,    230,    231,
5507         232,    233,    234,    235,    236,    237,    238,    239,
5508         240,    241,    242,    243,    244,    245,    246,    247,
5509         248,    249,    250,    251,    252,    253,    254,    255
5510 };
5511
5512 EXTCONST  unsigned char PL_fold_latin1[] = {
5513     /* Full latin1 complement folding, except for three problematic code points:
5514      *  Micro sign (181 = 0xB5) and y with diearesis (255 = 0xFF) have their
5515      *  fold complements outside the Latin1 range, so can't match something
5516      *  that isn't in utf8.
5517      *  German lower case sharp s (223 = 0xDF) folds to two characters, 'ss',
5518      *  not one, so can't be represented in this table.
5519      *
5520      * All have to be specially handled */
5521         0,      1,      2,      3,      4,      5,      6,      7,
5522         8,      9,      10,     11,     12,     13,     14,     15,
5523         16,     17,     18,     19,     20,     21,     22,     23,
5524         24,     25,     26,     27,     28,     29,     30,     31,
5525         32,     33,     34,     35,     36,     37,     38,     39,
5526         40,     41,     42,     43,     44,     45,     46,     47,
5527         48,     49,     50,     51,     52,     53,     54,     55,
5528         56,     57,     58,     59,     60,     61,     62,     63,
5529         64,     'a',    'b',    'c',    'd',    'e',    'f',    'g',
5530         'h',    'i',    'j',    'k',    'l',    'm',    'n',    'o',
5531         'p',    'q',    'r',    's',    't',    'u',    'v',    'w',
5532         'x',    'y',    'z',    91,     92,     93,     94,     95,
5533         96,     'A',    'B',    'C',    'D',    'E',    'F',    'G',
5534         'H',    'I',    'J',    'K',    'L',    'M',    'N',    'O',
5535         'P',    'Q',    'R',    'S',    'T',    'U',    'V',    'W',
5536         'X',    'Y',    'Z',    123,    124,    125,    126,    127,
5537         128,    129,    130,    131,    132,    133,    134,    135,
5538         136,    137,    138,    139,    140,    141,    142,    143,
5539         144,    145,    146,    147,    148,    149,    150,    151,
5540         152,    153,    154,    155,    156,    157,    158,    159,
5541         160,    161,    162,    163,    164,    165,    166,    167,
5542         168,    169,    170,    171,    172,    173,    174,    175,
5543         176,    177,    178,    179,    180,    181 /*micro */, 182,    183,
5544         184,    185,    186,    187,    188,    189,    190,    191,
5545         192+32, 193+32, 194+32, 195+32, 196+32, 197+32, 198+32, 199+32,
5546         200+32, 201+32, 202+32, 203+32, 204+32, 205+32, 206+32, 207+32,
5547         208+32, 209+32, 210+32, 211+32, 212+32, 213+32, 214+32, 215,
5548         216+32, 217+32, 218+32, 219+32, 220+32, 221+32, 222+32, 223 /* ss */,
5549         224-32, 225-32, 226-32, 227-32, 228-32, 229-32, 230-32, 231-32,
5550         232-32, 233-32, 234-32, 235-32, 236-32, 237-32, 238-32, 239-32,
5551         240-32, 241-32, 242-32, 243-32, 244-32, 245-32, 246-32, 247,
5552         248-32, 249-32, 250-32, 251-32, 252-32, 253-32, 254-32,
5553         255 /* y with diaeresis */
5554 };
5555
5556 /* If these tables are accessed through ebcdic, the access will be converted to
5557  * latin1 first */
5558 EXTCONST  unsigned char PL_latin1_lc[] = {  /* lowercasing */
5559         0,      1,      2,      3,      4,      5,      6,      7,
5560         8,      9,      10,     11,     12,     13,     14,     15,
5561         16,     17,     18,     19,     20,     21,     22,     23,
5562         24,     25,     26,     27,     28,     29,     30,     31,
5563         32,     33,     34,     35,     36,     37,     38,     39,
5564         40,     41,     42,     43,     44,     45,     46,     47,
5565         48,     49,     50,     51,     52,     53,     54,     55,
5566         56,     57,     58,     59,     60,     61,     62,     63,
5567         64,     'a',    'b',    'c',    'd',    'e',    'f',    'g',
5568         'h',    'i',    'j',    'k',    'l',    'm',    'n',    'o',
5569         'p',    'q',    'r',    's',    't',    'u',    'v',    'w',
5570         'x',    'y',    'z',    91,     92,     93,     94,     95,
5571         96,     97,     98,     99,     100,    101,    102,    103,
5572         104,    105,    106,    107,    108,    109,    110,    111,
5573         112,    113,    114,    115,    116,    117,    118,    119,
5574         120,    121,    122,    123,    124,    125,    126,    127,
5575         128,    129,    130,    131,    132,    133,    134,    135,
5576         136,    137,    138,    139,    140,    141,    142,    143,
5577         144,    145,    146,    147,    148,    149,    150,    151,
5578         152,    153,    154,    155,    156,    157,    158,    159,
5579         160,    161,    162,    163,    164,    165,    166,    167,
5580         168,    169,    170,    171,    172,    173,    174,    175,
5581         176,    177,    178,    179,    180,    181,    182,    183,
5582         184,    185,    186,    187,    188,    189,    190,    191,
5583         192+32, 193+32, 194+32, 195+32, 196+32, 197+32, 198+32, 199+32,
5584         200+32, 201+32, 202+32, 203+32, 204+32, 205+32, 206+32, 207+32,
5585         208+32, 209+32, 210+32, 211+32, 212+32, 213+32, 214+32, 215,
5586         216+32, 217+32, 218+32, 219+32, 220+32, 221+32, 222+32, 223,
5587         224,    225,    226,    227,    228,    229,    230,    231,
5588         232,    233,    234,    235,    236,    237,    238,    239,
5589         240,    241,    242,    243,    244,    245,    246,    247,
5590         248,    249,    250,    251,    252,    253,    254,    255
5591 };
5592
5593 /* upper and title case of latin1 characters, modified so that the three tricky
5594  * ones are mapped to 255 (which is one of the three) */
5595 EXTCONST  unsigned char PL_mod_latin1_uc[] = {
5596         0,      1,      2,      3,      4,      5,      6,      7,
5597         8,      9,      10,     11,     12,     13,     14,     15,
5598         16,     17,     18,     19,     20,     21,     22,     23,
5599         24,     25,     26,     27,     28,     29,     30,     31,
5600         32,     33,     34,     35,     36,     37,     38,     39,
5601         40,     41,     42,     43,     44,     45,     46,     47,
5602         48,     49,     50,     51,     52,     53,     54,     55,
5603         56,     57,     58,     59,     60,     61,     62,     63,
5604         64,     65,     66,     67,     68,     69,     70,     71,
5605         72,     73,     74,     75,     76,     77,     78,     79,
5606         80,     81,     82,     83,     84,     85,     86,     87,
5607         88,     89,     90,     91,     92,     93,     94,     95,
5608         96,     'A',    'B',    'C',    'D',    'E',    'F',    'G',
5609         'H',    'I',    'J',    'K',    'L',    'M',    'N',    'O',
5610         'P',    'Q',    'R',    'S',    'T',    'U',    'V',    'W',
5611         'X',    'Y',    'Z',    123,    124,    125,    126,    127,
5612         128,    129,    130,    131,    132,    133,    134,    135,
5613         136,    137,    138,    139,    140,    141,    142,    143,
5614         144,    145,    146,    147,    148,    149,    150,    151,
5615         152,    153,    154,    155,    156,    157,    158,    159,
5616         160,    161,    162,    163,    164,    165,    166,    167,
5617         168,    169,    170,    171,    172,    173,    174,    175,
5618         176,    177,    178,    179,    180,    255 /*micro*/,  182,    183,
5619         184,    185,    186,    187,    188,    189,    190,    191,
5620         192,    193,    194,    195,    196,    197,    198,    199,
5621         200,    201,    202,    203,    204,    205,    206,    207,
5622         208,    209,    210,    211,    212,    213,    214,    215,
5623         216,    217,    218,    219,    220,    221,    222,
5624 #    if    UNICODE_MAJOR_VERSION > 2                                        \
5625        || (UNICODE_MAJOR_VERSION == 2 && UNICODE_DOT_VERSION >= 1           \
5626                                       && UNICODE_DOT_DOT_VERSION >= 8)
5627                                                                 255 /*sharp s*/,
5628 #    else   /* uc(sharp s) is 'sharp s' itself in early unicode */
5629                                                                 223,
5630 #    endif
5631         224-32, 225-32, 226-32, 227-32, 228-32, 229-32, 230-32, 231-32,
5632         232-32, 233-32, 234-32, 235-32, 236-32, 237-32, 238-32, 239-32,
5633         240-32, 241-32, 242-32, 243-32, 244-32, 245-32, 246-32, 247,
5634         248-32, 249-32, 250-32, 251-32, 252-32, 253-32, 254-32, 255
5635 };
5636 #  endif  /* !EBCDIC, but still in DOINIT */
5637 #else   /* ! DOINIT */
5638 #  ifndef EBCDIC
5639 EXTCONST unsigned char PL_fold[];
5640 EXTCONST unsigned char PL_fold_latin1[];
5641 EXTCONST unsigned char PL_mod_latin1_uc[];
5642 EXTCONST unsigned char PL_latin1_lc[];
5643 #   endif
5644 #endif
5645
5646 /* Although only used for debugging, these constants must be available in
5647  * non-debugging builds too, since they're used in ext/re/re_exec.c,
5648  * which has DEBUGGING enabled always */
5649 #ifdef DOINIT
5650 EXTCONST char* const PL_block_type[] = {
5651         "NULL",
5652         "WHEN",
5653         "BLOCK",
5654         "GIVEN",
5655         "LOOP_ARY",
5656         "LOOP_LAZYSV",
5657         "LOOP_LAZYIV",
5658         "LOOP_LIST",
5659         "LOOP_PLAIN",
5660         "SUB",
5661         "FORMAT",
5662         "EVAL",
5663         "SUBST",
5664         "DEFER"
5665 };
5666 #else
5667 EXTCONST char* PL_block_type[];
5668 #endif
5669
5670 /* These are all the compile time options that affect binary compatibility.
5671    Other compile time options that are binary compatible are in perl.c
5672    (in S_Internals_V()). Both are combined for the output of perl -V
5673    However, this string will be embedded in any shared perl library, which will
5674    allow us add a comparison check in perlmain.c in the near future.  */
5675 #ifdef DOINIT
5676 EXTCONST char PL_bincompat_options[] =
5677 #  ifdef DEBUG_LEAKING_SCALARS
5678                              " DEBUG_LEAKING_SCALARS"
5679 #  endif
5680 #  ifdef DEBUG_LEAKING_SCALARS_FORK_DUMP
5681                              " DEBUG_LEAKING_SCALARS_FORK_DUMP"
5682 #  endif
5683 #  ifdef HAS_TIMES
5684                              " HAS_TIMES"
5685 #  endif
5686 #  ifdef HAVE_INTERP_INTERN
5687                              " HAVE_INTERP_INTERN"
5688 #  endif
5689 #  ifdef MULTIPLICITY
5690                              " MULTIPLICITY"
5691 #  endif
5692 #  ifdef MYMALLOC
5693                              " MYMALLOC"
5694 #  endif
5695 #  ifdef NO_HASH_SEED
5696                              " NO_HASH_SEED"
5697 #  endif
5698 #  ifdef PERLIO_LAYERS
5699                              " PERLIO_LAYERS"
5700 #  endif
5701 #  ifdef PERL_DEBUG_READONLY_COW
5702                              " PERL_DEBUG_READONLY_COW"
5703 #  endif
5704 #  ifdef PERL_DEBUG_READONLY_OPS
5705                              " PERL_DEBUG_READONLY_OPS"
5706 #  endif
5707 #  ifdef PERL_HASH_FUNC_DEFINE
5708 /* note that this is different from the others, PERL_HASH_FUNC_DEFINE
5709  * is a string which says which define was defined. */
5710                              " " PERL_HASH_FUNC_DEFINE
5711 #  endif
5712 #  ifdef PERL_HASH_USE_SBOX32
5713                              " PERL_HASH_USE_SBOX32"
5714 #  else
5715                              " PERL_HASH_NO_SBOX32"
5716 #  endif
5717 #  ifdef PERL_IMPLICIT_SYS
5718                              " PERL_IMPLICIT_SYS"
5719 #  endif
5720 #  ifdef PERL_POISON
5721                              " PERL_POISON"
5722 #  endif
5723 #  ifdef PERL_SAWAMPERSAND
5724                              " PERL_SAWAMPERSAND"
5725 #  endif
5726 #  ifdef PERL_TRACK_MEMPOOL
5727                              " PERL_TRACK_MEMPOOL"
5728 #  endif
5729 #  ifdef PERL_USES_PL_PIDSTATUS
5730                              " PERL_USES_PL_PIDSTATUS"
5731 #  endif
5732 #  ifdef USE_64_BIT_ALL
5733                              " USE_64_BIT_ALL"
5734 #  endif
5735 #  ifdef USE_64_BIT_INT
5736                              " USE_64_BIT_INT"
5737 #  endif
5738 #  ifdef USE_IEEE
5739                              " USE_IEEE"
5740 #  endif
5741 #  ifdef USE_ITHREADS
5742                              " USE_ITHREADS"
5743 #  endif
5744 #  ifdef USE_LARGE_FILES
5745                              " USE_LARGE_FILES"
5746 #  endif
5747 #  ifdef USE_LOCALE_COLLATE
5748                              " USE_LOCALE_COLLATE"
5749 #  endif
5750 #  ifdef USE_LOCALE_NUMERIC
5751                              " USE_LOCALE_NUMERIC"
5752 #  endif
5753 #  ifdef USE_LOCALE_TIME
5754                              " USE_LOCALE_TIME"
5755 #  endif
5756 #  ifdef USE_LONG_DOUBLE
5757                              " USE_LONG_DOUBLE"
5758 #  endif
5759 #  ifdef USE_PERLIO
5760                              " USE_PERLIO"
5761 #  endif
5762 #  ifdef USE_QUADMATH
5763                              " USE_QUADMATH"
5764 #  endif
5765 #  ifdef USE_REENTRANT_API
5766                              " USE_REENTRANT_API"
5767 #  endif
5768 #  ifdef USE_SOCKS
5769                              " USE_SOCKS"
5770 #  endif
5771 #  ifdef VMS_DO_SOCKETS
5772                              " VMS_DO_SOCKETS"
5773 #  endif
5774 #  ifdef VMS_SHORTEN_LONG_SYMBOLS
5775                              " VMS_SHORTEN_LONG_SYMBOLS"
5776 #  endif
5777 #  ifdef VMS_WE_ARE_CASE_SENSITIVE
5778                              " VMS_SYMBOL_CASE_AS_IS"
5779 #  endif
5780     ""; /* keep this on a line by itself, WITH the empty string */
5781 #else
5782 EXTCONST char PL_bincompat_options[];
5783 #endif
5784
5785 #ifndef PERL_SET_PHASE
5786 #  define PERL_SET_PHASE(new_phase) \
5787     PERL_DTRACE_PROBE_PHASE(new_phase); \
5788     PL_phase = new_phase;
5789 #endif
5790
5791 /* The interpreter phases. If these ever change, PL_phase_names right below will
5792  * need to be updated accordingly. */
5793 enum perl_phase {
5794     PERL_PHASE_CONSTRUCT        = 0,
5795     PERL_PHASE_START            = 1,
5796     PERL_PHASE_CHECK            = 2,
5797     PERL_PHASE_INIT             = 3,
5798     PERL_PHASE_RUN              = 4,
5799     PERL_PHASE_END              = 5,
5800     PERL_PHASE_DESTRUCT         = 6
5801 };
5802
5803 #ifdef DOINIT
5804 EXTCONST char *const PL_phase_names[] = {
5805     "CONSTRUCT",
5806     "START",
5807     "CHECK",
5808     "INIT",
5809     "RUN",
5810     "END",
5811     "DESTRUCT"
5812 };
5813 #else
5814 EXTCONST char *const PL_phase_names[];
5815 #endif
5816
5817 /*
5818 =for apidoc_section $utility
5819
5820 =for apidoc phase_name
5821
5822 Returns the given phase's name as a NUL-terminated string.
5823
5824 For example, to print a stack trace that includes the current
5825 interpreter phase you might do:
5826
5827     const char* phase_name = phase_name(PL_phase);
5828     mess("This is weird. (Perl phase: %s)", phase_name);
5829
5830 =cut
5831 */
5832
5833 #define phase_name(phase) (PL_phase_names[phase])
5834
5835 #ifndef PERL_CORE
5836 /* Do not use this macro. It only exists for extensions that rely on PL_dirty
5837  * instead of using the newer PL_phase, which provides everything PL_dirty
5838  * provided, and more. */
5839 #  define PL_dirty cBOOL(PL_phase == PERL_PHASE_DESTRUCT)
5840
5841 #  define PL_amagic_generation PL_na
5842 #  define PL_encoding ((SV *)NULL)
5843 #endif /* !PERL_CORE */
5844
5845 #define PL_hints PL_compiling.cop_hints
5846 #define PL_maxo  MAXO
5847
5848 END_EXTERN_C
5849
5850 /*****************************************************************************/
5851 /* This lexer/parser stuff is currently global since yacc is hard to reenter */
5852 /*****************************************************************************/
5853 /* XXX This needs to be revisited, since BEGIN makes yacc re-enter... */
5854
5855 #ifdef __Lynx__
5856 /* LynxOS defines these in scsi.h which is included via ioctl.h */
5857 #ifdef FORMAT
5858 #undef FORMAT
5859 #endif
5860 #ifdef SPACE
5861 #undef SPACE
5862 #endif
5863 #endif
5864
5865 #define LEX_NOTPARSING          11      /* borrowed from toke.c */
5866
5867 typedef enum {
5868     XOPERATOR,
5869     XTERM,
5870     XREF,
5871     XSTATE,
5872     XBLOCK,
5873     XATTRBLOCK, /* next token should be an attribute or block */
5874     XATTRTERM,  /* next token should be an attribute, or block in a term */
5875     XTERMBLOCK,
5876     XBLOCKTERM,
5877     XPOSTDEREF,
5878     XTERMORDORDOR /* evil hack */
5879     /* update exp_name[] in toke.c if adding to this enum */
5880 } expectation;
5881
5882 #define KEY_sigvar 0xFFFF /* fake keyword representing a signature var */
5883
5884 /* Hints are now stored in a dedicated U32, so the bottom 8 bits are no longer
5885    special and there is no need for HINT_PRIVATE_MASK for COPs.
5886
5887     NOTE: The typical module using these has the bit value hard-coded, so don't
5888     blindly change the values of these.
5889
5890    If we run out of bits, the 2 locale ones could be combined.  The PARTIAL one
5891    is for "use locale 'FOO'" which excludes some categories.  It requires going
5892    to %^H to find out which are in and which are out.  This could be extended
5893    for the normal case of a plain HINT_LOCALE, so that %^H would be used for
5894    any locale form. */
5895 #define HINT_INTEGER            0x00000001 /* integer pragma */
5896 #define HINT_STRICT_REFS        0x00000002 /* strict pragma */
5897 #define HINT_LOCALE             0x00000004 /* locale pragma */
5898 #define HINT_BYTES              0x00000008 /* bytes pragma */
5899 #define HINT_LOCALE_PARTIAL     0x00000010 /* locale, but a subset of categories */
5900
5901 #define HINT_EXPLICIT_STRICT_REFS       0x00000020 /* strict.pm */
5902 #define HINT_EXPLICIT_STRICT_SUBS       0x00000040 /* strict.pm */
5903 #define HINT_EXPLICIT_STRICT_VARS       0x00000080 /* strict.pm */
5904
5905 #define HINT_BLOCK_SCOPE        0x00000100
5906 #define HINT_STRICT_SUBS        0x00000200 /* strict pragma */
5907 #define HINT_STRICT_VARS        0x00000400 /* strict pragma */
5908 #define HINT_UNI_8_BIT          0x00000800 /* unicode_strings feature */
5909
5910 /* The HINT_NEW_* constants are used by the overload pragma */
5911 #define HINT_NEW_INTEGER        0x00001000
5912 #define HINT_NEW_FLOAT          0x00002000
5913 #define HINT_NEW_BINARY         0x00004000
5914 #define HINT_NEW_STRING         0x00008000
5915 #define HINT_NEW_RE             0x00010000
5916 #define HINT_LOCALIZE_HH        0x00020000 /* %^H needs to be copied */
5917 #define HINT_LEXICAL_IO_IN      0x00040000 /* ${^OPEN} is set for input */
5918 #define HINT_LEXICAL_IO_OUT     0x00080000 /* ${^OPEN} is set for output */
5919
5920 #define HINT_RE_TAINT           0x00100000 /* re pragma */
5921 #define HINT_RE_EVAL            0x00200000 /* re pragma */
5922
5923 #define HINT_FILETEST_ACCESS    0x00400000 /* filetest pragma */
5924 #define HINT_UTF8               0x00800000 /* utf8 pragma */
5925
5926 #define HINT_NO_AMAGIC          0x01000000 /* overloading pragma */
5927
5928 #define HINT_RE_FLAGS           0x02000000 /* re '/xism' pragma */
5929
5930 #define HINT_FEATURE_MASK       0x3c000000 /* 4 bits for feature bundles */
5931
5932                                 /* Note: Used for HINT_M_VMSISH_*,
5933                                    currently defined by vms/vmsish.h:
5934                                 0x40000000
5935                                 0x80000000
5936                                  */
5937
5938 #define HINT_ALL_STRICT       HINT_STRICT_REFS \
5939                             | HINT_STRICT_SUBS \
5940                             | HINT_STRICT_VARS
5941
5942 #ifdef USE_STRICT_BY_DEFAULT
5943 #define HINTS_DEFAULT            HINT_ALL_STRICT
5944 #else
5945 #define HINTS_DEFAULT            0
5946 #endif
5947
5948 /* flags for PL_sawampersand */
5949
5950 #define SAWAMPERSAND_LEFT       1   /* saw $` */
5951 #define SAWAMPERSAND_MIDDLE     2   /* saw $& */
5952 #define SAWAMPERSAND_RIGHT      4   /* saw $' */
5953
5954 #ifndef PERL_SAWAMPERSAND
5955 # define PL_sawampersand \
5956         (SAWAMPERSAND_LEFT|SAWAMPERSAND_MIDDLE|SAWAMPERSAND_RIGHT)
5957 #endif
5958
5959 /* Used for debugvar magic */
5960 #define DBVARMG_SINGLE  0
5961 #define DBVARMG_TRACE   1
5962 #define DBVARMG_SIGNAL  2
5963 #define DBVARMG_COUNT   3
5964
5965 #define PL_DBsingle_iv  (PL_DBcontrol[DBVARMG_SINGLE])
5966 #define PL_DBtrace_iv   (PL_DBcontrol[DBVARMG_TRACE])
5967 #define PL_DBsignal_iv  (PL_DBcontrol[DBVARMG_SIGNAL])
5968
5969 /* Various states of the input record separator SV (rs) */
5970 #define RsSNARF(sv)   (! SvOK(sv))
5971 #define RsSIMPLE(sv)  (SvOK(sv) && (! SvPOK(sv) || SvCUR(sv)))
5972 #define RsPARA(sv)    (SvPOK(sv) && ! SvCUR(sv))
5973 #define RsRECORD(sv)  (SvROK(sv) && (SvIV(SvRV(sv)) > 0))
5974
5975 /* A struct for keeping various DEBUGGING related stuff,
5976  * neatly packed.  Currently only scratch variables for
5977  * constructing debug output are included.  Needed always,
5978  * not just when DEBUGGING, though, because of the re extension. c*/
5979 struct perl_debug_pad {
5980   SV pad[3];
5981 };
5982
5983 #define PERL_DEBUG_PAD(i)       &(PL_debug_pad.pad[i])
5984 #define PERL_DEBUG_PAD_ZERO(i)  (SvPVX(PERL_DEBUG_PAD(i))[0] = 0, \
5985         (((XPV*) SvANY(PERL_DEBUG_PAD(i)))->xpv_cur = 0), \
5986         PERL_DEBUG_PAD(i))
5987
5988 /* Enable variables which are pointers to functions */
5989 typedef void (*peep_t)(pTHX_ OP* o);
5990 typedef regexp* (*regcomp_t) (pTHX_ char* exp, char* xend, PMOP* pm);
5991 typedef I32     (*regexec_t) (pTHX_ regexp* prog, char* stringarg,
5992                                       char* strend, char* strbeg, I32 minend,
5993                                       SV* screamer, void* data, U32 flags);
5994 typedef char*   (*re_intuit_start_t) (pTHX_ regexp *prog, SV *sv,
5995                                                 char *strpos, char *strend,
5996                                                 U32 flags,
5997                                                 re_scream_pos_data *d);
5998 typedef SV*     (*re_intuit_string_t) (pTHX_ regexp *prog);
5999 typedef void    (*regfree_t) (pTHX_ struct regexp* r);
6000 typedef regexp* (*regdupe_t) (pTHX_ const regexp* r, CLONE_PARAMS *param);
6001 typedef I32     (*re_fold_t)(pTHX_ const char *, char const *, I32);
6002
6003 typedef void (*DESTRUCTORFUNC_NOCONTEXT_t) (void*);
6004 typedef void (*DESTRUCTORFUNC_t) (pTHX_ void*);
6005 typedef void (*SVFUNC_t) (pTHX_ SV* const);
6006 typedef I32  (*SVCOMPARE_t) (pTHX_ SV* const, SV* const);
6007 typedef void (*XSINIT_t) (pTHX);
6008 typedef void (*ATEXIT_t) (pTHX_ void*);
6009 typedef void (*XSUBADDR_t) (pTHX_ CV *);
6010
6011 enum Perl_custom_infix_precedence {
6012     /* These numbers are spaced out to give room to insert new values as
6013      * required. They form part of the ABI contract with XS::Parse::Infix so
6014      * they should not be changed within a stable release cycle, but they can
6015      * be freely altered during a development cycle because no ABI guarantees
6016      * are made at that time */
6017     INFIX_PREC_LOW             =  10, /* non-associative */
6018     INFIX_PREC_LOGICAL_OR_LOW  =  30, /* left-associative, as `or` */
6019     INFIX_PREC_LOGICAL_AND_LOW =  40, /* left-associative, as `and` */
6020     INFIX_PREC_ASSIGN          =  50, /* right-associative, as `=` */
6021     INFIX_PREC_LOGICAL_OR      =  70, /* left-associative, as `||` */
6022     INFIX_PREC_LOGICAL_AND     =  80, /* left-associative, as `&&` */
6023     INFIX_PREC_REL             =  90, /* non-associative, just below `==` */
6024     INFIX_PREC_ADD             = 110, /* left-associative, as `+` */
6025     INFIX_PREC_MUL             = 130, /* left-associative, as `*` */
6026     INFIX_PREC_POW             = 150, /* right-associative, as `**` */
6027     INFIX_PREC_HIGH            = 170, /* non-associative */
6028     /* Try to keep within the range of a U8 in case we need to split the field
6029      * and add flags */
6030 };
6031 struct Perl_custom_infix;
6032 struct Perl_custom_infix {
6033     enum Perl_custom_infix_precedence prec;
6034     void (*parse)(pTHX_ SV **opdata, struct Perl_custom_infix *);  /* optional */
6035     OP *(*build_op)(pTHX_ SV **opdata, OP *lhs, OP *rhs, struct Perl_custom_infix *);
6036 };
6037
6038 typedef OP* (*Perl_ppaddr_t)(pTHX);
6039 typedef OP* (*Perl_check_t) (pTHX_ OP*);
6040 typedef void(*Perl_ophook_t)(pTHX_ OP*);
6041 typedef int (*Perl_keyword_plugin_t)(pTHX_ char*, STRLEN, OP**);
6042 typedef STRLEN (*Perl_infix_plugin_t)(pTHX_ char*, STRLEN, struct Perl_custom_infix **);
6043 typedef void(*Perl_cpeep_t)(pTHX_ OP *, OP *);
6044
6045 typedef void(*globhook_t)(pTHX);
6046
6047 #define KEYWORD_PLUGIN_DECLINE 0
6048 #define KEYWORD_PLUGIN_STMT    1
6049 #define KEYWORD_PLUGIN_EXPR    2
6050
6051 /* Interpreter exitlist entry */
6052 typedef struct exitlistentry {
6053     void (*fn) (pTHX_ void*);
6054     void *ptr;
6055 } PerlExitListEntry;
6056
6057 /* if you only have signal() and it resets on each signal, FAKE_PERSISTENT_SIGNAL_HANDLERS fixes */
6058 /* These have to be before perlvars.h */
6059 #if !defined(HAS_SIGACTION) && defined(VMS)
6060 #  define  FAKE_PERSISTENT_SIGNAL_HANDLERS
6061 #endif
6062 /* if we're doing kill() with sys$sigprc on VMS, FAKE_DEFAULT_SIGNAL_HANDLERS */
6063 #if defined(KILL_BY_SIGPRC)
6064 #  define  FAKE_DEFAULT_SIGNAL_HANDLERS
6065 #endif
6066
6067 #if !defined(MULTIPLICITY)
6068
6069 struct interpreter {
6070     char broiled;
6071 };
6072
6073 #else
6074
6075 /* If we have multiple interpreters define a struct
6076    holding variables which must be per-interpreter
6077    If we don't have threads anything that would have
6078    be per-thread is per-interpreter.
6079 */
6080
6081 /* Set up PERLVAR macros for populating structs */
6082 #  define PERLVAR(prefix,var,type) type prefix##var;
6083
6084 /* 'var' is an array of length 'n' */
6085 #  define PERLVARA(prefix,var,n,type) type prefix##var[n];
6086
6087 /* initialize 'var' to init' */
6088 #  define PERLVARI(prefix,var,type,init) type prefix##var;
6089
6090 /* like PERLVARI, but make 'var' a const */
6091 #  define PERLVARIC(prefix,var,type,init) type prefix##var;
6092
6093 struct interpreter {
6094 #  include "intrpvar.h"
6095 };
6096
6097 EXTCONST U16 PL_interp_size
6098   INIT(sizeof(struct interpreter));
6099
6100 #  define PERL_INTERPRETER_SIZE_UPTO_MEMBER(member)                     \
6101     STRUCT_OFFSET(struct interpreter, member) +                         \
6102     sizeof(((struct interpreter*)0)->member)
6103
6104 /* This will be useful for subsequent releases, because this has to be the
6105    same in your libperl as in main(), else you have a mismatch and must abort.
6106 */
6107 EXTCONST U16 PL_interp_size_5_18_0
6108   INIT(PERL_INTERPRETER_SIZE_UPTO_MEMBER(PERL_LAST_5_18_0_INTERP_MEMBER));
6109
6110
6111 /* Done with PERLVAR macros for now ... */
6112 #  undef PERLVAR
6113 #  undef PERLVARA
6114 #  undef PERLVARI
6115 #  undef PERLVARIC
6116
6117 #endif /* MULTIPLICITY */
6118
6119 struct tempsym; /* defined in pp_pack.c */
6120
6121 #include "thread.h"
6122 #include "pp.h"
6123
6124 #undef PERL_CKDEF
6125 #undef PERL_PPDEF
6126 #define PERL_CKDEF(s)   PERL_CALLCONV OP *s (pTHX_ OP *o);
6127 #define PERL_PPDEF(s)   PERL_CALLCONV OP *s (pTHX);
6128
6129 #ifdef MYMALLOC
6130 #  include "malloc_ctl.h"
6131 #endif
6132
6133 /*
6134  * This provides a layer of functions and macros to ensure extensions will
6135  * get to use the same RTL functions as the core.
6136  */
6137 #if defined(WIN32)
6138 #  include "win32iop.h"
6139 #endif
6140
6141
6142 #include "proto.h"
6143
6144 /* this has structure inits, so it cannot be included before here */
6145 #include "opcode.h"
6146
6147 /* The following must follow proto.h as #defines mess up syntax */
6148
6149 #if !defined(PERL_FOR_X2P)
6150 #  include "embedvar.h"
6151 #endif
6152
6153 /* Now include all the 'global' variables
6154  * If we don't have threads or multiple interpreters
6155  * these include variables that would have been their struct-s
6156  */
6157
6158 #define PERLVAR(prefix,var,type) EXT type PL_##var;
6159 #define PERLVARA(prefix,var,n,type) EXT type PL_##var[n];
6160 #define PERLVARI(prefix,var,type,init) EXT type  PL_##var INIT(init);
6161 #define PERLVARIC(prefix,var,type,init) EXTCONST type PL_##var INIT(init);
6162
6163 #if !defined(MULTIPLICITY)
6164 START_EXTERN_C
6165 #  include "intrpvar.h"
6166 END_EXTERN_C
6167 #  define PL_sv_yes   (PL_sv_immortals[0])
6168 #  define PL_sv_undef (PL_sv_immortals[1])
6169 #  define PL_sv_no    (PL_sv_immortals[2])
6170 #  define PL_sv_zero  (PL_sv_immortals[3])
6171 #endif
6172
6173 #ifdef PERL_CORE
6174 /* All core uses now exterminated. Ensure no zombies can return:  */
6175 #  undef PL_na
6176 #endif
6177
6178 /* Now all the config stuff is setup we can include embed.h
6179    In particular, need the relevant *ish file included already, as it may
6180    define HAVE_INTERP_INTERN  */
6181 #include "embed.h"
6182
6183 START_EXTERN_C
6184
6185 #  include "perlvars.h"
6186
6187 END_EXTERN_C
6188
6189 #undef PERLVAR
6190 #undef PERLVARA
6191 #undef PERLVARI
6192 #undef PERLVARIC
6193
6194 #if !defined(MULTIPLICITY)
6195 /* Set up PERLVAR macros for populating structs */
6196 #  define PERLVAR(prefix,var,type) type prefix##var;
6197 /* 'var' is an array of length 'n' */
6198 #  define PERLVARA(prefix,var,n,type) type prefix##var[n];
6199 /* initialize 'var' to init' */
6200 #  define PERLVARI(prefix,var,type,init) type prefix##var;
6201 /* like PERLVARI, but make 'var' a const */
6202 #  define PERLVARIC(prefix,var,type,init) type prefix##var;
6203
6204 /* this is never instantiated, is it just used for sizeof(struct PerlHandShakeInterpreter) */
6205 struct PerlHandShakeInterpreter {
6206 #  include "intrpvar.h"
6207 };
6208 #  undef PERLVAR
6209 #  undef PERLVARA
6210 #  undef PERLVARI
6211 #  undef PERLVARIC
6212 #endif
6213
6214 START_EXTERN_C
6215
6216 /* dummy variables that hold pointers to both runops functions, thus forcing
6217  * them *both* to get linked in (useful for Peek.xs, debugging etc) */
6218
6219 EXTCONST runops_proc_t PL_runops_std
6220   INIT(Perl_runops_standard);
6221 EXTCONST runops_proc_t PL_runops_dbg
6222   INIT(Perl_runops_debug);
6223
6224 #define EXT_MGVTBL EXTCONST MGVTBL
6225
6226 #define PERL_MAGIC_READONLY_ACCEPTABLE 0x40
6227 #define PERL_MAGIC_VALUE_MAGIC 0x80
6228 #define PERL_MAGIC_VTABLE_MASK 0x3F
6229
6230 /* can this type of magic be attached to a readonly SV? */
6231 #define PERL_MAGIC_TYPE_READONLY_ACCEPTABLE(t) \
6232     (PL_magic_data[(U8)(t)] & PERL_MAGIC_READONLY_ACCEPTABLE)
6233
6234 /* Is this type of magic container magic (%ENV, $1 etc),
6235  * or value magic (pos, taint etc)?
6236  */
6237 #define PERL_MAGIC_TYPE_IS_VALUE_MAGIC(t) \
6238     (PL_magic_data[(U8)(t)] & PERL_MAGIC_VALUE_MAGIC)
6239
6240 #include "mg_vtable.h"
6241
6242 #ifdef DOINIT
6243 EXTCONST U8 PL_magic_data[256] =
6244 #  include "mg_data.h"
6245 ;
6246 #else
6247 EXTCONST U8 PL_magic_data[256];
6248 #endif
6249
6250 #ifdef DOINIT
6251                         /* NL IV NV PV INV PI PN MG RX GV LV AV HV CV FM IO OBJ */
6252 EXTCONST bool
6253 PL_valid_types_IVX[]    = { 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0 };
6254 EXTCONST bool
6255 PL_valid_types_NVX[]    = { 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0 };
6256 EXTCONST bool
6257 PL_valid_types_PVX[]    = { 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0 };
6258 EXTCONST bool
6259 PL_valid_types_RV[]     = { 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0 };
6260 EXTCONST bool
6261 PL_valid_types_IV_set[] = { 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0 };
6262 EXTCONST bool
6263 PL_valid_types_NV_set[] = { 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0 };
6264
6265 EXTCONST U8
6266 PL_deBruijn_bitpos_tab32[] = {
6267     /* https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogDeBruijn */
6268     0,   1, 28,  2, 29, 14, 24,  3, 30, 22, 20, 15, 25, 17,  4,  8,
6269     31, 27, 13, 23, 21, 19, 16,  7, 26, 12, 18,  6, 11,  5, 10,  9
6270 };
6271
6272 EXTCONST U8
6273 PL_deBruijn_bitpos_tab64[] = {
6274     /* https://stackoverflow.com/questions/11376288/fast-computing-of-log2-for-64-bit-integers */
6275     63,  0, 58,  1, 59, 47, 53,  2, 60, 39, 48, 27, 54, 33, 42,  3,
6276     61, 51, 37, 40, 49, 18, 28, 20, 55, 30, 34, 11, 43, 14, 22,  4,
6277     62, 57, 46, 52, 38, 26, 32, 41, 50, 36, 17, 19, 29, 10, 13, 21,
6278     56, 45, 25, 31, 35, 16,  9, 12, 44, 24, 15,  8, 23,  7,  6,  5
6279 };
6280
6281 #else
6282
6283 EXTCONST bool PL_valid_types_IVX[];
6284 EXTCONST bool PL_valid_types_NVX[];
6285 EXTCONST bool PL_valid_types_PVX[];
6286 EXTCONST bool PL_valid_types_RV[];
6287 EXTCONST bool PL_valid_types_IV_set[];
6288 EXTCONST bool PL_valid_types_NV_set[];
6289 EXTCONST U8   PL_deBruijn_bitpos_tab32[];
6290 EXTCONST U8   PL_deBruijn_bitpos_tab64[];
6291
6292 #endif
6293
6294 /* The constants for using PL_deBruijn_bitpos_tab */
6295 #define PERL_deBruijnMagic32_  0x077CB531
6296 #define PERL_deBruijnShift32_  27
6297 #define PERL_deBruijnMagic64_  0x07EDD5E59A4E28C2
6298 #define PERL_deBruijnShift64_  58
6299
6300 /* In C99 we could use designated (named field) union initializers.
6301  * In C89 we need to initialize the member declared first.
6302  * In C++ we need extern C initializers.
6303  *
6304  * With the U8_NV version you will want to have inner braces,
6305  * while with the NV_U8 use just the NV. */
6306
6307 #define INFNAN_U8_NV_DECL EXTCONST union { U8 u8[NVSIZE]; NV nv; }
6308 #define INFNAN_NV_U8_DECL EXTCONST union { NV nv; U8 u8[NVSIZE]; }
6309
6310 /* if these never got defined, they need defaults */
6311 #ifndef PERL_SET_CONTEXT
6312 #  define PERL_SET_CONTEXT(i)           PERL_SET_INTERP(i)
6313 #endif
6314
6315 #ifdef USE_PERL_SWITCH_LOCALE_CONTEXT
6316 #  define PERL_SET_LOCALE_CONTEXT(i)                                        \
6317       STMT_START {                                                          \
6318           if (UNLIKELY(PL_veto_switch_non_tTHX_context))                    \
6319                 Perl_switch_locale_context();                               \
6320       } STMT_END
6321 #else
6322 #  define PERL_SET_LOCALE_CONTEXT(i)  NOOP
6323 #endif
6324
6325 /* In some Configurations there may be per-thread information that is carried
6326  * in a library instead of perl's tTHX structure.  This macro is to be used to
6327  * handle those when tTHX is changed.  Only locale handling is currently known
6328  * to be affected. */
6329 #define PERL_SET_NON_tTHX_CONTEXT(i)                                        \
6330                         STMT_START { PERL_SET_LOCALE_CONTEXT(i); } STMT_END
6331
6332
6333 #ifndef PERL_GET_CONTEXT
6334 #  define PERL_GET_CONTEXT              PERL_GET_INTERP
6335 #endif
6336
6337 #ifndef PERL_GET_THX
6338 #  define PERL_GET_THX                  ((void*)NULL)
6339 #endif
6340
6341 #ifndef PERL_SET_THX
6342 #  define PERL_SET_THX(t)               NOOP
6343 #endif
6344
6345 #ifndef EBCDIC
6346
6347 /* The tables below are adapted from
6348  * https://bjoern.hoehrmann.de/utf-8/decoder/dfa/, which requires this copyright
6349  * notice:
6350
6351 Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>
6352
6353 Permission is hereby granted, free of charge, to any person obtaining a copy of
6354 this software and associated documentation files (the "Software"), to deal in
6355 the Software without restriction, including without limitation the rights to
6356 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
6357 of the Software, and to permit persons to whom the Software is furnished to do
6358 so, subject to the following conditions:
6359
6360 The above copyright notice and this permission notice shall be included in all
6361 copies or substantial portions of the Software.
6362
6363 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
6364 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
6365 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
6366 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
6367 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
6368 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
6369 SOFTWARE.
6370
6371 */
6372
6373 #  ifdef DOINIT
6374 #    if 0       /* This is the original table given in
6375                    https://bjoern.hoehrmann.de/utf-8/decoder/dfa/ */
6376 static U8 utf8d_C9[] = {
6377   /* The first part of the table maps bytes to character classes that
6378    * to reduce the size of the transition table and create bitmasks. */
6379    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /*-1F*/
6380    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /*-3F*/
6381    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /*-5F*/
6382    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /*-7F*/
6383    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,  9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, /*-9F*/
6384    7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,  7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, /*-BF*/
6385    8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2,  2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, /*-DF*/
6386   10,3,3,3,3,3,3,3,3,3,3,3,3,4,3,3, 11,6,6,6,5,8,8,8,8,8,8,8,8,8,8,8, /*-FF*/
6387
6388   /* The second part is a transition table that maps a combination
6389    * of a state of the automaton and a character class to a state. */
6390    0,12,24,36,60,96,84,12,12,12,48,72, 12,12,12,12,12,12,12,12,12,12,12,12,
6391   12, 0,12,12,12,12,12, 0,12, 0,12,12, 12,24,12,12,12,12,12,24,12,24,12,12,
6392   12,12,12,12,12,12,12,24,12,12,12,12, 12,24,12,12,12,12,12,12,12,24,12,12,
6393   12,12,12,12,12,12,12,36,12,36,12,12, 12,36,12,12,12,12,12,36,12,36,12,12,
6394   12,36,12,12,12,12,12,12,12,12,12,12
6395 };
6396
6397 #    endif
6398
6399 /* This is a version of the above table customized for Perl that doesn't
6400  * exclude surrogates and accepts start bytes up through FD (FE on 64-bit
6401  * machines).  The classes have been renumbered so that the patterns are more
6402  * evident in the table.  The class numbers are structured so the values are:
6403  *
6404  *  a) UTF-8 invariant code points
6405  *          0
6406  *  b) Start bytes that always lead to either overlongs or some class of code
6407  *     point that needs outside intervention for handling (such as to raise a
6408  *     warning)
6409  *          1
6410  *  c) Start bytes that never lead to one of the above
6411  *      number of bytes in complete sequence
6412  *  d) Rest of start bytes (they can be resolved through this algorithm) and
6413  *     continuation bytes
6414  *          arbitrary class number chosen to not conflict with the above
6415  *          classes, and to index into the remaining table
6416  *
6417  * It would make the code simpler if start byte FF could also be handled, but
6418  * doing so would mean adding two more classes (one from splitting 80 from 81,
6419  * and one for FF), and nodes for each of 6 new continuation bytes.  The
6420  * current table has 436 entries; the new one would require 140 more = 576 (2
6421  * additional classes for each of the 10 existing nodes, and 20 for each of 6
6422  * new nodes.  The array would have to be made U16 instead of U8, not worth it
6423  * for this rarely encountered case
6424  *
6425  * The classes are
6426  *      00-7F           0   Always legal, single byte sequence
6427  *      80-81           7   Not legal immediately after start bytes E0 F0 F8 FC
6428  *                          FE
6429  *      82-83           8   Not legal immediately after start bytes E0 F0 F8 FC
6430  *      84-87           9   Not legal immediately after start bytes E0 F0 F8
6431  *      88-8F          10   Not legal immediately after start bytes E0 F0
6432  *      90-9F          11   Not legal immediately after start byte E0
6433  *      A0-BF          12   Always legal continuation byte
6434  *      C0,C1           1   Not legal: overlong
6435  *      C2-DF           2   Legal start byte for two byte sequences
6436  *      E0             13   Some sequences are overlong; others legal
6437  *      E1-EF           3   Legal start byte for three byte sequences
6438  *      F0             14   Some sequences are overlong; others legal
6439  *      F1-F7           4   Legal start byte for four byte sequences
6440  *      F8             15   Some sequences are overlong; others legal
6441  *      F9-FB           5   Legal start byte for five byte sequences
6442  *      FC             16   Some sequences are overlong; others legal
6443  *      FD              6   Legal start byte for six byte sequences
6444  *      FE             17   Some sequences are overlong; others legal
6445  *                          (is 1 on 32-bit machines, since it overflows)
6446  *      FF              1   Need to handle specially
6447  */
6448
6449 EXTCONST U8 PL_extended_utf8_dfa_tab[] = {
6450     /* The first part of the table maps bytes to character classes to reduce
6451      * the size of the transition table and create bitmasks. */
6452    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*00-0F*/
6453    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*10-1F*/
6454    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*20-2F*/
6455    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*30-3F*/
6456    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*40-4F*/
6457    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*50-5F*/
6458    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*60-6F*/
6459    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*70-7F*/
6460    7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10, /*80-8F*/
6461   11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11, /*90-9F*/
6462   12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12, /*A0-AF*/
6463   12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12, /*B0-BF*/
6464    1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /*C0-CF*/
6465    2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /*D0-DF*/
6466   13, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /*E0-EF*/
6467   14, 4, 4, 4, 4, 4, 4, 4,15, 5, 5, 5,16, 6,       /*F0-FD*/
6468 #    ifdef UV_IS_QUAD
6469                                             17,    /*FE*/
6470 #    else
6471                                              1,    /*FE*/
6472 #    endif
6473                                                 1, /*FF*/
6474
6475 /* The second part is a transition table that maps a combination
6476  * of a state of the automaton and a character class to a new state, called a
6477  * node.  The nodes are:
6478  * N0     The initial state, and final accepting one.
6479  * N1     Any one continuation byte (80-BF) left.  This is transitioned to
6480  *        immediately when the start byte indicates a two-byte sequence
6481  * N2     Any two continuation bytes left.
6482  * N3     Any three continuation bytes left.
6483  * N4     Any four continuation bytes left.
6484  * N5     Any five continuation bytes left.
6485  * N6     Start byte is E0.  Continuation bytes 80-9F are illegal (overlong);
6486  *        the other continuations transition to N1
6487  * N7     Start byte is F0.  Continuation bytes 80-8F are illegal (overlong);
6488  *        the other continuations transition to N2
6489  * N8     Start byte is F8.  Continuation bytes 80-87 are illegal (overlong);
6490  *        the other continuations transition to N3
6491  * N9     Start byte is FC.  Continuation bytes 80-83 are illegal (overlong);
6492  *        the other continuations transition to N4
6493  * N10    Start byte is FE.  Continuation bytes 80-81 are illegal (overlong);
6494  *        the other continuations transition to N5
6495  * 1      Reject.  All transitions not mentioned above (except the single
6496  *        byte ones (as they are always legal)) are to this state.
6497  */
6498
6499 #    if defined(PERL_CORE)
6500 #      define NUM_CLASSES 18
6501 #      define N0 0
6502 #      define N1 ((N0)   + NUM_CLASSES)
6503 #      define N2 ((N1)   + NUM_CLASSES)
6504 #      define N3 ((N2)   + NUM_CLASSES)
6505 #      define N4 ((N3)   + NUM_CLASSES)
6506 #      define N5 ((N4)   + NUM_CLASSES)
6507 #      define N6 ((N5)   + NUM_CLASSES)
6508 #      define N7 ((N6)   + NUM_CLASSES)
6509 #      define N8 ((N7)   + NUM_CLASSES)
6510 #      define N9 ((N8)   + NUM_CLASSES)
6511 #      define N10 ((N9)  + NUM_CLASSES)
6512
6513 /*Class: 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17  */
6514 /*N0*/   0, 1,N1,N2,N3,N4,N5, 1, 1, 1, 1, 1, 1,N6,N7,N8,N9,N10,
6515 /*N1*/   1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1,
6516 /*N2*/   1, 1, 1, 1, 1, 1, 1,N1,N1,N1,N1,N1,N1, 1, 1, 1, 1, 1,
6517 /*N3*/   1, 1, 1, 1, 1, 1, 1,N2,N2,N2,N2,N2,N2, 1, 1, 1, 1, 1,
6518 /*N4*/   1, 1, 1, 1, 1, 1, 1,N3,N3,N3,N3,N3,N3, 1, 1, 1, 1, 1,
6519 /*N5*/   1, 1, 1, 1, 1, 1, 1,N4,N4,N4,N4,N4,N4, 1, 1, 1, 1, 1,
6520
6521 /*N6*/   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,N1, 1, 1, 1, 1, 1,
6522 /*N7*/   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,N2,N2, 1, 1, 1, 1, 1,
6523 /*N8*/   1, 1, 1, 1, 1, 1, 1, 1, 1, 1,N3,N3,N3, 1, 1, 1, 1, 1,
6524 /*N9*/   1, 1, 1, 1, 1, 1, 1, 1, 1,N4,N4,N4,N4, 1, 1, 1, 1, 1,
6525 /*N10*/  1, 1, 1, 1, 1, 1, 1, 1,N5,N5,N5,N5,N5, 1, 1, 1, 1, 1,
6526 };
6527
6528 /* And below is a version of the above table that accepts only strict UTF-8.
6529  * Hence no surrogates nor non-characters, nor non-Unicode.  Thus, if the input
6530  * passes this dfa, it will be for a well-formed, non-problematic code point
6531  * that can be returned immediately.
6532  *
6533  * The "Implementation details" portion of
6534  * https://bjoern.hoehrmann.de/utf-8/decoder/dfa/ shows how
6535  * the first portion of the table maps each possible byte into a character
6536  * class.  And that the classes for those bytes which are start bytes have been
6537  * carefully chosen so they serve as well to be used as a shift value to mask
6538  * off the leading 1 bits of the start byte.  Unfortunately the addition of
6539  * being able to distinguish non-characters makes this not fully work.  This is
6540  * because, now, the start bytes E1-EF have to be broken into 3 classes instead
6541  * of 2:
6542  *  1) ED because it could be a surrogate
6543  *  2) EF because it could be a non-character
6544  *  3) the rest, which can never evaluate to a problematic code point.
6545  *
6546  * Each of E1-EF has three leading 1 bits, then a 0.  That means we could use a
6547  * shift (and hence class number) of either 3 or 4 to get a mask that works.
6548  * But that only allows two categories, and we need three.  khw made the
6549  * decision to therefore treat the ED start byte as an error, so that the dfa
6550  * drops out immediately for that.  In the dfa, classes 3 and 4 are used to
6551  * distinguish EF vs the rest.  Then special code is used to deal with ED,
6552  * that's executed only when the dfa drops out.  The code points started by ED
6553  * are half surrogates, and half hangul syllables.  This means that 2048 of
6554  * the hangul syllables (about 18%) take longer than all other non-problematic
6555  * code points to handle.
6556  *
6557  * The changes to handle non-characters requires the addition of states and
6558  * classes to the dfa.  (See the section on "Mapping bytes to character
6559  * classes" in the linked-to document for further explanation of the original
6560  * dfa.)
6561  *
6562  * The classes are
6563  *      00-7F           0
6564  *      80-8E           9
6565  *      8F             10
6566  *      90-9E          11
6567  *      9F             12
6568  *      A0-AE          13
6569  *      AF             14
6570  *      B0-B6          15
6571  *      B7             16
6572  *      B8-BD          15
6573  *      BE             17
6574  *      BF             18
6575  *      C0,C1           1
6576  *      C2-DF           2
6577  *      E0              7
6578  *      E1-EC           3
6579  *      ED              1
6580  *      EE              3
6581  *      EF              4
6582  *      F0              8
6583  *      F1-F3           6  (6 bits can be stripped)
6584  *      F4              5  (only 5 can be stripped)
6585  *      F5-FF           1
6586  */
6587
6588 EXTCONST U8 PL_strict_utf8_dfa_tab[] = {
6589     /* The first part of the table maps bytes to character classes to reduce
6590      * the size of the transition table and create bitmasks. */
6591    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*00-0F*/
6592    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*10-1F*/
6593    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*20-2F*/
6594    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*30-3F*/
6595    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*40-4F*/
6596    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*50-5F*/
6597    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*60-6F*/
6598    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*70-7F*/
6599    9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, /*80-8F*/
6600   11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12, /*90-9F*/
6601   13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,14, /*A0-AF*/
6602   15,15,15,15,15,15,15,16,15,15,15,15,15,15,17,18, /*B0-BF*/
6603    1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /*C0-CF*/
6604    2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /*D0-DF*/
6605    7, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 3, 4, /*E0-EF*/
6606    8, 6, 6, 6, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /*F0-FF*/
6607
6608 /* The second part is a transition table that maps a combination
6609  * of a state of the automaton and a character class to a new state, called a
6610  * node.  The nodes are:
6611  * N0     The initial state, and final accepting one.
6612  * N1     Any one continuation byte (80-BF) left.  This is transitioned to
6613  *        immediately when the start byte indicates a two-byte sequence
6614  * N2     Any two continuation bytes left.
6615  * N3     Start byte is E0.  Continuation bytes 80-9F are illegal (overlong);
6616  *        the other continuations transition to state N1
6617  * N4     Start byte is EF.  Continuation byte B7 transitions to N8; BF to N9;
6618  *        the other continuations transitions to N1
6619  * N5     Start byte is F0.  Continuation bytes 80-8F are illegal (overlong);
6620  *        [9AB]F transition to N10; the other continuations to N2.
6621  * N6     Start byte is F[123].  Continuation bytes [89AB]F transition
6622  *        to N10; the other continuations to N2.
6623  * N7     Start byte is F4.  Continuation bytes 90-BF are illegal
6624  *        (non-unicode); 8F transitions to N10; the other continuations to N2
6625  * N8     Initial sequence is EF B7.  Continuation bytes 90-AF are illegal
6626  *        (non-characters); the other continuations transition to N0.
6627  * N9     Initial sequence is EF BF.  Continuation bytes BE and BF are illegal
6628  *        (non-characters); the other continuations transition to N0.
6629  * N10    Initial sequence is one of: F0 [9-B]F; F[123] [8-B]F; or F4 8F.
6630  *        Continuation byte BF transitions to N11; the other continuations to
6631  *        N1
6632  * N11    Initial sequence is the two bytes given in N10 followed by BF.
6633  *        Continuation bytes BE and BF are illegal (non-characters); the other
6634  *        continuations transition to N0.
6635  * 1      Reject.  All transitions not mentioned above (except the single
6636  *        byte ones (as they are always legal) are to this state.
6637  */
6638
6639 #      undef N0
6640 #      undef N1
6641 #      undef N2
6642 #      undef N3
6643 #      undef N4
6644 #      undef N5
6645 #      undef N6
6646 #      undef N7
6647 #      undef N8
6648 #      undef N9
6649 #      undef NUM_CLASSES
6650 #      define NUM_CLASSES 19
6651 #      define N0 0
6652 #      define N1  ((N0)  + NUM_CLASSES)
6653 #      define N2  ((N1)  + NUM_CLASSES)
6654 #      define N3  ((N2)  + NUM_CLASSES)
6655 #      define N4  ((N3)  + NUM_CLASSES)
6656 #      define N5  ((N4)  + NUM_CLASSES)
6657 #      define N6  ((N5)  + NUM_CLASSES)
6658 #      define N7  ((N6)  + NUM_CLASSES)
6659 #      define N8  ((N7)  + NUM_CLASSES)
6660 #      define N9  ((N8)  + NUM_CLASSES)
6661 #      define N10 ((N9)  + NUM_CLASSES)
6662 #      define N11 ((N10) + NUM_CLASSES)
6663
6664 /*Class: 0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18 */
6665 /*N0*/   0,  1, N1, N2, N4, N7, N6, N3, N5,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
6666 /*N1*/   1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
6667 /*N2*/   1,  1,  1,  1,  1,  1,  1,  1,  1, N1, N1, N1, N1, N1, N1, N1, N1, N1, N1,
6668
6669 /*N3*/   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1, N1, N1, N1, N1, N1, N1,
6670 /*N4*/   1,  1,  1,  1,  1,  1,  1,  1,  1, N1, N1, N1, N1, N1, N1, N1, N8, N1, N9,
6671 /*N5*/   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1, N2,N10, N2,N10, N2, N2, N2,N10,
6672 /*N6*/   1,  1,  1,  1,  1,  1,  1,  1,  1, N2,N10, N2,N10, N2,N10, N2, N2, N2,N10,
6673 /*N7*/   1,  1,  1,  1,  1,  1,  1,  1,  1, N2,N10,  1,  1,  1,  1,  1,  1,  1,  1,
6674 /*N8*/   1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  1,  1,  1,  1,  0,  0,  0,  0,
6675 /*N9*/   1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,
6676 /*N10*/  1,  1,  1,  1,  1,  1,  1,  1,  1, N1, N1, N1, N1, N1, N1, N1, N1, N1,N11,
6677 /*N11*/  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,
6678 };
6679
6680 /* And below is yet another version of the above tables that accepts only UTF-8
6681  * as defined by Corregidum #9.  Hence no surrogates nor non-Unicode, but
6682  * it allows non-characters.  This is isomorphic to the original table
6683  * in https://bjoern.hoehrmann.de/utf-8/decoder/dfa/
6684  *
6685  * The classes are
6686  *      00-7F           0
6687  *      80-8F           9
6688  *      90-9F          10
6689  *      A0-BF          11
6690  *      C0,C1           1
6691  *      C2-DF           2
6692  *      E0              7
6693  *      E1-EC           3
6694  *      ED              4
6695  *      EE-EF           3
6696  *      F0              8
6697  *      F1-F3           6  (6 bits can be stripped)
6698  *      F4              5  (only 5 can be stripped)
6699  *      F5-FF           1
6700  */
6701
6702 EXTCONST U8 PL_c9_utf8_dfa_tab[] = {
6703     /* The first part of the table maps bytes to character classes to reduce
6704      * the size of the transition table and create bitmasks. */
6705    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*00-0F*/
6706    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*10-1F*/
6707    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*20-2F*/
6708    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*30-3F*/
6709    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*40-4F*/
6710    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*50-5F*/
6711    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*60-6F*/
6712    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*70-7F*/
6713    9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, /*80-8F*/
6714   10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, /*90-9F*/
6715   11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11, /*A0-AF*/
6716   11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11, /*B0-BF*/
6717    1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /*C0-CF*/
6718    2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /*D0-DF*/
6719    7, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 3, 3, /*E0-EF*/
6720    8, 6, 6, 6, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /*F0-FF*/
6721
6722 /* The second part is a transition table that maps a combination
6723  * of a state of the automaton and a character class to a new state, called a
6724  * node.  The nodes are:
6725  * N0     The initial state, and final accepting one.
6726  * N1     Any one continuation byte (80-BF) left.  This is transitioned to
6727  *        immediately when the start byte indicates a two-byte sequence
6728  * N2     Any two continuation bytes left.
6729  * N3     Any three continuation bytes left.
6730  * N4     Start byte is E0.  Continuation bytes 80-9F are illegal (overlong);
6731  *        the other continuations transition to state N1
6732  * N5     Start byte is ED.  Continuation bytes A0-BF all lead to surrogates,
6733  *        so are illegal.  The other continuations transition to state N1.
6734  * N6     Start byte is F0.  Continuation bytes 80-8F are illegal (overlong);
6735  *        the other continuations transition to N2
6736  * N7     Start byte is F4.  Continuation bytes 90-BF are illegal
6737  *        (non-unicode); the other continuations transition to N2
6738  * 1      Reject.  All transitions not mentioned above (except the single
6739  *        byte ones (as they are always legal) are to this state.
6740  */
6741
6742 #      undef N0
6743 #      undef N1
6744 #      undef N2
6745 #      undef N3
6746 #      undef N4
6747 #      undef N5
6748 #      undef N6
6749 #      undef N7
6750 #      undef NUM_CLASSES
6751 #      define NUM_CLASSES 12
6752 #      define N0 0
6753 #      define N1  ((N0)  + NUM_CLASSES)
6754 #      define N2  ((N1)  + NUM_CLASSES)
6755 #      define N3  ((N2)  + NUM_CLASSES)
6756 #      define N4  ((N3)  + NUM_CLASSES)
6757 #      define N5  ((N4)  + NUM_CLASSES)
6758 #      define N6  ((N5)  + NUM_CLASSES)
6759 #      define N7  ((N6)  + NUM_CLASSES)
6760
6761 /*Class: 0   1   2   3   4   5   6   7   8   9  10  11 */
6762 /*N0*/   0,  1, N1, N2, N5, N7, N3, N4, N6,  1,  1,  1,
6763 /*N1*/   1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,
6764 /*N2*/   1,  1,  1,  1,  1,  1,  1,  1,  1, N1, N1, N1,
6765 /*N3*/   1,  1,  1,  1,  1,  1,  1,  1,  1, N2, N2, N2,
6766
6767 /*N4*/   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1, N1,
6768 /*N5*/   1,  1,  1,  1,  1,  1,  1,  1,  1, N1, N1,  1,
6769 /*N6*/   1,  1,  1,  1,  1,  1,  1,  1,  1,  1, N2, N2,
6770 /*N7*/   1,  1,  1,  1,  1,  1,  1,  1,  1, N2,  1,  1,
6771 };
6772
6773 #    endif /* defined(PERL_CORE) */
6774 #  else     /* End of is DOINIT */
6775
6776 EXTCONST U8 PL_extended_utf8_dfa_tab[];
6777 EXTCONST U8 PL_strict_utf8_dfa_tab[];
6778 EXTCONST U8 PL_c9_utf8_dfa_tab[];
6779
6780 #  endif
6781 #endif    /* end of isn't EBCDIC */
6782
6783 #include "overload.h"
6784
6785 END_EXTERN_C
6786
6787 struct am_table {
6788   U8 flags;
6789   U8 fallback;
6790   U16 spare;
6791   U32 was_ok_sub;
6792   CV* table[NofAMmeth];
6793 };
6794 struct am_table_short {
6795   U8 flags;
6796   U8 fallback;
6797   U16 spare;
6798   U32 was_ok_sub;
6799 };
6800 typedef struct am_table AMT;
6801 typedef struct am_table_short AMTS;
6802
6803 #define AMGfallNEVER    1
6804 #define AMGfallNO       2
6805 #define AMGfallYES      3
6806
6807 #define AMTf_AMAGIC             1
6808 #define AMT_AMAGIC(amt)         ((amt)->flags & AMTf_AMAGIC)
6809 #define AMT_AMAGIC_on(amt)      ((amt)->flags |= AMTf_AMAGIC)
6810 #define AMT_AMAGIC_off(amt)     ((amt)->flags &= ~AMTf_AMAGIC)
6811
6812 #define StashHANDLER(stash,meth)        gv_handler((stash),CAT2(meth,_amg))
6813
6814 /*
6815  * some compilers like to redefine cos et alia as faster
6816  * (and less accurate?) versions called F_cos et cetera (Quidquid
6817  * latine dictum sit, altum viditur.)  This trick collides with
6818  * the Perl overloading (amg).  The following #defines fool both.
6819  */
6820
6821 #ifdef _FASTMATH
6822 #   ifdef atan2
6823 #       define F_atan2_amg  atan2_amg
6824 #   endif
6825 #   ifdef cos
6826 #       define F_cos_amg    cos_amg
6827 #   endif
6828 #   ifdef exp
6829 #       define F_exp_amg    exp_amg
6830 #   endif
6831 #   ifdef log
6832 #       define F_log_amg    log_amg
6833 #   endif
6834 #   ifdef pow
6835 #       define F_pow_amg    pow_amg
6836 #   endif
6837 #   ifdef sin
6838 #       define F_sin_amg    sin_amg
6839 #   endif
6840 #   ifdef sqrt
6841 #       define F_sqrt_amg   sqrt_amg
6842 #   endif
6843 #endif /* _FASTMATH */
6844
6845 #define PERLDB_ALL              (PERLDBf_SUB    | PERLDBf_LINE  |       \
6846                                  PERLDBf_NOOPT  | PERLDBf_INTER |       \
6847                                  PERLDBf_SUBLINE| PERLDBf_SINGLE|       \
6848                                  PERLDBf_NAMEEVAL| PERLDBf_NAMEANON |   \
6849                                  PERLDBf_SAVESRC)
6850                                         /* No _NONAME, _GOTO */
6851 #define PERLDBf_SUB             0x01    /* Debug sub enter/exit */
6852 #define PERLDBf_LINE            0x02    /* Keep line # */
6853 #define PERLDBf_NOOPT           0x04    /* Switch off optimizations */
6854 #define PERLDBf_INTER           0x08    /* Preserve more data for
6855                                            later inspections  */
6856 #define PERLDBf_SUBLINE         0x10    /* Keep subr source lines */
6857 #define PERLDBf_SINGLE          0x20    /* Start with single-step on */
6858 #define PERLDBf_NONAME          0x40    /* For _SUB: no name of the subr */
6859 #define PERLDBf_GOTO            0x80    /* Report goto: call DB::goto */
6860 #define PERLDBf_NAMEEVAL        0x100   /* Informative names for evals */
6861 #define PERLDBf_NAMEANON        0x200   /* Informative names for anon subs */
6862 #define PERLDBf_SAVESRC         0x400   /* Save source lines into @{"_<$filename"} */
6863 #define PERLDBf_SAVESRC_NOSUBS  0x800   /* Including evals that generate no subroutines */
6864 #define PERLDBf_SAVESRC_INVALID 0x1000  /* Save source that did not compile */
6865
6866 #define PERLDB_SUB              (PL_perldb & PERLDBf_SUB)
6867 #define PERLDB_LINE             (PL_perldb & PERLDBf_LINE)
6868 #define PERLDB_NOOPT            (PL_perldb & PERLDBf_NOOPT)
6869 #define PERLDB_INTER            (PL_perldb & PERLDBf_INTER)
6870 #define PERLDB_SUBLINE          (PL_perldb & PERLDBf_SUBLINE)
6871 #define PERLDB_SINGLE           (PL_perldb & PERLDBf_SINGLE)
6872 #define PERLDB_SUB_NN           (PL_perldb & PERLDBf_NONAME)
6873 #define PERLDB_GOTO             (PL_perldb & PERLDBf_GOTO)
6874 #define PERLDB_NAMEEVAL         (PL_perldb & PERLDBf_NAMEEVAL)
6875 #define PERLDB_NAMEANON         (PL_perldb & PERLDBf_NAMEANON)
6876 #define PERLDB_SAVESRC          (PL_perldb & PERLDBf_SAVESRC)
6877 #define PERLDB_SAVESRC_NOSUBS   (PL_perldb & PERLDBf_SAVESRC_NOSUBS)
6878 #define PERLDB_SAVESRC_INVALID  (PL_perldb & PERLDBf_SAVESRC_INVALID)
6879
6880 #define PERLDB_LINE_OR_SAVESRC (PL_perldb & (PERLDBf_LINE | PERLDBf_SAVESRC))
6881
6882 #ifdef USE_ITHREADS
6883 #  define KEYWORD_PLUGIN_MUTEX_INIT    MUTEX_INIT(&PL_keyword_plugin_mutex)
6884 #  define KEYWORD_PLUGIN_MUTEX_LOCK    MUTEX_LOCK(&PL_keyword_plugin_mutex)
6885 #  define KEYWORD_PLUGIN_MUTEX_UNLOCK  MUTEX_UNLOCK(&PL_keyword_plugin_mutex)
6886 #  define KEYWORD_PLUGIN_MUTEX_TERM    MUTEX_DESTROY(&PL_keyword_plugin_mutex)
6887 #  define USER_PROP_MUTEX_INIT    MUTEX_INIT(&PL_user_prop_mutex)
6888 #  define USER_PROP_MUTEX_LOCK    MUTEX_LOCK(&PL_user_prop_mutex)
6889 #  define USER_PROP_MUTEX_UNLOCK  MUTEX_UNLOCK(&PL_user_prop_mutex)
6890 #  define USER_PROP_MUTEX_TERM    MUTEX_DESTROY(&PL_user_prop_mutex)
6891 #else
6892 #  define KEYWORD_PLUGIN_MUTEX_INIT    NOOP
6893 #  define KEYWORD_PLUGIN_MUTEX_LOCK    NOOP
6894 #  define KEYWORD_PLUGIN_MUTEX_UNLOCK  NOOP
6895 #  define KEYWORD_PLUGIN_MUTEX_TERM    NOOP
6896 #  define USER_PROP_MUTEX_INIT    NOOP
6897 #  define USER_PROP_MUTEX_LOCK    NOOP
6898 #  define USER_PROP_MUTEX_UNLOCK  NOOP
6899 #  define USER_PROP_MUTEX_TERM    NOOP
6900 #endif
6901
6902 #ifdef USE_LOCALE /* These locale things are all subject to change */
6903
6904    /* Returns TRUE if the plain locale pragma without a parameter is in effect.
6905     * */
6906 #  define IN_LOCALE_RUNTIME     (PL_curcop                                  \
6907                               && CopHINTS_get(PL_curcop) & HINT_LOCALE)
6908
6909    /* Returns TRUE if either form of the locale pragma is in effect */
6910 #  define IN_SOME_LOCALE_FORM_RUNTIME                                       \
6911         cBOOL(CopHINTS_get(PL_curcop) & (HINT_LOCALE|HINT_LOCALE_PARTIAL))
6912
6913 #  define IN_LOCALE_COMPILETIME cBOOL(PL_hints & HINT_LOCALE)
6914 #  define IN_SOME_LOCALE_FORM_COMPILETIME                                   \
6915                         cBOOL(PL_hints & (HINT_LOCALE|HINT_LOCALE_PARTIAL))
6916
6917 /*
6918 =for apidoc_section $locale
6919
6920 =for apidoc Amn|bool|IN_LOCALE
6921
6922 Evaluates to TRUE if the plain locale pragma without a parameter (S<C<use
6923 locale>>) is in effect.
6924
6925 =for apidoc Amn|bool|IN_LOCALE_COMPILETIME
6926
6927 Evaluates to TRUE if, when compiling a perl program (including an C<eval>) if
6928 the plain locale pragma without a parameter (S<C<use locale>>) is in effect.
6929
6930 =for apidoc Amn|bool|IN_LOCALE_RUNTIME
6931
6932 Evaluates to TRUE if, when executing a perl program (including an C<eval>) if
6933 the plain locale pragma without a parameter (S<C<use locale>>) is in effect.
6934
6935 =cut
6936 */
6937
6938 #  define IN_LOCALE                                                         \
6939         (IN_PERL_COMPILETIME ? IN_LOCALE_COMPILETIME : IN_LOCALE_RUNTIME)
6940 #  define IN_SOME_LOCALE_FORM                                               \
6941                     (IN_PERL_COMPILETIME ? IN_SOME_LOCALE_FORM_COMPILETIME  \
6942                                          : IN_SOME_LOCALE_FORM_RUNTIME)
6943
6944 #  define IN_LC_ALL_COMPILETIME   IN_LOCALE_COMPILETIME
6945 #  define IN_LC_ALL_RUNTIME       IN_LOCALE_RUNTIME
6946
6947 #  define IN_LC_PARTIAL_COMPILETIME   cBOOL(PL_hints & HINT_LOCALE_PARTIAL)
6948 #  define IN_LC_PARTIAL_RUNTIME                                             \
6949               (PL_curcop && CopHINTS_get(PL_curcop) & HINT_LOCALE_PARTIAL)
6950
6951 #  define IN_LC_COMPILETIME(category)                                       \
6952        (       IN_LC_ALL_COMPILETIME                                        \
6953         || (   IN_LC_PARTIAL_COMPILETIME                                    \
6954             && Perl__is_in_locale_category(aTHX_ TRUE, (category))))
6955 #  define IN_LC_RUNTIME(category)                                           \
6956       (IN_LC_ALL_RUNTIME || (IN_LC_PARTIAL_RUNTIME                          \
6957                  && Perl__is_in_locale_category(aTHX_ FALSE, (category))))
6958 #  define IN_LC(category)  \
6959                     (IN_LC_COMPILETIME(category) || IN_LC_RUNTIME(category))
6960
6961 #  if defined (PERL_CORE) || defined (PERL_IN_XSUB_RE)
6962
6963      /* This internal macro should be called from places that operate under
6964       * locale rules.  If there is a problem with the current locale that
6965       * hasn't been raised yet, it will output a warning this time.  Because
6966       * this will so rarely  be true, there is no point to optimize for time;
6967       * instead it makes sense to minimize space used and do all the work in
6968       * the rarely called function */
6969 #    ifdef USE_LOCALE_CTYPE
6970 #      define CHECK_AND_WARN_PROBLEMATIC_LOCALE_                              \
6971                 STMT_START {                                                  \
6972                     if (UNLIKELY(PL_warn_locale)) {                           \
6973                         Perl_warn_problematic_locale();                       \
6974                     }                                                         \
6975                 }  STMT_END
6976 #    else
6977 #      define CHECK_AND_WARN_PROBLEMATIC_LOCALE_
6978 #    endif
6979
6980
6981      /* These two internal macros are called when a warning should be raised,
6982       * and will do so if enabled.  The first takes a single code point
6983       * argument; the 2nd, is a pointer to the first byte of the UTF-8 encoded
6984       * string, and an end position which it won't try to read past */
6985 #    define _CHECK_AND_OUTPUT_WIDE_LOCALE_CP_MSG(cp)                        \
6986         STMT_START {                                                        \
6987             if (! IN_UTF8_CTYPE_LOCALE && ckWARN(WARN_LOCALE)) {            \
6988                 Perl_warner(aTHX_ packWARN(WARN_LOCALE),                    \
6989                                        "Wide character (U+%" UVXf ") in %s",\
6990                                        (UV) cp, OP_DESC(PL_op));            \
6991             }                                                               \
6992         }  STMT_END
6993
6994 #    define _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(s, send)                 \
6995         STMT_START { /* Check if to warn before doing the conversion work */\
6996             if (! IN_UTF8_CTYPE_LOCALE && ckWARN(WARN_LOCALE)) {            \
6997                 UV cp = utf8_to_uvchr_buf((U8 *) (s), (U8 *) (send), NULL); \
6998                 Perl_warner(aTHX_ packWARN(WARN_LOCALE),                    \
6999                     "Wide character (U+%" UVXf ") in %s",                   \
7000                     (cp == 0)                                               \
7001                      ? UNICODE_REPLACEMENT                                  \
7002                      : (UV) cp,                                             \
7003                     OP_DESC(PL_op));                                        \
7004             }                                                               \
7005         }  STMT_END
7006
7007 #  endif   /* PERL_CORE or PERL_IN_XSUB_RE */
7008 #else   /* No locale usage */
7009 #  define IN_LOCALE_RUNTIME                0
7010 #  define IN_SOME_LOCALE_FORM_RUNTIME      0
7011 #  define IN_LOCALE_COMPILETIME            0
7012 #  define IN_SOME_LOCALE_FORM_COMPILETIME  0
7013 #  define IN_LOCALE                        0
7014 #  define IN_SOME_LOCALE_FORM              0
7015 #  define IN_LC_ALL_COMPILETIME            0
7016 #  define IN_LC_ALL_RUNTIME                0
7017 #  define IN_LC_PARTIAL_COMPILETIME        0
7018 #  define IN_LC_PARTIAL_RUNTIME            0
7019 #  define IN_LC_COMPILETIME(category)      0
7020 #  define IN_LC_RUNTIME(category)          0
7021 #  define IN_LC(category)                  0
7022 #  define CHECK_AND_WARN_PROBLEMATIC_LOCALE_
7023 #  define _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(s, send)
7024 #  define _CHECK_AND_OUTPUT_WIDE_LOCALE_CP_MSG(c)
7025 #endif
7026
7027 #define locale_panic_via_(m, f, l)  Perl_locale_panic((m), __LINE__, f, l)
7028 #define locale_panic_(m)  locale_panic_via_((m), __FILE__, __LINE__)
7029
7030 /* Locale/thread synchronization macros. */
7031 #if ! defined(USE_LOCALE_THREADS)
7032 #  define LOCALE_LOCK_(cond)  NOOP
7033 #  define LOCALE_UNLOCK_      NOOP
7034 #  define LOCALE_INIT
7035 #  define LOCALE_TERM
7036
7037 #else   /* Below: Threaded, and locales are supported */
7038
7039     /* A locale mutex is required on all such threaded builds.
7040      *
7041      * This mutex simulates a general (or recursive) semaphore.  The current
7042      * thread will lock the mutex if the per-thread variable is zero, and then
7043      * increments that variable.  Each corresponding UNLOCK decrements the
7044      * variable until it is 0, at which point it actually unlocks the mutex.
7045      * Since the variable is per-thread, initialized to 0, there is no race
7046      * with other threads.
7047      *
7048      * The single argument is a condition to test for, and if true, to panic.
7049      * Call it with the constant 0 to suppress the check.
7050      *
7051      * Clang improperly gives warnings for this, if not silenced:
7052      * https://clang.llvm.org/docs/ThreadSafetyAnalysis.html#conditional-locks
7053      */
7054 #  define LOCALE_LOCK_(cond_to_panic_if_already_locked)                     \
7055         STMT_START {                                                        \
7056             CLANG_DIAG_IGNORE(-Wthread-safety)                              \
7057             if (LIKELY(PL_locale_mutex_depth <= 0)) {                       \
7058                 DEBUG_Lv(PerlIO_printf(Perl_debug_log,                      \
7059                          "%s: %d: locking locale; depth=1\n",               \
7060                          __FILE__, __LINE__));                              \
7061                 MUTEX_LOCK(&PL_locale_mutex);                               \
7062                 PL_locale_mutex_depth = 1;                                  \
7063                 DEBUG_Lv(PerlIO_printf(Perl_debug_log,                      \
7064                          "%s: %d: locale locked; depth=1\n",               \
7065                          __FILE__, __LINE__));                              \
7066             }                                                               \
7067             else {                                                          \
7068                 PL_locale_mutex_depth++;                                    \
7069                 DEBUG_Lv(PerlIO_printf(Perl_debug_log,                      \
7070                         "%s: %d: avoided locking locale; new depth=%d\n",   \
7071                         __FILE__, __LINE__, PL_locale_mutex_depth));        \
7072                 if (cond_to_panic_if_already_locked) {                      \
7073                     locale_panic_("Trying to lock locale incompatibly: "    \
7074                          STRINGIFY(cond_to_panic_if_already_locked));       \
7075                 }                                                           \
7076             }                                                               \
7077             CLANG_DIAG_RESTORE                                              \
7078         } STMT_END
7079
7080 #  define LOCALE_UNLOCK_                                                    \
7081         STMT_START {                                                        \
7082             if (LIKELY(PL_locale_mutex_depth == 1)) {                       \
7083                 DEBUG_Lv(PerlIO_printf(Perl_debug_log,                      \
7084                          "%s: %d: unlocking locale; new depth=0\n",         \
7085                          __FILE__, __LINE__));                              \
7086                 PL_locale_mutex_depth = 0;                                  \
7087                 MUTEX_UNLOCK(&PL_locale_mutex);                             \
7088             }                                                               \
7089             else if (PL_locale_mutex_depth <= 0) {                          \
7090                 DEBUG_L(PerlIO_printf(Perl_debug_log,                       \
7091                         "%s: %d: ignored attempt to unlock already"         \
7092                         " unlocked locale; depth unchanged at %d\n",        \
7093                        __FILE__, __LINE__, PL_locale_mutex_depth));         \
7094             }                                                               \
7095             else {                                                          \
7096                 PL_locale_mutex_depth--;                                    \
7097                 DEBUG_Lv(PerlIO_printf(Perl_debug_log,                      \
7098                         "%s: %d: avoided unlocking locale; new depth=%d\n", \
7099                         __FILE__, __LINE__, PL_locale_mutex_depth));        \
7100             }                                                               \
7101         } STMT_END
7102
7103 #  if defined(USE_THREADS) && ! defined(USE_THREAD_SAFE_LOCALE)
7104
7105      /* By definition, a thread-unsafe locale means we need a critical
7106       * section. */
7107 #    define LOCALE_LOCK    LOCALE_LOCK_(0)
7108 #    define LOCALE_UNLOCK  LOCALE_UNLOCK_
7109 #    ifdef USE_LOCALE_NUMERIC
7110 #      define LC_NUMERIC_LOCK(cond_to_panic_if_already_locked)              \
7111                  LOCALE_LOCK_(cond_to_panic_if_already_locked)
7112 #      define LC_NUMERIC_UNLOCK  LOCALE_UNLOCK_
7113 #    endif
7114 #  endif
7115
7116 #  ifdef WIN32_USE_FAKE_OLD_MINGW_LOCALES
7117     /* This function is coerced by this Configure option into cleaning up
7118      * memory that is static to locale.c.  So we call it at termination.  Doing
7119      * it this way is kludgy but confines having to deal with this
7120      * Configuration to a bare minimum number of places. */
7121 #      define LOCALE_TERM_POSIX_2008_  Perl_thread_locale_term(NULL)
7122 #  elif ! defined(USE_POSIX_2008_LOCALE)
7123 #      define LOCALE_TERM_POSIX_2008_  NOOP
7124 #  else
7125      /* We have a locale object holding the 'C' locale for Posix 2008 */
7126 #    define LOCALE_TERM_POSIX_2008_                                         \
7127                     STMT_START {                                            \
7128                         if (PL_C_locale_obj) {                              \
7129                             /* Make sure we aren't using the locale         \
7130                              * space we are about to free */                \
7131                             uselocale(LC_GLOBAL_LOCALE);                    \
7132                             freelocale(PL_C_locale_obj);                    \
7133                             PL_C_locale_obj = (locale_t) NULL;              \
7134                         }                                                   \
7135                     } STMT_END
7136 #  endif
7137
7138 #  define LOCALE_INIT           MUTEX_INIT(&PL_locale_mutex)
7139 #  define LOCALE_TERM           STMT_START {                                \
7140                                     LOCALE_TERM_POSIX_2008_;                \
7141                                     MUTEX_DESTROY(&PL_locale_mutex);        \
7142                                 } STMT_END
7143 #endif
7144
7145 /* There are some locale-related functions which may need locking only because
7146  * they share some common memory across threads, and hence there is the
7147  * potential for a race in accessing that space.  Most are because their return
7148  * points to a global static buffer, but some just use some common space
7149  * internally.  All functions accessing a given space need to have a critical
7150  * section to prevent any other thread from accessing it at the same time.
7151  * Ideally, there would be a separate mutex for each such space, so that
7152  * another thread isn't unnecessarily blocked.  But, most of them need to be
7153  * locked against the locale changing while accessing that space, and it is not
7154  * expected that any will be called frequently, and the locked interval should
7155  * be short, and modern platforms will have reentrant versions (which don't
7156  * lock) for almost all of them, so khw thinks a single mutex should suffice.
7157  * Having a single mutex facilitates that, avoiding potential deadlock
7158  * situations.
7159  *
7160  * This will be a no-op iff the perl is unthreaded. 'gw' stands for 'global
7161  * write', to indicate the caller wants to be able to access memory that isn't
7162  * thread specific, either to write to itself, or to prevent anyone else from
7163  * writing. */
7164 #define gwLOCALE_LOCK    LOCALE_LOCK_(0)
7165 #define gwLOCALE_UNLOCK  LOCALE_UNLOCK_
7166
7167 /* setlocale() generally returns in a global static buffer, but not on Windows
7168  * when operating in thread-safe mode */
7169 #if defined(WIN32) && defined(USE_THREAD_SAFE_LOCALE)
7170 #  define POSIX_SETLOCALE_LOCK                                              \
7171             STMT_START {                                                    \
7172                 if (_configthreadlocale(0) == _DISABLE_PER_THREAD_LOCALE)   \
7173                     gwLOCALE_LOCK;                                          \
7174             } STMT_END
7175 #  define POSIX_SETLOCALE_UNLOCK                                            \
7176             STMT_START {                                                    \
7177                 if (_configthreadlocale(0) == _DISABLE_PER_THREAD_LOCALE)   \
7178                     gwLOCALE_UNLOCK;                                        \
7179             } STMT_END
7180 #else
7181 #  define POSIX_SETLOCALE_LOCK      gwLOCALE_LOCK
7182 #  define POSIX_SETLOCALE_UNLOCK    gwLOCALE_UNLOCK
7183 #endif
7184
7185 /* It handles _wsetlocale() as well */
7186 #define WSETLOCALE_LOCK      POSIX_SETLOCALE_LOCK
7187 #define WSETLOCALE_UNLOCK    POSIX_SETLOCALE_UNLOCK
7188
7189 /* Similar to gwLOCALE_LOCK, there are functions that require both the locale
7190  * and environment to be constant during their execution, and don't change
7191  * either of those things, but do write to some sort of shared global space.
7192  * They require some sort of exclusive lock against similar functions, and a
7193  * read lock on both the locale and environment.  However, on systems which
7194  * have per-thread locales, the locale is constant during the execution of
7195  * these functions, and so no locale lock is necssary.  For such systems, an
7196  * exclusive ENV lock is necessary and sufficient.  On systems where the locale
7197  * could change out from under us, we use an exclusive LOCALE lock to prevent
7198  * that, and a read ENV lock to prevent other threads that have nothing to do
7199  * with locales here from changing the environment. */
7200 #ifdef LOCALE_LOCK
7201 #  define gwENVr_LOCALEr_LOCK                                               \
7202                     STMT_START { LOCALE_LOCK; ENV_READ_LOCK; } STMT_END
7203 #  define gwENVr_LOCALEr_UNLOCK                                             \
7204                 STMT_START { ENV_READ_UNLOCK; LOCALE_UNLOCK; } STMT_END
7205 #else
7206 #  define gwENVr_LOCALEr_LOCK           ENV_LOCK
7207 #  define gwENVr_LOCALEr_UNLOCK         ENV_UNLOCK
7208 #endif
7209
7210 /* Now that we have defined gwENVr_LOCALEr_LOCK, we can finish defining
7211  * LOCALE_LOCK, which we kept undefined until here on a thread-safe system
7212  * so that we could use that fact to calculate what gwENVr_LOCALEr_LOCK should
7213  * be */
7214 #ifndef LOCALE_LOCK
7215 #  define LOCALE_LOCK                NOOP
7216 #  define LOCALE_UNLOCK              NOOP
7217 #endif
7218
7219
7220       /* On systems that don't have per-thread locales, even though we don't
7221        * think we are changing the locale ourselves, behind the scenes it does
7222        * get changed to whatever the thread's should be, so it has to be an
7223        * exclusive lock.  By defining it here with this name, we can, for the
7224        * most part, hide this detail from the rest of the code */
7225 /* Currently, the read lock is an exclusive lock */
7226 #define LOCALE_READ_LOCK                LOCALE_LOCK
7227 #define LOCALE_READ_UNLOCK              LOCALE_UNLOCK
7228
7229
7230 #ifndef LC_NUMERIC_LOCK
7231 #  define LC_NUMERIC_LOCK(cond)   NOOP
7232 #  define LC_NUMERIC_UNLOCK       NOOP
7233 #endif
7234
7235    /* These non-reentrant versions use global space */
7236 #  define MBLEN_LOCK_                gwLOCALE_LOCK
7237 #  define MBLEN_UNLOCK_              gwLOCALE_UNLOCK
7238
7239 #  define MBTOWC_LOCK_               gwLOCALE_LOCK
7240 #  define MBTOWC_UNLOCK_             gwLOCALE_UNLOCK
7241
7242 #  define WCTOMB_LOCK_               gwLOCALE_LOCK
7243 #  define WCTOMB_UNLOCK_             gwLOCALE_UNLOCK
7244
7245    /* Whereas the reentrant versions don't (assuming they are called with a
7246     * per-thread buffer; some have the capability of being called with a NULL
7247     * parameter, which defeats the reentrancy) */
7248 #  define MBRLEN_LOCK_                  NOOP
7249 #  define MBRLEN_UNLOCK_                NOOP
7250 #  define MBRTOWC_LOCK_                 NOOP
7251 #  define MBRTOWC_UNLOCK_               NOOP
7252 #  define WCRTOMB_LOCK_                 NOOP
7253 #  define WCRTOMB_UNLOCK_               NOOP
7254
7255 #  define LC_COLLATE_LOCK               LOCALE_LOCK
7256 #  define LC_COLLATE_UNLOCK             LOCALE_UNLOCK
7257
7258 #  define STRFTIME_LOCK                 ENV_LOCK
7259 #  define STRFTIME_UNLOCK               ENV_UNLOCK
7260
7261 #ifdef USE_LOCALE_NUMERIC
7262
7263 /* These macros are for toggling between the underlying locale (UNDERLYING or
7264  * LOCAL) and the C locale (STANDARD).  (Actually we don't have to use the C
7265  * locale if the underlying locale is indistinguishable from it in the numeric
7266  * operations used by Perl, namely the decimal point, and even the thousands
7267  * separator.)
7268
7269 =for apidoc_section $locale
7270
7271 =for apidoc Amn|void|DECLARATION_FOR_LC_NUMERIC_MANIPULATION
7272
7273 This macro should be used as a statement.  It declares a private variable
7274 (whose name begins with an underscore) that is needed by the other macros in
7275 this section.  Failing to include this correctly should lead to a syntax error.
7276 For compatibility with C89 C compilers it should be placed in a block before
7277 any executable statements.
7278
7279 =for apidoc Am|void|STORE_LC_NUMERIC_FORCE_TO_UNDERLYING
7280
7281 This is used by XS code that is C<LC_NUMERIC> locale-aware to force the
7282 locale for category C<LC_NUMERIC> to be what perl thinks is the current
7283 underlying locale.  (The perl interpreter could be wrong about what the
7284 underlying locale actually is if some C or XS code has called the C library
7285 function L<setlocale(3)> behind its back; calling L</sync_locale> before calling
7286 this macro will update perl's records.)
7287
7288 A call to L</DECLARATION_FOR_LC_NUMERIC_MANIPULATION> must have been made to
7289 declare at compile time a private variable used by this macro.  This macro
7290 should be called as a single statement, not an expression, but with an empty
7291 argument list, like this:
7292
7293  {
7294     DECLARATION_FOR_LC_NUMERIC_MANIPULATION;
7295      ...
7296     STORE_LC_NUMERIC_FORCE_TO_UNDERLYING();
7297      ...
7298     RESTORE_LC_NUMERIC();
7299      ...
7300  }
7301
7302 The private variable is used to save the current locale state, so
7303 that the requisite matching call to L</RESTORE_LC_NUMERIC> can restore it.
7304
7305 On threaded perls not operating with thread-safe functionality, this macro uses
7306 a mutex to force a critical section.  Therefore the matching RESTORE should be
7307 close by, and guaranteed to be called.
7308
7309 =for apidoc Am|void|STORE_LC_NUMERIC_SET_TO_NEEDED
7310
7311 This is used to help wrap XS or C code that is C<LC_NUMERIC> locale-aware.
7312 This locale category is generally kept set to a locale where the decimal radix
7313 character is a dot, and the separator between groups of digits is empty.  This
7314 is because most XS code that reads floating point numbers is expecting them to
7315 have this syntax.
7316
7317 This macro makes sure the current C<LC_NUMERIC> state is set properly, to be
7318 aware of locale if the call to the XS or C code from the Perl program is
7319 from within the scope of a S<C<use locale>>; or to ignore locale if the call is
7320 instead from outside such scope.
7321
7322 This macro is the start of wrapping the C or XS code; the wrap ending is done
7323 by calling the L</RESTORE_LC_NUMERIC> macro after the operation.  Otherwise
7324 the state can be changed that will adversely affect other XS code.
7325
7326 A call to L</DECLARATION_FOR_LC_NUMERIC_MANIPULATION> must have been made to
7327 declare at compile time a private variable used by this macro.  This macro
7328 should be called as a single statement, not an expression, but with an empty
7329 argument list, like this:
7330
7331  {
7332     DECLARATION_FOR_LC_NUMERIC_MANIPULATION;
7333      ...
7334     STORE_LC_NUMERIC_SET_TO_NEEDED();
7335      ...
7336     RESTORE_LC_NUMERIC();
7337      ...
7338  }
7339
7340 On threaded perls not operating with thread-safe functionality, this macro uses
7341 a mutex to force a critical section.  Therefore the matching RESTORE should be
7342 close by, and guaranteed to be called; see L</WITH_LC_NUMERIC_SET_TO_NEEDED>
7343 for a more contained way to ensure that.
7344
7345 =for apidoc Am|void|STORE_LC_NUMERIC_SET_TO_NEEDED_IN|bool in_lc_numeric
7346
7347 Same as L</STORE_LC_NUMERIC_SET_TO_NEEDED> with in_lc_numeric provided
7348 as the precalculated value of C<IN_LC(LC_NUMERIC)>. It is the caller's
7349 responsibility to ensure that the status of C<PL_compiling> and C<PL_hints>
7350 cannot have changed since the precalculation.
7351
7352 =for apidoc Am|void|RESTORE_LC_NUMERIC
7353
7354 This is used in conjunction with one of the macros
7355 L</STORE_LC_NUMERIC_SET_TO_NEEDED>
7356 and L</STORE_LC_NUMERIC_FORCE_TO_UNDERLYING> to properly restore the
7357 C<LC_NUMERIC> state.
7358
7359 A call to L</DECLARATION_FOR_LC_NUMERIC_MANIPULATION> must have been made to
7360 declare at compile time a private variable used by this macro and the two
7361 C<STORE> ones.  This macro should be called as a single statement, not an
7362 expression, but with an empty argument list, like this:
7363
7364  {
7365     DECLARATION_FOR_LC_NUMERIC_MANIPULATION;
7366      ...
7367     RESTORE_LC_NUMERIC();
7368      ...
7369  }
7370
7371 =for apidoc Am|void|WITH_LC_NUMERIC_SET_TO_NEEDED|block
7372
7373 This macro invokes the supplied statement or block within the context
7374 of a L</STORE_LC_NUMERIC_SET_TO_NEEDED> .. L</RESTORE_LC_NUMERIC> pair
7375 if required, so eg:
7376
7377   WITH_LC_NUMERIC_SET_TO_NEEDED(
7378     SNPRINTF_G(fv, ebuf, sizeof(ebuf), precis)
7379   );
7380
7381 is equivalent to:
7382
7383   {
7384 #ifdef USE_LOCALE_NUMERIC
7385     DECLARATION_FOR_LC_NUMERIC_MANIPULATION;
7386     STORE_LC_NUMERIC_SET_TO_NEEDED();
7387 #endif
7388     SNPRINTF_G(fv, ebuf, sizeof(ebuf), precis);
7389 #ifdef USE_LOCALE_NUMERIC
7390     RESTORE_LC_NUMERIC();
7391 #endif
7392   }
7393
7394 =for apidoc Am|void|WITH_LC_NUMERIC_SET_TO_NEEDED_IN|bool in_lc_numeric|block
7395
7396 Same as L</WITH_LC_NUMERIC_SET_TO_NEEDED> with in_lc_numeric provided
7397 as the precalculated value of C<IN_LC(LC_NUMERIC)>. It is the caller's
7398 responsibility to ensure that the status of C<PL_compiling> and C<PL_hints>
7399 cannot have changed since the precalculation.
7400
7401 =cut
7402
7403 */
7404
7405 /* If the underlying numeric locale has a non-dot decimal point or has a
7406  * non-empty floating point thousands separator, the current locale is instead
7407  * generally kept in the C locale instead of that underlying locale.  The
7408  * current status is known by looking at two words.  One is non-zero if the
7409  * current numeric locale is the standard C/POSIX one or is indistinguishable
7410  * from C.  The other is non-zero if the current locale is the underlying
7411  * locale.  Both can be non-zero if, as often happens, the underlying locale is
7412  * C or indistinguishable from it.
7413  *
7414  * khw believes the reason for the variables instead of the bits in a single
7415  * word is to avoid having to have masking instructions. */
7416
7417 #  define NOT_IN_NUMERIC_STANDARD_ (! PL_numeric_standard)
7418
7419 /* We can lock the category to stay in the C locale, making requests to the
7420  * contrary be noops, in the dynamic scope by setting PL_numeric_standard to 2.
7421  * */
7422 #  define NOT_IN_NUMERIC_UNDERLYING_                                        \
7423                     (! PL_numeric_underlying && PL_numeric_standard < 2)
7424
7425 #  define DECLARATION_FOR_LC_NUMERIC_MANIPULATION                           \
7426     void (*_restore_LC_NUMERIC_function)(pTHX) = NULL
7427
7428 #  define STORE_LC_NUMERIC_SET_TO_NEEDED_IN(in)                             \
7429         STMT_START {                                                        \
7430             bool _in_lc_numeric = (in);                                     \
7431             LC_NUMERIC_LOCK(                                                \
7432                     (   (  _in_lc_numeric && NOT_IN_NUMERIC_UNDERLYING_)    \
7433                      || (! _in_lc_numeric && NOT_IN_NUMERIC_STANDARD_)));   \
7434             if (_in_lc_numeric) {                                           \
7435                 if (NOT_IN_NUMERIC_UNDERLYING_) {                           \
7436                     Perl_set_numeric_underlying(aTHX);                      \
7437                     _restore_LC_NUMERIC_function                            \
7438                                             = &Perl_set_numeric_standard;   \
7439                 }                                                           \
7440             }                                                               \
7441             else {                                                          \
7442                 if (NOT_IN_NUMERIC_STANDARD_) {                             \
7443                     Perl_set_numeric_standard(aTHX);                        \
7444                     _restore_LC_NUMERIC_function                            \
7445                                             = &Perl_set_numeric_underlying; \
7446                 }                                                           \
7447             }                                                               \
7448         } STMT_END
7449
7450 #  define STORE_LC_NUMERIC_SET_TO_NEEDED() \
7451         STORE_LC_NUMERIC_SET_TO_NEEDED_IN(IN_LC(LC_NUMERIC))
7452
7453 #  define RESTORE_LC_NUMERIC()                                              \
7454         STMT_START {                                                        \
7455             if (_restore_LC_NUMERIC_function) {                             \
7456                 _restore_LC_NUMERIC_function(aTHX);                         \
7457             }                                                               \
7458             LC_NUMERIC_UNLOCK;                                              \
7459         } STMT_END
7460
7461 /* The next two macros should be rarely used, and only after being sure that
7462  * this is what is needed */
7463 #  define SET_NUMERIC_STANDARD()                                            \
7464         STMT_START {                                                        \
7465             DEBUG_Lv(PerlIO_printf(Perl_debug_log,                          \
7466                                "%s: %d: lc_numeric standard=%d\n",          \
7467                                 __FILE__, __LINE__, PL_numeric_standard));  \
7468             if (UNLIKELY(NOT_IN_NUMERIC_STANDARD_)) {                       \
7469                 Perl_set_numeric_standard(aTHX);                            \
7470             }                                                               \
7471             DEBUG_Lv(PerlIO_printf(Perl_debug_log,                          \
7472                                  "%s: %d: lc_numeric standard=%d\n",        \
7473                                  __FILE__, __LINE__, PL_numeric_standard)); \
7474         } STMT_END
7475
7476 #  define SET_NUMERIC_UNDERLYING()                                          \
7477         STMT_START {                                                        \
7478           /*assert(PL_locale_mutex_depth > 0);*/                            \
7479             if (NOT_IN_NUMERIC_UNDERLYING_) {                               \
7480                 Perl_set_numeric_underlying(aTHX);                          \
7481             }                                                               \
7482         } STMT_END
7483
7484 /* The rest of these LC_NUMERIC macros toggle to one or the other state, with
7485  * the RESTORE_foo ones called to switch back, but only if need be */
7486 #  define STORE_LC_NUMERIC_SET_STANDARD()                                   \
7487         STMT_START {                                                        \
7488             LC_NUMERIC_LOCK(NOT_IN_NUMERIC_STANDARD_);                      \
7489             if (NOT_IN_NUMERIC_STANDARD_) {                                 \
7490                 _restore_LC_NUMERIC_function = &Perl_set_numeric_underlying;\
7491                 Perl_set_numeric_standard(aTHX);                            \
7492             }                                                               \
7493         } STMT_END
7494
7495 /* Rarely, we want to change to the underlying locale even outside of 'use
7496  * locale'.  This is principally in the POSIX:: functions */
7497 #  define STORE_LC_NUMERIC_FORCE_TO_UNDERLYING()                            \
7498         STMT_START {                                                        \
7499             LC_NUMERIC_LOCK(NOT_IN_NUMERIC_UNDERLYING_);                    \
7500             if (NOT_IN_NUMERIC_UNDERLYING_) {                               \
7501                 Perl_set_numeric_underlying(aTHX);                          \
7502                 _restore_LC_NUMERIC_function = &Perl_set_numeric_standard;  \
7503             }                                                               \
7504         } STMT_END
7505
7506 /* Lock/unlock changes to LC_NUMERIC.  This needs to be recursively callable.
7507  * The highest level caller is responsible for making sure that LC_NUMERIC is
7508  * set to a locale with a dot radix character.  These deliberately don't check
7509  * for the internal state being so, as they can be called from code that is not
7510  * party to the internal conventions, namely 'version' (vutil.c).
7511  * PL_numeric_standard changing doesn't affect anything about what locale is in
7512  * effect, etc.  [perl #128207] */
7513 #  define DISABLE_LC_NUMERIC_CHANGES()                                      \
7514         STMT_START {                                                        \
7515             DEBUG_Lv(PerlIO_printf(Perl_debug_log,                          \
7516                     "%s: %d: lc_numeric_standard now locked to depth %d\n", \
7517                     __FILE__, __LINE__, PL_numeric_standard));              \
7518             PL_numeric_standard++;                                          \
7519         } STMT_END
7520
7521 #  define REENABLE_LC_NUMERIC_CHANGES()                                     \
7522         STMT_START {                                                        \
7523             if (PL_numeric_standard > 1) {                                  \
7524                 PL_numeric_standard--;                                      \
7525             }                                                               \
7526             else {                                                          \
7527                 assert(0);                                                  \
7528             }                                                               \
7529             DEBUG_Lv(PerlIO_printf(Perl_debug_log,                          \
7530                                    "%s: %d: ",  __FILE__, __LINE__);        \
7531                     if (PL_numeric_standard <= 1)                           \
7532                         PerlIO_printf(Perl_debug_log,                       \
7533                                       "lc_numeric_standard now unlocked\n");\
7534                     else PerlIO_printf(Perl_debug_log,                      \
7535                      "lc_numeric_standard lock decremented to depth %d\n",  \
7536                                                      PL_numeric_standard););\
7537         } STMT_END
7538
7539 /* Essentially synonyms for the above.  The LOCK asserts at the top level that
7540  * we are in a locale equivalent to C.  By including the top level, this can be
7541  * recursively called from chains which include DISABLE_LC_NUMERIC_CHANGES().
7542  * */
7543 #  define LOCK_LC_NUMERIC_STANDARD()                                        \
7544         STMT_START {                                                        \
7545             assert(PL_numeric_standard > 0 || PL_numeric_standard);         \
7546             DISABLE_LC_NUMERIC_CHANGES();                                   \
7547         } STMT_END
7548 #  define UNLOCK_LC_NUMERIC_STANDARD()  REENABLE_LC_NUMERIC_CHANGES()
7549
7550 #  define WITH_LC_NUMERIC_SET_TO_NEEDED_IN(in_lc_numeric, block)            \
7551         STMT_START {                                                        \
7552             DECLARATION_FOR_LC_NUMERIC_MANIPULATION;                        \
7553             STORE_LC_NUMERIC_SET_TO_NEEDED_IN(in_lc_numeric);               \
7554             block;                                                          \
7555             RESTORE_LC_NUMERIC();                                           \
7556         } STMT_END
7557
7558 #  define WITH_LC_NUMERIC_SET_TO_NEEDED(block) \
7559         WITH_LC_NUMERIC_SET_TO_NEEDED_IN(IN_LC(LC_NUMERIC), block)
7560
7561 #else /* !USE_LOCALE_NUMERIC */
7562
7563 #  define SET_NUMERIC_STANDARD()
7564 #  define SET_NUMERIC_UNDERLYING()
7565 #  define IS_NUMERIC_RADIX(a, b)                (0)
7566 #  define DECLARATION_FOR_LC_NUMERIC_MANIPULATION  dNOOP
7567 #  define STORE_LC_NUMERIC_SET_STANDARD()
7568 #  define STORE_LC_NUMERIC_FORCE_TO_UNDERLYING()
7569 #  define STORE_LC_NUMERIC_SET_TO_NEEDED_IN(in_lc_numeric)
7570 #  define STORE_LC_NUMERIC_SET_TO_NEEDED()
7571 #  define RESTORE_LC_NUMERIC()
7572 #  define LOCK_LC_NUMERIC_STANDARD()
7573 #  define UNLOCK_LC_NUMERIC_STANDARD()
7574 #  define DISABLE_LC_NUMERIC_CHANGES()
7575 #  define REENABLE_LC_NUMERIC_CHANGES()
7576 #  define WITH_LC_NUMERIC_SET_TO_NEEDED_IN(in_lc_numeric, block) \
7577     STMT_START { block; } STMT_END
7578 #  define WITH_LC_NUMERIC_SET_TO_NEEDED(block) \
7579     STMT_START { block; } STMT_END
7580
7581 #endif /* !USE_LOCALE_NUMERIC */
7582
7583 #ifdef USE_LOCALE_THREADS
7584 #  define ENV_LOCK            PERL_WRITE_LOCK(&PL_env_mutex)
7585 #  define ENV_UNLOCK          PERL_WRITE_UNLOCK(&PL_env_mutex)
7586 #  define ENV_READ_LOCK       PERL_READ_LOCK(&PL_env_mutex)
7587 #  define ENV_READ_UNLOCK     PERL_READ_UNLOCK(&PL_env_mutex)
7588 #  define ENV_INIT            PERL_RW_MUTEX_INIT(&PL_env_mutex)
7589 #  define ENV_TERM            PERL_RW_MUTEX_DESTROY(&PL_env_mutex)
7590
7591    /* On platforms where the static buffer contained in getenv() is per-thread
7592     * rather than process-wide, another thread executing a getenv() at the same
7593     * time won't destroy ours before we have copied the result safely away and
7594     * unlocked the mutex.  On such platforms (which is most), we can have many
7595     * readers of the environment at the same time. */
7596 #  ifdef GETENV_PRESERVES_OTHER_THREAD
7597 #    define GETENV_LOCK    ENV_READ_LOCK
7598 #    define GETENV_UNLOCK  ENV_READ_UNLOCK
7599 #  else
7600      /* If, on the other hand, another thread could zap our getenv() return, we
7601       * need to keep them from executing until we are done */
7602 #    define GETENV_LOCK    ENV_LOCK
7603 #    define GETENV_UNLOCK  ENV_UNLOCK
7604 #  endif
7605 #else
7606 #  define ENV_LOCK        NOOP
7607 #  define ENV_UNLOCK      NOOP
7608 #  define ENV_READ_LOCK   NOOP
7609 #  define ENV_READ_UNLOCK NOOP
7610 #  define ENV_INIT        NOOP
7611 #  define ENV_TERM        NOOP
7612 #  define GETENV_LOCK     NOOP
7613 #  define GETENV_UNLOCK   NOOP
7614 #endif
7615
7616 /* Some critical sections need to lock both the locale and the environment from
7617  * changing, while allowing for any number of readers.  To avoid deadlock, this
7618  * is always done in the same order.  These should always be invoked, like all
7619  * locks really, at such a low level that its just a libc call that is wrapped,
7620  * so as to prevent recursive calls which could deadlock. */
7621 #define ENVr_LOCALEr_LOCK                                               \
7622             STMT_START { LOCALE_READ_LOCK; ENV_READ_LOCK; } STMT_END
7623 #define ENVr_LOCALEr_UNLOCK                                             \
7624         STMT_START { ENV_READ_UNLOCK; LOCALE_READ_UNLOCK; } STMT_END
7625
7626 /* These time-related functions all requre that the environment and locale
7627  * don't change while they are executing (at least in glibc; this appears to be
7628  * contrary to the POSIX standard).  tzset() writes global variables, so
7629  * always needs to have write locking.  ctime, localtime, mktime, and strftime
7630  * effectively call it, so they too need exclusive access.  The rest need to
7631  * have exclusive locking as well so that they can copy the contents of the
7632  * returned static buffer before releasing the lock.  That leaves asctime and
7633  * gmtime.  There may be reentrant versions of these available on the platform
7634  * which don't require write locking.
7635  */
7636 #ifdef PERL_REENTR_USING_ASCTIME_R
7637 #  define ASCTIME_LOCK     ENVr_LOCALEr_LOCK
7638 #  define ASCTIME_UNLOCK   ENVr_LOCALEr_UNLOCK
7639 #else
7640 #  define ASCTIME_LOCK     gwENVr_LOCALEr_LOCK
7641 #  define ASCTIME_UNLOCK   gwENVr_LOCALEr_UNLOCK
7642 #endif
7643
7644 #define CTIME_LOCK         gwENVr_LOCALEr_LOCK
7645 #define CTIME_UNLOCK       gwENVr_LOCALEr_UNLOCK
7646
7647 #ifdef PERL_REENTR_USING_GMTIME_R
7648 #  define GMTIME_LOCK      ENVr_LOCALEr_LOCK
7649 #  define GMTIME_UNLOCK    ENVr_LOCALEr_UNLOCK
7650 #else
7651 #  define GMTIME_LOCK      gwENVr_LOCALEr_LOCK
7652 #  define GMTIME_UNLOCK    gwENVr_LOCALEr_UNLOCK
7653 #endif
7654
7655 #define LOCALTIME_LOCK     gwENVr_LOCALEr_LOCK
7656 #define LOCALTIME_UNLOCK   gwENVr_LOCALEr_UNLOCK
7657 #define MKTIME_LOCK        gwENVr_LOCALEr_LOCK
7658 #define MKTIME_UNLOCK      gwENVr_LOCALEr_UNLOCK
7659 #define TZSET_LOCK         gwENVr_LOCALEr_LOCK
7660 #define TZSET_UNLOCK       gwENVr_LOCALEr_UNLOCK
7661
7662 /* Similiarly, these functions need a constant environment and/or locale.  And
7663  * some have a buffer that is shared with another thread executing the same or
7664  * a related call.  A mutex could be created for each class, but for now, share
7665  * the ENV mutex with everything, as none probably gets called so much that
7666  * performance would suffer by a thread being locked out by another thread that
7667  * could have used a different mutex.
7668  *
7669  * But, create a different macro name just to indicate the ones that don't
7670  * actually depend on the environment, but are using its mutex for want of a
7671  * better one */
7672 #define gwLOCALEr_LOCK              gwENVr_LOCALEr_LOCK
7673 #define gwLOCALEr_UNLOCK            gwENVr_LOCALEr_UNLOCK
7674
7675 #ifdef PERL_REENTR_USING_GETHOSTBYADDR_R
7676 #  define GETHOSTBYADDR_LOCK        ENVr_LOCALEr_LOCK
7677 #  define GETHOSTBYADDR_UNLOCK      ENVr_LOCALEr_UNLOCK
7678 #else
7679 #  define GETHOSTBYADDR_LOCK        gwENVr_LOCALEr_LOCK
7680 #  define GETHOSTBYADDR_UNLOCK      gwENVr_LOCALEr_UNLOCK
7681 #endif
7682 #ifdef PERL_REENTR_USING_GETHOSTBYNAME_R
7683 #  define GETHOSTBYNAME_LOCK        ENVr_LOCALEr_LOCK
7684 #  define GETHOSTBYNAME_UNLOCK      ENVr_LOCALEr_UNLOCK
7685 #else
7686 #  define GETHOSTBYNAME_LOCK        gwENVr_LOCALEr_LOCK
7687 #  define GETHOSTBYNAME_UNLOCK      gwENVr_LOCALEr_UNLOCK
7688 #endif
7689 #ifdef PERL_REENTR_USING_GETNETBYADDR_R
7690 #  define GETNETBYADDR_LOCK         LOCALE_READ_LOCK
7691 #  define GETNETBYADDR_UNLOCK       LOCALE_READ_UNLOCK
7692 #else
7693 #  define GETNETBYADDR_LOCK         gwLOCALEr_LOCK
7694 #  define GETNETBYADDR_UNLOCK       gwLOCALEr_UNLOCK
7695 #endif
7696 #ifdef PERL_REENTR_USING_GETNETBYNAME_R
7697 #  define GETNETBYNAME_LOCK         LOCALE_READ_LOCK
7698 #  define GETNETBYNAME_UNLOCK       LOCALE_READ_UNLOCK
7699 #else
7700 #  define GETNETBYNAME_LOCK         gwLOCALEr_LOCK
7701 #  define GETNETBYNAME_UNLOCK       gwLOCALEr_UNLOCK
7702 #endif
7703 #ifdef PERL_REENTR_USING_GETPROTOBYNAME_R
7704 #  define GETPROTOBYNAME_LOCK       LOCALE_READ_LOCK
7705 #  define GETPROTOBYNAME_UNLOCK     LOCALE_READ_UNLOCK
7706 #else
7707 #  define GETPROTOBYNAME_LOCK       gwLOCALEr_LOCK
7708 #  define GETPROTOBYNAME_UNLOCK     gwLOCALEr_UNLOCK
7709 #endif
7710 #ifdef PERL_REENTR_USING_GETPROTOBYNUMBER_R
7711 #  define GETPROTOBYNUMBER_LOCK     LOCALE_READ_LOCK
7712 #  define GETPROTOBYNUMBER_UNLOCK   LOCALE_READ_UNLOCK
7713 #else
7714 #  define GETPROTOBYNUMBER_LOCK     gwLOCALEr_LOCK
7715 #  define GETPROTOBYNUMBER_UNLOCK   gwLOCALEr_UNLOCK
7716 #endif
7717 #ifdef PERL_REENTR_USING_GETPROTOENT_R
7718 #  define GETPROTOENT_LOCK          LOCALE_READ_LOCK
7719 #  define GETPROTOENT_UNLOCK        LOCALE_READ_UNLOCK
7720 #else
7721 #  define GETPROTOENT_LOCK          gwLOCALEr_LOCK
7722 #  define GETPROTOENT_UNLOCK        gwLOCALEr_UNLOCK
7723 #endif
7724 #ifdef PERL_REENTR_USING_GETPWNAM_R
7725 #  define GETPWNAM_LOCK             LOCALE_READ_LOCK
7726 #  define GETPWNAM_UNLOCK           LOCALE_READ_UNLOCK
7727 #else
7728 #  define GETPWNAM_LOCK             gwLOCALEr_LOCK
7729 #  define GETPWNAM_UNLOCK           gwLOCALEr_UNLOCK
7730 #endif
7731 #ifdef PERL_REENTR_USING_GETPWUID_R
7732 #  define GETPWUID_LOCK             LOCALE_READ_LOCK
7733 #  define GETPWUID_UNLOCK           LOCALE_READ_UNLOCK
7734 #else
7735 #  define GETPWUID_LOCK             gwLOCALEr_LOCK
7736 #  define GETPWUID_UNLOCK           gwLOCALEr_UNLOCK
7737 #endif
7738 #ifdef PERL_REENTR_USING_GETSERVBYNAME_R
7739 #  define GETSERVBYNAME_LOCK        LOCALE_READ_LOCK
7740 #  define GETSERVBYNAME_UNLOCK      LOCALE_READ_UNLOCK
7741 #else
7742 #  define GETSERVBYNAME_LOCK        gwLOCALEr_LOCK
7743 #  define GETSERVBYNAME_UNLOCK      gwLOCALEr_UNLOCK
7744 #endif
7745 #ifdef PERL_REENTR_USING_GETSERVBYPORT_R
7746 #  define GETSERVBYPORT_LOCK        LOCALE_READ_LOCK
7747 #  define GETSERVBYPORT_UNLOCK      LOCALE_READ_UNLOCK
7748 #else
7749 #  define GETSERVBYPORT_LOCK        gwLOCALEr_LOCK
7750 #  define GETSERVBYPORT_UNLOCK      gwLOCALEr_UNLOCK
7751 #endif
7752 #ifdef PERL_REENTR_USING_GETSERVENT_R
7753 #  define GETSERVENT_LOCK           LOCALE_READ_LOCK
7754 #  define GETSERVENT_UNLOCK         LOCALE_READ_UNLOCK
7755 #else
7756 #  define GETSERVENT_LOCK           gwLOCALEr_LOCK
7757 #  define GETSERVENT_UNLOCK         gwLOCALEr_UNLOCK
7758 #endif
7759 #ifdef PERL_REENTR_USING_GETSPNAM_R
7760 #  define GETSPNAM_LOCK             LOCALE_READ_LOCK
7761 #  define GETSPNAM_UNLOCK           LOCALE_READ_UNLOCK
7762 #else
7763 #  define GETSPNAM_LOCK             gwLOCALEr_LOCK
7764 #  define GETSPNAM_UNLOCK           gwLOCALEr_UNLOCK
7765 #endif
7766
7767 #define STRFMON_LOCK        LC_MONETARY_LOCK
7768 #define STRFMON_UNLOCK      LC_MONETARY_UNLOCK
7769
7770 /* End of locale/env synchronization */
7771
7772 #ifndef PERL_NO_INLINE_FUNCTIONS
7773 /* Static inline funcs that depend on includes and declarations above.
7774    Some of these reference functions in the perl object files, and some
7775    compilers aren't smart enough to eliminate unused static inline
7776    functions, so including this file in source code can cause link errors
7777    even if the source code uses none of the functions. Hence including these
7778    can be suppressed by setting PERL_NO_INLINE_FUNCTIONS. Doing this will
7779    (obviously) result in unworkable XS code, but allows simple probing code
7780    to continue to work, because it permits tests to include the perl headers
7781    for definitions without creating a link dependency on the perl library
7782    (which may not exist yet).
7783 */
7784
7785 START_EXTERN_C
7786
7787 #  include "perlstatic.h"
7788 #  include "inline.h"
7789 #  include "sv_inline.h"
7790
7791 END_EXTERN_C
7792
7793 #endif
7794
7795 /*
7796
7797 =for apidoc_section $numeric
7798
7799 =for apidoc AmTR|NV|Strtod|NN const char * const s|NULLOK char ** e
7800
7801 This is a synonym for L</my_strtod>.
7802
7803 =for apidoc AmTR|NV|Strtol|NN const char * const s|NULLOK char ** e|int base
7804
7805 Platform and configuration independent C<strtol>.  This expands to the
7806 appropriate C<strotol>-like function based on the platform and F<Configure>
7807 options>.  For example it could expand to C<strtoll> or C<strtoq> instead of
7808 C<strtol>.
7809
7810 =for apidoc AmTR|NV|Strtoul|NN const char * const s|NULLOK char ** e|int base
7811
7812 Platform and configuration independent C<strtoul>.  This expands to the
7813 appropriate C<strotoul>-like function based on the platform and F<Configure>
7814 options>.  For example it could expand to C<strtoull> or C<strtouq> instead of
7815 C<strtoul>.
7816
7817 =cut
7818
7819 */
7820
7821 #define Strtod                          my_strtod
7822
7823 #if    defined(HAS_STRTOD)                                          \
7824    ||  defined(USE_QUADMATH)                                        \
7825    || (defined(HAS_STRTOLD) && defined(HAS_LONG_DOUBLE)             \
7826                             && defined(USE_LONG_DOUBLE))
7827 #  define Perl_strtod   Strtod
7828 #endif
7829
7830 #if !defined(Strtol) && defined(USE_64_BIT_INT) && defined(IV_IS_QUAD) && \
7831         (QUADKIND == QUAD_IS_LONG_LONG || QUADKIND == QUAD_IS___INT64)
7832 #    ifdef __hpux
7833 #        define strtoll __strtoll       /* secret handshake */
7834 #    endif
7835 #    if defined(WIN64) && defined(_MSC_VER)
7836 #        define strtoll _strtoi64       /* secret handshake */
7837 #    endif
7838 #   if !defined(Strtol) && defined(HAS_STRTOLL)
7839 #       define Strtol   strtoll
7840 #   endif
7841 #    if !defined(Strtol) && defined(HAS_STRTOQ)
7842 #       define Strtol   strtoq
7843 #    endif
7844 /* is there atoq() anywhere? */
7845 #endif
7846 #if !defined(Strtol) && defined(HAS_STRTOL)
7847 #   define Strtol       strtol
7848 #endif
7849 #ifndef Atol
7850 /* It would be more fashionable to use Strtol() to define atol()
7851  * (as is done for Atoul(), see below) but for backward compatibility
7852  * we just assume atol(). */
7853 #   if defined(USE_64_BIT_INT) && defined(IV_IS_QUAD) && defined(HAS_ATOLL) && \
7854         (QUADKIND == QUAD_IS_LONG_LONG || QUADKIND == QUAD_IS___INT64)
7855 #    ifdef WIN64
7856 #       define atoll    _atoi64         /* secret handshake */
7857 #    endif
7858 #       define Atol     atoll
7859 #   else
7860 #       define Atol     atol
7861 #   endif
7862 #endif
7863
7864 #if !defined(Strtoul) && defined(USE_64_BIT_INT) && defined(UV_IS_QUAD) && \
7865         (QUADKIND == QUAD_IS_LONG_LONG || QUADKIND == QUAD_IS___INT64)
7866 #    ifdef __hpux
7867 #        define strtoull __strtoull     /* secret handshake */
7868 #    endif
7869 #    if defined(WIN64) && defined(_MSC_VER)
7870 #        define strtoull _strtoui64     /* secret handshake */
7871 #    endif
7872 #    if !defined(Strtoul) && defined(HAS_STRTOULL)
7873 #       define Strtoul  strtoull
7874 #    endif
7875 #    if !defined(Strtoul) && defined(HAS_STRTOUQ)
7876 #       define Strtoul  strtouq
7877 #    endif
7878 /* is there atouq() anywhere? */
7879 #endif
7880 #if !defined(Strtoul) && defined(HAS_STRTOUL)
7881 #   define Strtoul      strtoul
7882 #endif
7883 #if !defined(Strtoul) && defined(HAS_STRTOL) /* Last resort. */
7884 #   define Strtoul(s, e, b)     strchr((s), '-') ? ULONG_MAX : (unsigned long)strtol((s), (e), (b))
7885 #endif
7886 #ifndef Atoul
7887 #   define Atoul(s)     Strtoul(s, NULL, 10)
7888 #endif
7889
7890 #define grok_bin(s,lp,fp,rp)                                                \
7891                     grok_bin_oct_hex(s, lp, fp, rp, 1, CC_BINDIGIT_, 'b')
7892 #define grok_oct(s,lp,fp,rp)                                                \
7893                     (*(fp) |= PERL_SCAN_DISALLOW_PREFIX,                    \
7894                     grok_bin_oct_hex(s, lp, fp, rp, 3, CC_OCTDIGIT_, '\0'))
7895 #define grok_hex(s,lp,fp,rp)                                                \
7896                     grok_bin_oct_hex(s, lp, fp, rp, 4, CC_XDIGIT_, 'x')
7897
7898 #ifndef PERL_SCRIPT_MODE
7899 #define PERL_SCRIPT_MODE "r"
7900 #endif
7901
7902 /* not used. Kept as a NOOP for backcompat */
7903 #define PERL_STACK_OVERFLOW_CHECK()  NOOP
7904
7905 /*
7906  * Some nonpreemptive operating systems find it convenient to
7907  * check for asynchronous conditions after each op execution.
7908  * Keep this check simple, or it may slow down execution
7909  * massively.
7910  */
7911
7912 #ifndef PERL_ASYNC_CHECK
7913 #define PERL_ASYNC_CHECK() if (UNLIKELY(PL_sig_pending)) PL_signalhook(aTHX)
7914 #endif
7915
7916 /*
7917  * On some operating systems, a memory allocation may succeed,
7918  * but put the process too close to the system's comfort limit.
7919  * In this case, PERL_ALLOC_CHECK frees the pointer and sets
7920  * it to NULL.
7921  */
7922 #ifndef PERL_ALLOC_CHECK
7923 #define PERL_ALLOC_CHECK(p)  NOOP
7924 #endif
7925
7926 #ifdef HAS_SEM
7927 #   include <sys/ipc.h>
7928 #   include <sys/sem.h>
7929 #   ifndef HAS_UNION_SEMUN      /* Provide the union semun. */
7930     union semun {
7931         int             val;
7932         struct semid_ds *buf;
7933         unsigned short  *array;
7934     };
7935 #   endif
7936 #   ifdef USE_SEMCTL_SEMUN
7937 #       ifdef IRIX32_SEMUN_BROKEN_BY_GCC
7938             union gccbug_semun {
7939                 int             val;
7940                 struct semid_ds *buf;
7941                 unsigned short  *array;
7942                 char            __dummy[5];
7943             };
7944 #           define semun gccbug_semun
7945 #       endif
7946 #       define Semctl(id, num, cmd, semun) semctl(id, num, cmd, semun)
7947 #   elif defined(USE_SEMCTL_SEMID_DS)
7948 #           ifdef EXTRA_F_IN_SEMUN_BUF
7949 #               define Semctl(id, num, cmd, semun) semctl(id, num, cmd, semun.buff)
7950 #           else
7951 #               define Semctl(id, num, cmd, semun) semctl(id, num, cmd, semun.buf)
7952 #           endif
7953 #   endif
7954 #endif
7955
7956 /*
7957  * Boilerplate macros for initializing and accessing interpreter-local
7958  * data from C.  All statics in extensions should be reworked to use
7959  * this, if you want to make the extension thread-safe.  See
7960  * ext/XS/APItest/APItest.xs for an example of the use of these macros,
7961  * and perlxs.pod for more.
7962  *
7963  * Code that uses these macros is responsible for the following:
7964  * 1. #define MY_CXT_KEY to a unique string, e.g.
7965  *    "DynaLoader::_guts" XS_VERSION
7966  *    XXX in the current implementation, this string is ignored.
7967  * 2. Declare a typedef named my_cxt_t that is a structure that contains
7968  *    all the data that needs to be interpreter-local that perl controls.  This
7969  *    doesn't include things that libc controls, such as the uselocale object
7970  *    in Configurations that use it.
7971  * 3. Use the START_MY_CXT macro after the declaration of my_cxt_t.
7972  * 4. Use the MY_CXT_INIT macro such that it is called exactly once
7973  *    (typically put in the BOOT: section).
7974  * 5. Use the members of the my_cxt_t structure everywhere as
7975  *    MY_CXT.member.
7976  * 6. Use the dMY_CXT macro (a declaration) in all the functions that
7977  *    access MY_CXT.
7978  */
7979
7980 #if defined(MULTIPLICITY)
7981
7982 /* START_MY_CXT must appear in all extensions that define a my_cxt_t structure,
7983  * right after the definition (i.e. at file scope).  The non-threads
7984  * case below uses it to declare the data as static. */
7985 #    define START_MY_CXT static int my_cxt_index = -1;
7986 #    define MY_CXT_INDEX my_cxt_index
7987 #    define MY_CXT_INIT_ARG &my_cxt_index
7988
7989 /* Creates and zeroes the per-interpreter data.
7990  * (We allocate my_cxtp in a Perl SV so that it will be released when
7991  * the interpreter goes away.) */
7992 #  define MY_CXT_INIT \
7993         my_cxt_t *my_cxtp = \
7994             (my_cxt_t*)Perl_my_cxt_init(aTHX_ MY_CXT_INIT_ARG, sizeof(my_cxt_t)); \
7995         PERL_UNUSED_VAR(my_cxtp)
7996 #  define MY_CXT_INIT_INTERP(my_perl) \
7997         my_cxt_t *my_cxtp = \
7998             (my_cxt_t*)Perl_my_cxt_init(my_perl, MY_CXT_INIT_ARG, sizeof(my_cxt_t)); \
7999         PERL_UNUSED_VAR(my_cxtp)
8000
8001 /* This declaration should be used within all functions that use the
8002  * interpreter-local data. */
8003 #  define dMY_CXT       \
8004         my_cxt_t *my_cxtp = (my_cxt_t *)PL_my_cxt_list[MY_CXT_INDEX]
8005 #  define dMY_CXT_INTERP(my_perl)       \
8006         my_cxt_t *my_cxtp = (my_cxt_t *)(my_perl)->Imy_cxt_list[MY_CXT_INDEX]
8007
8008 /* Clones the per-interpreter data. */
8009 #  define MY_CXT_CLONE \
8010         my_cxt_t *my_cxtp = (my_cxt_t*)SvPVX(newSV(sizeof(my_cxt_t)-1));\
8011         void * old_my_cxtp = PL_my_cxt_list[MY_CXT_INDEX];              \
8012         PL_my_cxt_list[MY_CXT_INDEX] = my_cxtp;                         \
8013         Copy(old_my_cxtp, my_cxtp, 1, my_cxt_t);
8014
8015
8016
8017 /* This macro must be used to access members of the my_cxt_t structure.
8018  * e.g. MY_CXT.some_data */
8019 #  define MY_CXT                (*my_cxtp)
8020
8021 /* Judicious use of these macros can reduce the number of times dMY_CXT
8022  * is used.  Use is similar to pTHX, aTHX etc. */
8023 #  define pMY_CXT       my_cxt_t *my_cxtp
8024 #  define pMY_CXT_      pMY_CXT,
8025 #  define _pMY_CXT      ,pMY_CXT
8026 #  define aMY_CXT       my_cxtp
8027 #  define aMY_CXT_      aMY_CXT,
8028 #  define _aMY_CXT      ,aMY_CXT
8029
8030 #else /* MULTIPLICITY */
8031 #  define START_MY_CXT          static my_cxt_t my_cxt;
8032 #  define dMY_CXT               dNOOP
8033 #  define dMY_CXT_INTERP(my_perl) dNOOP
8034 #  define MY_CXT_INIT           NOOP
8035 #  define MY_CXT_CLONE          NOOP
8036 #  define MY_CXT                my_cxt
8037
8038 #  define pMY_CXT               void
8039 #  define pMY_CXT_
8040 #  define _pMY_CXT
8041 #  define aMY_CXT
8042 #  define aMY_CXT_
8043 #  define _aMY_CXT
8044
8045 #endif /* !defined(MULTIPLICITY) */
8046
8047 #ifdef I_FCNTL
8048 #  include <fcntl.h>
8049 #endif
8050
8051 #ifdef __Lynx__
8052 #  include <fcntl.h>
8053 #endif
8054
8055 #ifdef __amigaos4__
8056 #  undef FD_CLOEXEC /* a lie in AmigaOS */
8057 #endif
8058
8059 #ifdef I_SYS_FILE
8060 #  include <sys/file.h>
8061 #endif
8062
8063 #if defined(HAS_FLOCK) && !defined(HAS_FLOCK_PROTO)
8064 EXTERN_C int flock(int fd, int op);
8065 #endif
8066
8067 #ifndef O_RDONLY
8068 /* Assume UNIX defaults */
8069 #    define O_RDONLY    0000
8070 #    define O_WRONLY    0001
8071 #    define O_RDWR      0002
8072 #    define O_CREAT     0100
8073 #endif
8074
8075 #ifndef O_BINARY
8076 #  define O_BINARY 0
8077 #endif
8078
8079 #ifndef O_TEXT
8080 #  define O_TEXT 0
8081 #endif
8082
8083 #if O_TEXT != O_BINARY
8084     /* If you have different O_TEXT and O_BINARY and you are a CRLF shop,
8085      * that is, you are somehow DOSish. */
8086 #   if defined(__HAIKU__) || defined(__VOS__) || defined(__CYGWIN__)
8087     /* Haiku has O_TEXT != O_BINARY but O_TEXT and O_BINARY have no effect;
8088      * Haiku is always UNIXoid (LF), not DOSish (CRLF). */
8089     /* VOS has O_TEXT != O_BINARY, and they have effect,
8090      * but VOS always uses LF, never CRLF. */
8091     /* If you have O_TEXT different from your O_BINARY but you still are
8092      * not a CRLF shop. */
8093 #       undef PERLIO_USING_CRLF
8094 #   else
8095     /* If you really are DOSish. */
8096 #      define PERLIO_USING_CRLF 1
8097 #   endif
8098 #endif
8099
8100 #ifdef I_LIBUTIL
8101 #   include <libutil.h>         /* setproctitle() in some FreeBSDs */
8102 #endif
8103
8104 #ifndef EXEC_ARGV_CAST
8105 #define EXEC_ARGV_CAST(x) (char **)x
8106 #endif
8107
8108 #define IS_NUMBER_IN_UV               0x01 /* number within UV range (maybe not
8109                                               int).  value returned in pointed-
8110                                               to UV */
8111 #define IS_NUMBER_GREATER_THAN_UV_MAX 0x02 /* pointed to UV undefined */
8112 #define IS_NUMBER_NOT_INT             0x04 /* saw . or E notation or infnan */
8113 #define IS_NUMBER_NEG                 0x08 /* leading minus sign */
8114 #define IS_NUMBER_INFINITY            0x10 /* this is big */
8115 #define IS_NUMBER_NAN                 0x20 /* this is not */
8116 #define IS_NUMBER_TRAILING            0x40 /* number has trailing trash */
8117
8118 /*
8119 =for apidoc_section $numeric
8120
8121 =for apidoc AmdR|bool|GROK_NUMERIC_RADIX|NN const char **sp|NN const char *send
8122
8123 A synonym for L</grok_numeric_radix>
8124
8125 =cut
8126 */
8127 #define GROK_NUMERIC_RADIX(sp, send) grok_numeric_radix(sp, send)
8128
8129 /* Number scan flags.  All are used for input, the ones used for output are so
8130  * marked */
8131 #define PERL_SCAN_ALLOW_UNDERSCORES   0x01 /* grok_??? accept _ in numbers */
8132 #define PERL_SCAN_DISALLOW_PREFIX     0x02 /* grok_??? reject 0x in hex etc */
8133
8134 /* grok_??? input: ignored; output: found overflow */
8135 #define PERL_SCAN_GREATER_THAN_UV_MAX 0x04
8136
8137 /* grok_??? don't warn about illegal digits.  To preserve total backcompat,
8138  * this isn't set on output if one is found.  Instead, see
8139  * PERL_SCAN_NOTIFY_ILLDIGIT. */
8140 #define PERL_SCAN_SILENT_ILLDIGIT     0x08
8141
8142 #define PERL_SCAN_TRAILING            0x10 /* grok_number_flags() allow trailing
8143                                               and set IS_NUMBER_TRAILING */
8144
8145 /* These are considered experimental, so not exposed publicly */
8146 #if defined(PERL_CORE) || defined(PERL_EXT)
8147 /* grok_??? don't warn about very large numbers which are <= UV_MAX;
8148  * output: found such a number */
8149 #  define PERL_SCAN_SILENT_NON_PORTABLE 0x20
8150
8151 /* If this is set on input, and no illegal digit is found, it will be cleared
8152  * on output; otherwise unchanged */
8153 #  define PERL_SCAN_NOTIFY_ILLDIGIT 0x40
8154
8155 /* Don't warn on overflow; output flag still set */
8156 #  define PERL_SCAN_SILENT_OVERFLOW 0x80
8157
8158 /* Forbid a leading underscore, which the other one doesn't */
8159 #  define PERL_SCAN_ALLOW_MEDIAL_UNDERSCORES (0x100|PERL_SCAN_ALLOW_UNDERSCORES)
8160 #endif
8161
8162
8163 /* to let user control profiling */
8164 #ifdef PERL_GPROF_CONTROL
8165 extern void moncontrol(int);
8166 #define PERL_GPROF_MONCONTROL(x) moncontrol(x)
8167 #else
8168 #define PERL_GPROF_MONCONTROL(x)
8169 #endif
8170
8171 /* ISO 6429 NEL - C1 control NExt Line */
8172 /* See https://www.unicode.org/unicode/reports/tr13/ */
8173 #define NEXT_LINE_CHAR  NEXT_LINE_NATIVE
8174
8175 #ifndef PIPESOCK_MODE
8176 #  define PIPESOCK_MODE
8177 #endif
8178
8179 #ifndef SOCKET_OPEN_MODE
8180 #  define SOCKET_OPEN_MODE      PIPESOCK_MODE
8181 #endif
8182
8183 #ifndef PIPE_OPEN_MODE
8184 #  define PIPE_OPEN_MODE        PIPESOCK_MODE
8185 #endif
8186
8187 #define PERL_MAGIC_UTF8_CACHESIZE       2
8188
8189 #ifdef PERL_CORE
8190
8191 #define PERL_UNICODE_STDIN_FLAG                 0x0001
8192 #define PERL_UNICODE_STDOUT_FLAG                0x0002
8193 #define PERL_UNICODE_STDERR_FLAG                0x0004
8194 #define PERL_UNICODE_IN_FLAG                    0x0008
8195 #define PERL_UNICODE_OUT_FLAG                   0x0010
8196 #define PERL_UNICODE_ARGV_FLAG                  0x0020
8197 #define PERL_UNICODE_LOCALE_FLAG                0x0040
8198 #define PERL_UNICODE_WIDESYSCALLS_FLAG          0x0080 /* for Sarathy */
8199 #define PERL_UNICODE_UTF8CACHEASSERT_FLAG       0x0100
8200
8201 #define PERL_UNICODE_STD_FLAG           \
8202         (PERL_UNICODE_STDIN_FLAG        | \
8203          PERL_UNICODE_STDOUT_FLAG       | \
8204          PERL_UNICODE_STDERR_FLAG)
8205
8206 #define PERL_UNICODE_INOUT_FLAG         \
8207         (PERL_UNICODE_IN_FLAG   | \
8208          PERL_UNICODE_OUT_FLAG)
8209
8210 #define PERL_UNICODE_DEFAULT_FLAGS      \
8211         (PERL_UNICODE_STD_FLAG          | \
8212          PERL_UNICODE_INOUT_FLAG        | \
8213          PERL_UNICODE_LOCALE_FLAG)
8214
8215 #define PERL_UNICODE_ALL_FLAGS                  0x01ff
8216
8217 #define PERL_UNICODE_STDIN                      'I'
8218 #define PERL_UNICODE_STDOUT                     'O'
8219 #define PERL_UNICODE_STDERR                     'E'
8220 #define PERL_UNICODE_STD                        'S'
8221 #define PERL_UNICODE_IN                         'i'
8222 #define PERL_UNICODE_OUT                        'o'
8223 #define PERL_UNICODE_INOUT                      'D'
8224 #define PERL_UNICODE_ARGV                       'A'
8225 #define PERL_UNICODE_LOCALE                     'L'
8226 #define PERL_UNICODE_WIDESYSCALLS               'W'
8227 #define PERL_UNICODE_UTF8CACHEASSERT            'a'
8228
8229 #endif
8230
8231 /*
8232 =for apidoc_section $signals
8233 =for apidoc Amn|U32|PERL_SIGNALS_UNSAFE_FLAG
8234 If this bit in C<PL_signals> is set, the system is uing the pre-Perl 5.8
8235 unsafe signals.  See L<perlrun/PERL_SIGNALS> and L<perlipc/Deferred Signals
8236 (Safe Signals)>.
8237
8238 =cut
8239 */
8240 #define PERL_SIGNALS_UNSAFE_FLAG        0x0001
8241
8242 /*
8243 =for apidoc_section $numeric
8244
8245 =for apidoc Am|int|PERL_ABS|int x
8246
8247 Typeless C<abs> or C<fabs>, I<etc>.  (The usage below indicates it is for
8248 integers, but it works for any type.)  Use instead of these, since the C
8249 library ones force their argument to be what it is expecting, potentially
8250 leading to disaster.  But also beware that this evaluates its argument twice,
8251 so no C<x++>.
8252
8253 =cut
8254 */
8255
8256 #define PERL_ABS(x) ((x) < 0 ? -(x) : (x))
8257
8258 #if defined(__DECC) && defined(__osf__)
8259 #pragma message disable (mainparm) /* Perl uses the envp in main(). */
8260 #endif
8261
8262 #define do_open(g, n, l, a, rm, rp, sf) \
8263         do_openn(g, n, l, a, rm, rp, sf, (SV **) NULL, 0)
8264 #ifdef PERL_DEFAULT_DO_EXEC3_IMPLEMENTATION
8265 #  define do_exec(cmd)                  do_exec3(cmd,0,0)
8266 #endif
8267 #ifdef OS2
8268 #  define do_aexec                      Perl_do_aexec
8269 #else
8270 #  define do_aexec(really, mark,sp)     do_aexec5(really, mark, sp, 0, 0)
8271 #endif
8272
8273
8274 /*
8275 =for apidoc_section $utility
8276
8277 =for apidoc Am|bool|IS_SAFE_SYSCALL|NN const char *pv|STRLEN len|NN const char *what|NN const char *op_name
8278
8279 Same as L</is_safe_syscall>.
8280
8281 =cut
8282
8283 Allows one ending \0
8284 */
8285 #define IS_SAFE_SYSCALL(p, len, what, op_name) (Perl_is_safe_syscall(aTHX_ (p), (len), (what), (op_name)))
8286
8287 #define IS_SAFE_PATHNAME(p, len, op_name) IS_SAFE_SYSCALL((p), (len), "pathname", (op_name))
8288
8289 #if defined(OEMVS) || defined(__amigaos4__)
8290 #define NO_ENV_ARRAY_IN_MAIN
8291 #endif
8292
8293 /* These are used by Perl_pv_escape() and Perl_pv_pretty()
8294  * are here so that they are available throughout the core
8295  * NOTE that even though some are for _escape and some for _pretty
8296  * there must not be any clashes as the flags from _pretty are
8297  * passed straight through to _escape.
8298  */
8299
8300 #define PERL_PV_ESCAPE_QUOTE        0x000001
8301 #define PERL_PV_PRETTY_QUOTE        PERL_PV_ESCAPE_QUOTE
8302
8303 #define PERL_PV_PRETTY_ELLIPSES     0x000002
8304 #define PERL_PV_PRETTY_LTGT         0x000004
8305 #define PERL_PV_PRETTY_EXACTSIZE    0x000008
8306
8307 #define PERL_PV_ESCAPE_UNI          0x000100
8308 #define PERL_PV_ESCAPE_UNI_DETECT   0x000200
8309 #define PERL_PV_ESCAPE_NONASCII     0x000400
8310 #define PERL_PV_ESCAPE_FIRSTCHAR    0x000800
8311
8312 #define PERL_PV_ESCAPE_ALL          0x001000
8313 #define PERL_PV_ESCAPE_NOBACKSLASH  0x002000
8314 #define PERL_PV_ESCAPE_NOCLEAR      0x004000
8315 #define PERL_PV_PRETTY_NOCLEAR      PERL_PV_ESCAPE_NOCLEAR
8316 #define PERL_PV_ESCAPE_RE           0x008000
8317
8318 /* Escape PV with hex, except leave NULs as octal: */
8319 #define PERL_PV_ESCAPE_DWIM         0x010000
8320
8321 /* Escape PV with all hex, including NUL. */
8322 #define PERL_PV_ESCAPE_DWIM_ALL_HEX 0x020000
8323
8324 /* Do not escape word characters, alters meaning of other flags */
8325 #define PERL_PV_ESCAPE_NON_WC       0x040000
8326 #define PERL_PV_ESCAPE_TRUNC_MIDDLE 0x080000
8327
8328 #define PERL_PV_PRETTY_QUOTEDPREFIX (   \
8329         PERL_PV_PRETTY_ELLIPSES |       \
8330         PERL_PV_PRETTY_QUOTE    |       \
8331         PERL_PV_ESCAPE_NONASCII |       \
8332         PERL_PV_ESCAPE_NON_WC   |       \
8333         PERL_PV_ESCAPE_TRUNC_MIDDLE |   \
8334         0)
8335
8336
8337 /* used by pv_display in dump.c*/
8338 #define PERL_PV_PRETTY_DUMP  PERL_PV_PRETTY_ELLIPSES|PERL_PV_PRETTY_QUOTE
8339 #define PERL_PV_PRETTY_REGPROP PERL_PV_PRETTY_ELLIPSES|PERL_PV_PRETTY_LTGT|PERL_PV_ESCAPE_RE|PERL_PV_ESCAPE_NONASCII
8340
8341 #if DOUBLEKIND == DOUBLE_IS_VAX_F_FLOAT || \
8342     DOUBLEKIND == DOUBLE_IS_VAX_D_FLOAT || \
8343     DOUBLEKIND == DOUBLE_IS_VAX_G_FLOAT
8344 #  define DOUBLE_IS_VAX_FLOAT
8345 #else
8346 #  define DOUBLE_IS_IEEE_FORMAT
8347 #endif
8348
8349 #if DOUBLEKIND == DOUBLE_IS_IEEE_754_32_BIT_LITTLE_ENDIAN || \
8350     DOUBLEKIND == DOUBLE_IS_IEEE_754_64_BIT_LITTLE_ENDIAN || \
8351     DOUBLEKIND == DOUBLE_IS_IEEE_754_128_BIT_LITTLE_ENDIAN
8352 #  define DOUBLE_LITTLE_ENDIAN
8353 #endif
8354
8355 #if DOUBLEKIND == DOUBLE_IS_IEEE_754_32_BIT_BIG_ENDIAN || \
8356     DOUBLEKIND == DOUBLE_IS_IEEE_754_64_BIT_BIG_ENDIAN || \
8357     DOUBLEKIND == DOUBLE_IS_IEEE_754_128_BIT_BIG_ENDIAN
8358 #  define DOUBLE_BIG_ENDIAN
8359 #endif
8360
8361 #if DOUBLEKIND == DOUBLE_IS_IEEE_754_64_BIT_MIXED_ENDIAN_LE_BE || \
8362     DOUBLEKIND == DOUBLE_IS_IEEE_754_64_BIT_MIXED_ENDIAN_BE_LE
8363 #  define DOUBLE_MIX_ENDIAN
8364 #endif
8365
8366 /* The VAX fp formats are neither consistently little-endian nor
8367  * big-endian, and neither are they really IEEE-mixed endian like
8368  * the mixed-endian ARM IEEE formats (with swapped bytes).
8369  * Ultimately, the VAX format came from the PDP-11.
8370  *
8371  * The ordering of the parts in VAX floats is quite vexing.
8372  * In the below the fraction_n are the mantissa bits.
8373  *
8374  * The fraction_1 is the most significant (numbering as by DEC/Digital),
8375  * while the rightmost bit in each fraction is the least significant:
8376  * in other words, big-endian bit order within the fractions.
8377  *
8378  * The fraction segments themselves would be big-endianly, except that
8379  * within 32 bit segments the less significant half comes first, the more
8380  * significant after, except that in the format H (used for long doubles)
8381  * the first fraction segment is alone, because the exponent is wider.
8382  * This means for example that both the most and the least significant
8383  * bits can be in the middle of the floats, not at either end.
8384  *
8385  * References:
8386  * http://nssdc.gsfc.nasa.gov/nssdc/formats/VAXFloatingPoint.htm
8387  * http://www.quadibloc.com/comp/cp0201.htm
8388  * http://h71000.www7.hp.com/doc/82final/6443/6443pro_028.html
8389  * (somebody at HP should be fired for the URLs)
8390  *
8391  * F   fraction_2:16 sign:1 exp:8  fraction_1:7
8392  *     (exponent bias 128, hidden first one-bit)
8393  *
8394  * D   fraction_2:16 sign:1 exp:8  fraction_1:7
8395  *     fraction_4:16               fraction_3:16
8396  *     (exponent bias 128, hidden first one-bit)
8397  *
8398  * G   fraction_2:16 sign:1 exp:11 fraction_1:4
8399  *     fraction_4:16               fraction_3:16
8400  *     (exponent bias 1024, hidden first one-bit)
8401  *
8402  * H   fraction_1:16 sign:1 exp:15
8403  *     fraction_3:16               fraction_2:16
8404  *     fraction_5:16               fraction_4:16
8405  *     fraction_7:16               fraction_6:16
8406  *     (exponent bias 16384, hidden first one-bit)
8407  *     (available only on VAX, and only on Fortran?)
8408  *
8409  * The formats S, T and X are available on the Alpha (and Itanium,
8410  * also known as I64/IA64) and are equivalent with the IEEE-754 formats
8411  * binary32, binary64, and binary128 (commonly: float, double, long double).
8412  *
8413  * S   sign:1 exp:8 mantissa:23
8414  *     (exponent bias 127, hidden first one-bit)
8415  *
8416  * T   sign:1 exp:11 mantissa:52
8417  *     (exponent bias 1022, hidden first one-bit)
8418  *
8419  * X   sign:1 exp:15 mantissa:112
8420  *     (exponent bias 16382, hidden first one-bit)
8421  *
8422  */
8423
8424 #ifdef DOUBLE_IS_VAX_FLOAT
8425 #  define DOUBLE_VAX_ENDIAN
8426 #endif
8427
8428 #ifdef DOUBLE_IS_IEEE_FORMAT
8429 /* All the basic IEEE formats have the implicit bit,
8430  * except for the x86 80-bit extended formats, which will undef this.
8431  * Also note that the IEEE 754 subnormals (formerly known as denormals)
8432  * do not have the implicit bit of one. */
8433 #  define NV_IMPLICIT_BIT
8434 #endif
8435
8436 #if defined(LONG_DOUBLEKIND) && LONG_DOUBLEKIND != LONG_DOUBLE_IS_DOUBLE
8437
8438 #  if LONG_DOUBLEKIND == LONG_DOUBLE_IS_IEEE_754_128_BIT_LITTLE_ENDIAN || \
8439       LONG_DOUBLEKIND == LONG_DOUBLE_IS_X86_80_BIT_LITTLE_ENDIAN || \
8440       LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_LE_LE
8441 #    define LONGDOUBLE_LITTLE_ENDIAN
8442 #  endif
8443
8444 #  if LONG_DOUBLEKIND == LONG_DOUBLE_IS_IEEE_754_128_BIT_BIG_ENDIAN || \
8445       LONG_DOUBLEKIND == LONG_DOUBLE_IS_X86_80_BIT_BIG_ENDIAN || \
8446       LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_BE_BE
8447 #    define LONGDOUBLE_BIG_ENDIAN
8448 #  endif
8449
8450 #  if LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_LE_BE || \
8451       LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_BE_LE
8452 #    define LONGDOUBLE_MIX_ENDIAN
8453 #  endif
8454
8455 #  if LONG_DOUBLEKIND == LONG_DOUBLE_IS_X86_80_BIT_LITTLE_ENDIAN || \
8456       LONG_DOUBLEKIND == LONG_DOUBLE_IS_X86_80_BIT_BIG_ENDIAN
8457 #    define LONGDOUBLE_X86_80_BIT
8458 #    ifdef USE_LONG_DOUBLE
8459 #      undef NV_IMPLICIT_BIT
8460 #      define NV_X86_80_BIT
8461 #    endif
8462 #  endif
8463
8464 #  if LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_LE_LE || \
8465       LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_BE_BE || \
8466       LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_LE_BE || \
8467       LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_BE_LE
8468 #    define LONGDOUBLE_DOUBLEDOUBLE
8469 #  endif
8470
8471 #  if LONG_DOUBLEKIND == LONG_DOUBLE_IS_VAX_H_FLOAT
8472 #    define LONGDOUBLE_VAX_ENDIAN
8473 #  endif
8474
8475 #endif /* LONG_DOUBLEKIND */
8476
8477 #ifdef USE_QUADMATH /* assume quadmath endianness == native double endianness */
8478 #  if defined(DOUBLE_LITTLE_ENDIAN)
8479 #    define NV_LITTLE_ENDIAN
8480 #  elif defined(DOUBLE_BIG_ENDIAN)
8481 #    define NV_BIG_ENDIAN
8482 #  elif defined(DOUBLE_MIX_ENDIAN) /* stretch */
8483 #    define NV_MIX_ENDIAN
8484 #  endif
8485 #elif NVSIZE == DOUBLESIZE
8486 #  ifdef DOUBLE_LITTLE_ENDIAN
8487 #    define NV_LITTLE_ENDIAN
8488 #  endif
8489 #  ifdef DOUBLE_BIG_ENDIAN
8490 #    define NV_BIG_ENDIAN
8491 #  endif
8492 #  ifdef DOUBLE_MIX_ENDIAN
8493 #    define NV_MIX_ENDIAN
8494 #  endif
8495 #  ifdef DOUBLE_VAX_ENDIAN
8496 #    define NV_VAX_ENDIAN
8497 #  endif
8498 #elif NVSIZE == LONG_DOUBLESIZE
8499 #  ifdef LONGDOUBLE_LITTLE_ENDIAN
8500 #    define NV_LITTLE_ENDIAN
8501 #  endif
8502 #  ifdef LONGDOUBLE_BIG_ENDIAN
8503 #    define NV_BIG_ENDIAN
8504 #  endif
8505 #  ifdef LONGDOUBLE_MIX_ENDIAN
8506 #    define NV_MIX_ENDIAN
8507 #  endif
8508 #  ifdef LONGDOUBLE_VAX_ENDIAN
8509 #    define NV_VAX_ENDIAN
8510 #  endif
8511 #endif
8512
8513 /* We have somehow managed not to define the denormal/subnormal
8514  * detection.
8515  *
8516  * This may happen if the compiler doesn't expose the C99 math like
8517  * the fpclassify() without some special switches.  Perl tries to
8518  * stay C89, so for example -std=c99 is not an option.
8519  *
8520  * The Perl_isinf() and Perl_isnan() should have been defined even if
8521  * the C99 isinf() and isnan() are unavailable, and the NV_MIN becomes
8522  * from the C89 DBL_MIN or moral equivalent. */
8523 #if !defined(Perl_fp_class_denorm) && defined(Perl_isinf) && defined(Perl_isnan) && defined(NV_MIN)
8524 #  define Perl_fp_class_denorm(x) ((x) != 0.0 && !Perl_isinf(x) && !Perl_isnan(x) && PERL_ABS(x) < NV_MIN)
8525 #endif
8526
8527 /* This is not a great fallback: subnormals tests will fail,
8528  * but at least Perl will link and 99.999% of tests will work. */
8529 #if !defined(Perl_fp_class_denorm)
8530 #  define Perl_fp_class_denorm(x) FALSE
8531 #endif
8532
8533 #ifdef DOUBLE_IS_IEEE_FORMAT
8534 #  define DOUBLE_HAS_INF
8535 #  define DOUBLE_HAS_NAN
8536 #endif
8537
8538 #ifdef DOUBLE_HAS_NAN
8539
8540 START_EXTERN_C
8541
8542 #ifdef DOINIT
8543
8544 /* PL_inf and PL_nan initialization.
8545  *
8546  * For inf and nan initialization the ultimate fallback is dividing
8547  * one or zero by zero: however, some compilers will warn or even fail
8548  * on divide-by-zero, but hopefully something earlier will work.
8549  *
8550  * If you are thinking of using HUGE_VAL for infinity, or using
8551  * <math.h> functions to generate NV_INF (e.g. exp(1e9), log(-1.0)),
8552  * stop.  Neither will work portably: HUGE_VAL can be just DBL_MAX,
8553  * and the math functions might be just generating DBL_MAX, or even zero.
8554  *
8555  * Also, do NOT try doing NV_NAN based on NV_INF and trying (NV_INF-NV_INF).
8556  * Though logically correct, some compilers (like Visual C 2003)
8557  * falsely misoptimize that to zero (x-x is always zero, right?)
8558  *
8559  * Finally, note that not all floating point formats define Inf (or NaN).
8560  * For the infinity a large number may be used instead.  Operations that
8561  * under the IEEE floating point would return Inf or NaN may return
8562  * either large numbers (positive or negative), or they may cause
8563  * a floating point exception or some other fault.
8564  */
8565
8566 /* The quadmath literals are anon structs which -Wc++-compat doesn't like. */
8567 #  ifndef USE_CPLUSPLUS
8568 GCC_DIAG_IGNORE_DECL(-Wc++-compat);
8569 #  endif
8570
8571 #  ifdef USE_QUADMATH
8572 /* Cannot use HUGE_VALQ for PL_inf because not a compile-time
8573  * constant. */
8574 INFNAN_NV_U8_DECL PL_inf = { 1.0Q/0.0Q };
8575 #  elif NVSIZE == LONG_DOUBLESIZE && defined(LONGDBLINFBYTES)
8576 INFNAN_U8_NV_DECL PL_inf = { { LONGDBLINFBYTES } };
8577 #  elif NVSIZE == DOUBLESIZE && defined(DOUBLEINFBYTES)
8578 INFNAN_U8_NV_DECL PL_inf = { { DOUBLEINFBYTES } };
8579 #  else
8580 #    if NVSIZE == LONG_DOUBLESIZE && defined(USE_LONG_DOUBLE)
8581 #      if defined(LDBL_INFINITY)
8582 INFNAN_NV_U8_DECL PL_inf = { LDBL_INFINITY };
8583 #      elif defined(LDBL_INF)
8584 INFNAN_NV_U8_DECL PL_inf = { LDBL_INF };
8585 #      elif defined(INFINITY)
8586 INFNAN_NV_U8_DECL PL_inf = { (NV)INFINITY };
8587 #      elif defined(INF)
8588 INFNAN_NV_U8_DECL PL_inf = { (NV)INF };
8589 #      else
8590 INFNAN_NV_U8_DECL PL_inf = { 1.0L/0.0L }; /* keep last */
8591 #      endif
8592 #    else
8593 #      if defined(DBL_INFINITY)
8594 INFNAN_NV_U8_DECL PL_inf = { DBL_INFINITY };
8595 #      elif defined(DBL_INF)
8596 INFNAN_NV_U8_DECL PL_inf = { DBL_INF };
8597 #      elif defined(INFINITY) /* C99 */
8598 INFNAN_NV_U8_DECL PL_inf = { (NV)INFINITY };
8599 #      elif defined(INF)
8600 INFNAN_NV_U8_DECL PL_inf = { (NV)INF };
8601 #      else
8602 INFNAN_NV_U8_DECL PL_inf = { 1.0/0.0 }; /* keep last */
8603 #      endif
8604 #    endif
8605 #  endif
8606
8607 #  ifdef USE_QUADMATH
8608 /* Cannot use nanq("0") for PL_nan because not a compile-time
8609  * constant. */
8610 INFNAN_NV_U8_DECL PL_nan = { 0.0Q/0.0Q };
8611 #  elif NVSIZE == LONG_DOUBLESIZE && defined(LONGDBLNANBYTES)
8612 INFNAN_U8_NV_DECL PL_nan = { { LONGDBLNANBYTES } };
8613 #  elif NVSIZE == DOUBLESIZE && defined(DOUBLENANBYTES)
8614 INFNAN_U8_NV_DECL PL_nan = { { DOUBLENANBYTES } };
8615 #  else
8616 #    if NVSIZE == LONG_DOUBLESIZE && defined(USE_LONG_DOUBLE)
8617 #      if defined(LDBL_NAN)
8618 INFNAN_NV_U8_DECL PL_nan = { LDBL_NAN };
8619 #      elif defined(LDBL_QNAN)
8620 INFNAN_NV_U8_DECL PL_nan = { LDBL_QNAN };
8621 #      elif defined(NAN)
8622 INFNAN_NV_U8_DECL PL_nan = { (NV)NAN };
8623 #      else
8624 INFNAN_NV_U8_DECL PL_nan = { 0.0L/0.0L }; /* keep last */
8625 #      endif
8626 #    else
8627 #      if defined(DBL_NAN)
8628 INFNAN_NV_U8_DECL PL_nan = { DBL_NAN };
8629 #      elif defined(DBL_QNAN)
8630 INFNAN_NV_U8_DECL PL_nan = { DBL_QNAN };
8631 #      elif defined(NAN) /* C99 */
8632 INFNAN_NV_U8_DECL PL_nan = { (NV)NAN };
8633 #      else
8634 INFNAN_NV_U8_DECL PL_nan = { 0.0/0.0 }; /* keep last */
8635 #      endif
8636 #    endif
8637 #  endif
8638
8639 #  ifndef USE_CPLUSPLUS
8640 GCC_DIAG_RESTORE_DECL;
8641 #  endif
8642
8643 #else
8644
8645 /* The declarations here need to match the initializations done above,
8646    since a mismatch across compilation units causes undefined
8647    behavior.  It also prevents warnings from LTO builds.
8648 */
8649 #  if !defined(USE_QUADMATH) && \
8650        (NVSIZE == LONG_DOUBLESIZE && defined(LONGDBLINFBYTES) ||   \
8651         NVSIZE == DOUBLESIZE && defined(DOUBLEINFBYTES))
8652 INFNAN_U8_NV_DECL PL_inf;
8653 #  else
8654 INFNAN_NV_U8_DECL PL_inf;
8655 #  endif
8656
8657 #  if !defined(USE_QUADMATH) && \
8658        (NVSIZE == LONG_DOUBLESIZE && defined(LONGDBLNANBYTES) ||   \
8659         NVSIZE == DOUBLESIZE && defined(DOUBLENANBYTES))
8660 INFNAN_U8_NV_DECL PL_nan;
8661 #  else
8662 INFNAN_NV_U8_DECL PL_nan;
8663 #  endif
8664
8665 #endif
8666
8667 END_EXTERN_C
8668
8669 /* If you have not defined NV_INF/NV_NAN (like for example win32/win32.h),
8670  * we will define NV_INF/NV_NAN as the nv part of the global const
8671  * PL_inf/PL_nan.  Note, however, that the preexisting NV_INF/NV_NAN
8672  * might not be a compile-time constant, in which case it cannot be
8673  * used to initialize PL_inf/PL_nan above. */
8674 #ifndef NV_INF
8675 #  define NV_INF PL_inf.nv
8676 #endif
8677 #ifndef NV_NAN
8678 #  define NV_NAN PL_nan.nv
8679 #endif
8680
8681 /* NaNs (not-a-numbers) can carry payload bits, in addition to
8682  * "nan-ness".  Part of the payload is the quiet/signaling bit.
8683  * To back up a bit (harhar):
8684  *
8685  * For IEEE 754 64-bit formats [1]:
8686  *
8687  * s 000 (mantissa all-zero)  zero
8688  * s 000 (mantissa non-zero)  subnormals (denormals)
8689  * s 001 ... 7fe              normals
8690  * s 7ff q                    nan
8691  *
8692  * For IEEE 754 128-bit formats:
8693  *
8694  * s 0000 (mantissa all-zero)  zero
8695  * s 0000 (mantissa non-zero)  subnormals (denormals)
8696  * s 0001 ... 7ffe             normals
8697  * s 7fff q                    nan
8698  *
8699  * [1] this looks like big-endian, but applies equally to little-endian.
8700  *
8701  * s = Sign bit.  Yes, zeros and nans can have negative sign,
8702  *     the interpretation is application-specific.
8703  *
8704  * q = Quietness bit, the interpretation is platform-specific.
8705  *     Most platforms have the most significant bit being one
8706  *     meaning quiet, but some (older mips, hppa) have the msb
8707  *     being one meaning signaling.  Note that the above means
8708  *     that on most platforms there cannot be signaling nan with
8709  *     zero payload because that is identical with infinity;
8710  *     while conversely on older mips/hppa there cannot be a quiet nan
8711  *     because that is identical with infinity.
8712  *
8713  *     Moreover, whether there is any behavioral difference
8714  *     between quiet and signaling NaNs, depends on the platform.
8715  *
8716  * x86 80-bit extended precision is different, the mantissa bits:
8717  *
8718  * 63 62 61   30387+    pre-387    visual c
8719  * --------   ----      --------   --------
8720  *  0  0  0   invalid   infinity
8721  *  0  0  1   invalid   snan
8722  *  0  1  0   invalid   snan
8723  *  0  1  1   invalid   snan
8724  *  1  0  0   infinity  snan        1.#INF
8725  *  1  0  1   snan                  1.#SNAN
8726  *  1  1  0   qnan                 -1.#IND  (x86 chooses this to negative)
8727  *  1  1  1   qnan                  1.#QNAN
8728  *
8729  * This means that in this format there are 61 bits available
8730  * for the nan payload.
8731  *
8732  * Note that the 32-bit x86 ABI cannot do signaling nans: the x87
8733  * simply cannot preserve the bit.  You can either use the 80-bit
8734  * extended precision (long double, -Duselongdouble), or use x86-64.
8735  *
8736  * In all platforms, the payload bytes (and bits, some of them are
8737  * often in a partial byte) themselves can be either all zero (x86),
8738  * all one (sparc or mips), or a mixture: in IEEE 754 128-bit double
8739  * or in a double-double, the first half of the payload can follow the
8740  * native double, while in the second half the payload can be all
8741  * zeros.  (Therefore the mask for payload bits is not necessarily
8742  * identical to bit complement of the NaN.)  Another way of putting
8743  * this: the payload for the default NaN might not be zero.
8744  *
8745  * For the x86 80-bit long doubles, the trailing bytes (the 80 bits
8746  * being 'packaged' in either 12 or 16 bytes) can be whatever random
8747  * garbage.
8748  *
8749  * Furthermore, the semantics of the sign bit on NaNs are platform-specific.
8750  * On normal floats, the sign bit being on means negative.  But this may,
8751  * or may not, be reverted on NaNs: in other words, the default NaN might
8752  * have the sign bit on, and therefore look like negative if you look
8753  * at it at the bit level.
8754  *
8755  * NaN payloads are not propagated even on copies, or in arithmetics.
8756  * They *might* be, according to some rules, on your particular
8757  * cpu/os/compiler/libraries, but no guarantees.
8758  *
8759  * To summarize, on most platforms, and for 64-bit doubles
8760  * (using big-endian ordering here):
8761  *
8762  * [7FF8000000000000..7FFFFFFFFFFFFFFF] quiet
8763  * [FFF8000000000000..FFFFFFFFFFFFFFFF] quiet
8764  * [7FF0000000000001..7FF7FFFFFFFFFFFF] signaling
8765  * [FFF0000000000001..FFF7FFFFFFFFFFFF] signaling
8766  *
8767  * The C99 nan() is supposed to generate *quiet* NaNs.
8768  *
8769  * Note the asymmetry:
8770  * The 7FF0000000000000 is positive infinity,
8771  * the FFF0000000000000 is negative infinity.
8772  */
8773
8774 /* NVMANTBITS is the number of _real_ mantissa bits in an NV.
8775  * For the standard IEEE 754 fp this number is usually one less that
8776  * *DBL_MANT_DIG because of the implicit (aka hidden) bit, which isn't
8777  * real.  For the 80-bit extended precision formats (x86*), the number
8778  * of mantissa bits... depends. For normal floats, it's 64.  But for
8779  * the inf/nan, it's different (zero for inf, 61 for nan).
8780  * NVMANTBITS works for normal floats. */
8781
8782 /* We do not want to include the quiet/signaling bit. */
8783 #define NV_NAN_BITS (NVMANTBITS - 1)
8784
8785 #if defined(USE_LONG_DOUBLE) && NVSIZE > DOUBLESIZE
8786 #  if LONG_DOUBLEKIND == LONG_DOUBLE_IS_IEEE_754_128_BIT_LITTLE_ENDIAN
8787 #    define NV_NAN_QS_BYTE_OFFSET 13
8788 #  elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_IEEE_754_128_BIT_BIG_ENDIAN
8789 #    define NV_NAN_QS_BYTE_OFFSET 2
8790 #  elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_X86_80_BIT_LITTLE_ENDIAN
8791 #    define NV_NAN_QS_BYTE_OFFSET 7
8792 #  elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_X86_80_BIT_BIG_ENDIAN
8793 #    define NV_NAN_QS_BYTE_OFFSET 2
8794 #  elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_LE_LE
8795 #    define NV_NAN_QS_BYTE_OFFSET 13
8796 #  elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_BE_BE
8797 #    define NV_NAN_QS_BYTE_OFFSET 1
8798 #  elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_LE_BE
8799 #    define NV_NAN_QS_BYTE_OFFSET 9
8800 #  elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_BE_LE
8801 #    define NV_NAN_QS_BYTE_OFFSET 6
8802 #  else
8803 #    error "Unexpected long double format"
8804 #  endif
8805 #else
8806 #  ifdef USE_QUADMATH
8807 #    ifdef NV_LITTLE_ENDIAN
8808 #      define NV_NAN_QS_BYTE_OFFSET 13
8809 #    elif defined(NV_BIG_ENDIAN)
8810 #      define NV_NAN_QS_BYTE_OFFSET 2
8811 #    else
8812 #      error "Unexpected quadmath format"
8813 #    endif
8814 #  elif DOUBLEKIND == DOUBLE_IS_IEEE_754_32_BIT_LITTLE_ENDIAN
8815 #    define NV_NAN_QS_BYTE_OFFSET 2
8816 #  elif DOUBLEKIND == DOUBLE_IS_IEEE_754_32_BIT_BIG_ENDIAN
8817 #    define NV_NAN_QS_BYTE_OFFSET 1
8818 #  elif DOUBLEKIND == DOUBLE_IS_IEEE_754_64_BIT_LITTLE_ENDIAN
8819 #    define NV_NAN_QS_BYTE_OFFSET 6
8820 #  elif DOUBLEKIND == DOUBLE_IS_IEEE_754_64_BIT_BIG_ENDIAN
8821 #    define NV_NAN_QS_BYTE_OFFSET 1
8822 #  elif DOUBLEKIND == DOUBLE_IS_IEEE_754_128_BIT_LITTLE_ENDIAN
8823 #    define NV_NAN_QS_BYTE_OFFSET 13
8824 #  elif DOUBLEKIND == DOUBLE_IS_IEEE_754_128_BIT_BIG_ENDIAN
8825 #    define NV_NAN_QS_BYTE_OFFSET 2
8826 #  elif DOUBLEKIND == DOUBLE_IS_IEEE_754_64_BIT_MIXED_ENDIAN_LE_BE
8827 #    define NV_NAN_QS_BYTE_OFFSET 2 /* bytes 4 5 6 7 0 1 2 3 (MSB 7) */
8828 #  elif DOUBLEKIND == DOUBLE_IS_IEEE_754_64_BIT_MIXED_ENDIAN_BE_LE
8829 #    define NV_NAN_QS_BYTE_OFFSET 5 /* bytes 3 2 1 0 7 6 5 4 (MSB 7) */
8830 #  else
8831 /* For example the VAX formats should never
8832  * get here because they do not have NaN. */
8833 #    error "Unexpected double format"
8834 #  endif
8835 #endif
8836 /* NV_NAN_QS_BYTE is the byte to test for the quiet/signaling */
8837 #define NV_NAN_QS_BYTE(nvp) (((U8*)(nvp))[NV_NAN_QS_BYTE_OFFSET])
8838 /* NV_NAN_QS_BIT is the bit to test in the NV_NAN_QS_BYTE_OFFSET
8839  * for the quiet/signaling */
8840 #if defined(USE_LONG_DOUBLE) && \
8841   (LONG_DOUBLEKIND == LONG_DOUBLE_IS_X86_80_BIT_LITTLE_ENDIAN || \
8842    LONG_DOUBLEKIND == LONG_DOUBLE_IS_X86_80_BIT_BIG_ENDIAN)
8843 #  define NV_NAN_QS_BIT_SHIFT 6 /* 0x40 */
8844 #elif defined(USE_LONG_DOUBLE) && \
8845   (LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_LE_LE || \
8846    LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_BE_BE || \
8847    LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_LE_BE || \
8848    LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_BE_LE)
8849 #  define NV_NAN_QS_BIT_SHIFT 3 /* 0x08, but not via NV_NAN_BITS */
8850 #else
8851 #  define NV_NAN_QS_BIT_SHIFT ((NV_NAN_BITS) % 8) /* usually 3, or 0x08 */
8852 #endif
8853 #define NV_NAN_QS_BIT (1 << (NV_NAN_QS_BIT_SHIFT))
8854 /* NV_NAN_QS_BIT_OFFSET is the bit offset from the beginning of a NV
8855  * (bytes ordered big-endianly) for the quiet/signaling bit
8856  * for the quiet/signaling */
8857 #define NV_NAN_QS_BIT_OFFSET \
8858     (8 * (NV_NAN_QS_BYTE_OFFSET) + (NV_NAN_QS_BIT_SHIFT))
8859 /* NV_NAN_QS_QUIET (always defined) is true if the NV_NAN_QS_QS_BIT being
8860  * on indicates quiet NaN.  NV_NAN_QS_SIGNALING (also always defined)
8861  * is true if the NV_NAN_QS_BIT being on indicates signaling NaN. */
8862 #define NV_NAN_QS_QUIET \
8863     ((NV_NAN_QS_BYTE(PL_nan.u8) & NV_NAN_QS_BIT) == NV_NAN_QS_BIT)
8864 #define NV_NAN_QS_SIGNALING (!(NV_NAN_QS_QUIET))
8865 #define NV_NAN_QS_TEST(nvp) (NV_NAN_QS_BYTE(nvp) & NV_NAN_QS_BIT)
8866 /* NV_NAN_IS_QUIET() returns true if the NV behind nvp is a NaN,
8867  * whether it is a quiet NaN, NV_NAN_IS_SIGNALING() if a signaling NaN.
8868  * Note however that these do not check whether the nvp is a NaN. */
8869 #define NV_NAN_IS_QUIET(nvp) \
8870     (NV_NAN_QS_TEST(nvp) == (NV_NAN_QS_QUIET ? NV_NAN_QS_BIT : 0))
8871 #define NV_NAN_IS_SIGNALING(nvp) \
8872     (NV_NAN_QS_TEST(nvp) == (NV_NAN_QS_QUIET ? 0 : NV_NAN_QS_BIT))
8873 #define NV_NAN_SET_QUIET(nvp) \
8874     (NV_NAN_QS_QUIET ? \
8875      (NV_NAN_QS_BYTE(nvp) |= NV_NAN_QS_BIT) : \
8876      (NV_NAN_QS_BYTE(nvp) &= ~NV_NAN_QS_BIT))
8877 #define NV_NAN_SET_SIGNALING(nvp) \
8878     (NV_NAN_QS_QUIET ? \
8879      (NV_NAN_QS_BYTE(nvp) &= ~NV_NAN_QS_BIT) : \
8880      (NV_NAN_QS_BYTE(nvp) |= NV_NAN_QS_BIT))
8881 #define NV_NAN_QS_XOR(nvp) (NV_NAN_QS_BYTE(nvp) ^= NV_NAN_QS_BIT)
8882
8883 /* NV_NAN_PAYLOAD_MASK: masking the nan payload bits.
8884  *
8885  * NV_NAN_PAYLOAD_PERM: permuting the nan payload bytes.
8886  * 0xFF means "don't go here".*/
8887
8888 /* Shorthands to avoid typoses. */
8889 #define NV_NAN_PAYLOAD_MASK_SKIP_EIGHT \
8890   0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0
8891 #define NV_NAN_PAYLOAD_PERM_SKIP_EIGHT \
8892   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
8893 #define NV_NAN_PAYLOAD_PERM_0_TO_7 \
8894   0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7
8895 #define NV_NAN_PAYLOAD_PERM_7_TO_0 \
8896   0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0
8897 #define NV_NAN_PAYLOAD_MASK_IEEE_754_128_LE \
8898   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, \
8899   0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x00, 0x00
8900 #define NV_NAN_PAYLOAD_PERM_IEEE_754_128_LE \
8901   NV_NAN_PAYLOAD_PERM_0_TO_7, \
8902   0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xFF, 0xFF
8903 #define NV_NAN_PAYLOAD_MASK_IEEE_754_128_BE \
8904   0x00, 0x00, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, \
8905   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
8906 #define NV_NAN_PAYLOAD_PERM_IEEE_754_128_BE \
8907   0xFF, 0xFF, 0xd, 0xc, 0xb, 0xa, 0x9, 0x8, \
8908   NV_NAN_PAYLOAD_PERM_7_TO_0
8909 #define NV_NAN_PAYLOAD_MASK_IEEE_754_64_LE \
8910   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x07, 0x00
8911 #define NV_NAN_PAYLOAD_PERM_IEEE_754_64_LE \
8912   0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0xFF
8913 #define NV_NAN_PAYLOAD_MASK_IEEE_754_64_BE \
8914   0x00, 0x07, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
8915 #define NV_NAN_PAYLOAD_PERM_IEEE_754_64_BE \
8916   0xFF, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0
8917
8918 #if defined(USE_LONG_DOUBLE) && NVSIZE > DOUBLESIZE
8919 #  if LONG_DOUBLEKIND == LONG_DOUBLE_IS_IEEE_754_128_BIT_LITTLE_ENDIAN
8920 #    define NV_NAN_PAYLOAD_MASK NV_NAN_PAYLOAD_MASK_IEEE_754_128_LE
8921 #    define NV_NAN_PAYLOAD_PERM NV_NAN_PAYLOAD_PERM_IEEE_754_128_LE
8922 #  elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_IEEE_754_128_BIT_BIG_ENDIAN
8923 #    define NV_NAN_PAYLOAD_MASK NV_NAN_PAYLOAD_MASK_IEEE_754_128_BE
8924 #    define NV_NAN_PAYLOAD_PERM NV_NAN_PAYLOAD_PERM_IEEE_754_128_BE
8925 #  elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_X86_80_BIT_LITTLE_ENDIAN
8926 #    if LONG_DOUBLESIZE == 10
8927 #      define NV_NAN_PAYLOAD_MASK \
8928          0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, \
8929          0x00, 0x00
8930 #      define NV_NAN_PAYLOAD_PERM \
8931          NV_NAN_PAYLOAD_PERM_0_TO_7, 0xFF, 0xFF
8932 #    elif LONG_DOUBLESIZE == 12
8933 #      define NV_NAN_PAYLOAD_MASK \
8934          0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, \
8935          0x00, 0x00, 0x00, 0x00
8936 #      define NV_NAN_PAYLOAD_PERM \
8937          NV_NAN_PAYLOAD_PERM_0_TO_7, 0xFF, 0xFF, 0xFF, 0xFF
8938 #    elif LONG_DOUBLESIZE == 16
8939 #      define NV_NAN_PAYLOAD_MASK \
8940          0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, \
8941          0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
8942 #      define NV_NAN_PAYLOAD_PERM \
8943          NV_NAN_PAYLOAD_PERM_0_TO_7, \
8944          0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
8945 #    else
8946 #      error "Unexpected x86 80-bit little-endian long double format"
8947 #    endif
8948 #  elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_X86_80_BIT_BIG_ENDIAN
8949 #    if LONG_DOUBLESIZE == 10
8950 #      define NV_NAN_PAYLOAD_MASK \
8951          0x00, 0x00, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, \
8952          0xff, 0xff
8953 #      define NV_NAN_PAYLOAD_PERM \
8954          NV_NAN_PAYLOAD_PERM_7_TO_0, 0xFF, 0xFF
8955 #    elif LONG_DOUBLESIZE == 12
8956 #      define NV_NAN_PAYLOAD_MASK \
8957          0x00, 0x00, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, \
8958          0xff, 0xff, 0x00, 0x00
8959 #      define NV_NAN_PAYLOAD_PERM \
8960          NV_NAN_PAYLOAD_PERM_7_TO_0, 0xFF, 0xFF, 0xFF, 0xFF
8961 #    elif LONG_DOUBLESIZE == 16
8962 #      define NV_NAN_PAYLOAD_MASK \
8963          0x00, 0x00, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, \
8964          0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
8965 #      define NV_NAN_PAYLOAD_PERM \
8966          NV_NAN_PAYLOAD_PERM_7_TO_0, \
8967          0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
8968 #    else
8969 #      error "Unexpected x86 80-bit big-endian long double format"
8970 #    endif
8971 #  elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_LE_LE
8972 /* For double-double we assume only the first double (in LE or BE terms)
8973  * is used for NaN. */
8974 #    define NV_NAN_PAYLOAD_MASK \
8975        NV_NAN_PAYLOAD_MASK_SKIP_EIGHT, NV_NAN_PAYLOAD_MASK_IEEE_754_64_LE
8976 #    define NV_NAN_PAYLOAD_PERM \
8977        NV_NAN_PAYLOAD_PERM_SKIP_EIGHT, NV_NAN_PAYLOAD_PERM_IEEE_754_64_LE
8978 #  elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_BE_BE
8979 #    define NV_NAN_PAYLOAD_MASK \
8980        NV_NAN_PAYLOAD_MASK_IEEE_754_64_BE
8981 #    define NV_NAN_PAYLOAD_PERM \
8982        NV_NAN_PAYLOAD_PERM_IEEE_754_64_BE
8983 #  elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_LE_BE
8984 #    define NV_NAN_PAYLOAD_MASK \
8985        NV_NAN_PAYLOAD_MASK_IEEE_754_64_LE
8986 #    define NV_NAN_PAYLOAD_PERM \
8987        NV_NAN_PAYLOAD_PERM_IEEE_754_64_LE
8988 #  elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_BE_LE
8989 #    define NV_NAN_PAYLOAD_MASK \
8990        NV_NAN_PAYLOAD_MASK_SKIP_EIGHT, NV_NAN_PAYLOAD_MASK_IEEE_754_64_BE
8991 #    define NV_NAN_PAYLOAD_PERM \
8992        NV_NAN_PAYLOAD_PERM_SKIP_EIGHT, NV_NAN_PAYLOAD_PERM_IEEE_754_64_BE
8993 #  else
8994 #    error "Unexpected long double format"
8995 #  endif
8996 #else
8997 #  ifdef USE_QUADMATH /* quadmath is not long double */
8998 #    ifdef NV_LITTLE_ENDIAN
8999 #      define NV_NAN_PAYLOAD_MASK NV_NAN_PAYLOAD_MASK_IEEE_754_128_LE
9000 #      define NV_NAN_PAYLOAD_PERM NV_NAN_PAYLOAD_PERM_IEEE_754_128_LE
9001 #    elif defined(NV_BIG_ENDIAN)
9002 #      define NV_NAN_PAYLOAD_MASK NV_NAN_PAYLOAD_MASK_IEEE_754_128_BE
9003 #      define NV_NAN_PAYLOAD_PERM NV_NAN_PAYLOAD_PERM_IEEE_754_128_BE
9004 #    else
9005 #      error "Unexpected quadmath format"
9006 #    endif
9007 #  elif DOUBLEKIND == DOUBLE_IS_IEEE_754_32_BIT_LITTLE_ENDIAN
9008 #    define NV_NAN_PAYLOAD_MASK 0xff, 0xff, 0x07, 0x00
9009 #    define NV_NAN_PAYLOAD_PERM 0x0, 0x1, 0x2, 0xFF
9010 #  elif DOUBLEKIND == DOUBLE_IS_IEEE_754_32_BIT_BIG_ENDIAN
9011 #    define NV_NAN_PAYLOAD_MASK 0x00, 0x07, 0xff, 0xff
9012 #    define NV_NAN_PAYLOAD_PERM 0xFF, 0x2, 0x1, 0x0
9013 #  elif DOUBLEKIND == DOUBLE_IS_IEEE_754_64_BIT_LITTLE_ENDIAN
9014 #    define NV_NAN_PAYLOAD_MASK NV_NAN_PAYLOAD_MASK_IEEE_754_64_LE
9015 #    define NV_NAN_PAYLOAD_PERM NV_NAN_PAYLOAD_PERM_IEEE_754_64_LE
9016 #  elif DOUBLEKIND == DOUBLE_IS_IEEE_754_64_BIT_BIG_ENDIAN
9017 #    define NV_NAN_PAYLOAD_MASK NV_NAN_PAYLOAD_MASK_IEEE_754_64_BE
9018 #    define NV_NAN_PAYLOAD_PERM NV_NAN_PAYLOAD_PERM_IEEE_754_64_BE
9019 #  elif DOUBLEKIND == DOUBLE_IS_IEEE_754_128_BIT_LITTLE_ENDIAN
9020 #    define NV_NAN_PAYLOAD_MASK NV_NAN_PAYLOAD_MASK_IEEE_754_128_LE
9021 #    define NV_NAN_PAYLOAD_PERM NV_NAN_PAYLOAD_PERM_IEEE_754_128_LE
9022 #  elif DOUBLEKIND == DOUBLE_IS_IEEE_754_128_BIT_BIG_ENDIAN
9023 #    define NV_NAN_PAYLOAD_MASK NV_NAN_PAYLOAD_MASK_IEEE_754_128_BE
9024 #    define NV_NAN_PAYLOAD_PERM NV_NAN_PAYLOAD_PERM_IEEE_754_128_BE
9025 #  elif DOUBLEKIND == DOUBLE_IS_IEEE_754_64_BIT_MIXED_ENDIAN_LE_BE
9026 #    define NV_NAN_PAYLOAD_MASK 0xff, 0xff, 0x07, 0x00, 0xff, 0xff, 0xff, 0xff
9027 #    define NV_NAN_PAYLOAD_PERM 0x4, 0x5, 0x6, 0xFF, 0x0, 0x1, 0x2, 0x3
9028 #  elif DOUBLEKIND == DOUBLE_IS_IEEE_754_64_BIT_MIXED_ENDIAN_BE_LE
9029 #    define NV_NAN_PAYLOAD_MASK 0xff, 0xff, 0xff, 0xff, 0x00, 0x07, 0xff, 0xff
9030 #    define NV_NAN_PAYLOAD_PERM 0x3, 0x2, 0x1, 0x0, 0xFF, 0x6, 0x5, 0x4
9031 #  else
9032 #    error "Unexpected double format"
9033 #  endif
9034 #endif
9035
9036 #endif /* DOUBLE_HAS_NAN */
9037
9038 /* these are used to faciliate the env var PERL_RAND_SEED,
9039  * which allows consistent behavior from code that calls
9040  * srand() with no arguments, either explicitly or implicitly.
9041  */
9042 #define PERL_SRAND_OVERRIDE_NEXT() PERL_XORSHIFT32_A(PL_srand_override_next);
9043
9044 #define PERL_SRAND_OVERRIDE_NEXT_INIT() STMT_START {    \
9045     PL_srand_override = PL_srand_override_next;         \
9046     PERL_SRAND_OVERRIDE_NEXT();                         \
9047 } STMT_END
9048
9049 #define PERL_SRAND_OVERRIDE_GET(into) STMT_START {      \
9050     into= PL_srand_override;                            \
9051     PERL_SRAND_OVERRIDE_NEXT_INIT();                    \
9052 } STMT_END
9053
9054 #define PERL_SRAND_OVERRIDE_NEXT_CHILD() STMT_START {   \
9055     PERL_XORSHIFT32_B(PL_srand_override_next);          \
9056     PERL_SRAND_OVERRIDE_NEXT_INIT();                    \
9057 } STMT_END
9058
9059 #define PERL_SRAND_OVERRIDE_NEXT_PARENT() \
9060     PERL_SRAND_OVERRIDE_NEXT()
9061
9062 /* in something like
9063  *
9064  * perl -le'sub f { eval "BEGIN{ f() }" }'
9065  *
9066  * Each iteration chews up 8 stacks frames, and we will eventually SEGV
9067  * due to C stack overflow.
9068  *
9069  * This define provides a maximum limit to prevent the SEGV. Such code is
9070  * unusual, so it unlikely we need a very large number here.
9071  */
9072 #ifndef PERL_MAX_NESTED_EVAL_BEGIN_BLOCKS_DEFAULT
9073 #define PERL_MAX_NESTED_EVAL_BEGIN_BLOCKS_DEFAULT 1000
9074 #endif
9075 /* ${^MAX_NESTED_EVAL_BEGIN_BLOCKS} */
9076 #define PERL_VAR_MAX_NESTED_EVAL_BEGIN_BLOCKS "\015AX_NESTED_EVAL_BEGIN_BLOCKS"
9077
9078 /* Defines like this make it easier to do porting/diag.t. They are no-
9079  * ops that return their argument which can be used to hint to diag.t
9080  * that a string is actually an error message. By putting the category
9081  * information into the macro name it considerably simplifies extended
9082  * diag.t to support these cases. Feel free to add more.
9083  *
9084  * While it seems tempting to try to convert all of our diagnostics to
9085  * this format, it would miss part of the point of diag.t in that it
9086  * detects NEW diagnostics, which would not necessarily use these
9087  * macros. The macros instead exist where we know we have an error
9088  * message that isnt being picked up by diag.t because it is declared
9089  * as a string independently of the function it is fed to, something
9090  * diag.t can never handle right without help.
9091  */
9092 #define PERL_DIAG_STR_(x)           ("" x "")
9093 #define PERL_DIAG_WARN_SYNTAX(x)    PERL_DIAG_STR_(x)
9094 #define PERL_DIAG_DIE_SYNTAX(x)     PERL_DIAG_STR_(x)
9095
9096 #ifndef PERL_STOP_PARSING_AFTER_N_ERRORS
9097 #define PERL_STOP_PARSING_AFTER_N_ERRORS 10
9098 #endif
9099
9100 #define PERL_PARSE_ERROR_COUNT(f)     (f)
9101
9102 /*
9103
9104    (KEEP THIS LAST IN perl.h!)
9105
9106    Mention
9107
9108    NV_PRESERVES_UV
9109
9110    HAS_MKSTEMP
9111    HAS_MKSTEMPS
9112    HAS_MKDTEMP
9113
9114    HAS_GETCWD
9115
9116    HAS_MMAP
9117    HAS_MPROTECT
9118    HAS_MSYNC
9119    HAS_MADVISE
9120    HAS_MUNMAP
9121    I_SYSMMAN
9122    Mmap_t
9123
9124    NVef
9125    NVff
9126    NVgf
9127
9128    HAS_UALARM
9129    HAS_USLEEP
9130
9131    HAS_SETITIMER
9132    HAS_GETITIMER
9133
9134    HAS_SENDMSG
9135    HAS_RECVMSG
9136    HAS_READV
9137    HAS_WRITEV
9138    I_SYSUIO
9139    HAS_STRUCT_MSGHDR
9140    HAS_STRUCT_CMSGHDR
9141
9142    HAS_NL_LANGINFO
9143
9144    HAS_DIRFD
9145
9146    so that Configure picks them up.
9147
9148    (KEEP THIS LAST IN perl.h!)
9149
9150 */
9151
9152 #endif /* Include guard */
9153
9154 /*
9155  * ex: set ts=8 sts=4 sw=4 et:
9156  */