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